blob: e80795caccfd553a2686612d842a294ab00cb39e [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"
42#include "llvm/Support/raw_ostream.h"
43#include "llvm/Transforms/Utils/Cloning.h"
David Neto22f144c2017-06-12 14:26:21 -040044
David Neto85082642018-03-24 06:55:20 -070045#include "spirv/1.0/spirv.hpp"
David Neto118188e2018-08-24 11:27:54 -040046
David Neto85082642018-03-24 06:55:20 -070047#include "clspv/AddressSpace.h"
alan-bakerf5e5f692018-11-27 08:33:24 -050048#include "clspv/DescriptorMap.h"
David Neto118188e2018-08-24 11:27:54 -040049#include "clspv/Option.h"
David Neto85082642018-03-24 06:55:20 -070050#include "clspv/spirv_c_strings.hpp"
51#include "clspv/spirv_glsl.hpp"
David Neto22f144c2017-06-12 14:26:21 -040052
David Neto4feb7a42017-10-06 17:29:42 -040053#include "ArgKind.h"
alan-bakerf67468c2019-11-25 15:51:49 -050054#include "Builtins.h"
alan-baker06cad652019-12-03 17:56:47 -050055#include "ComputeStructuredOrder.h"
David Neto85082642018-03-24 06:55:20 -070056#include "ConstantEmitter.h"
Alan Baker202c8c72018-08-13 13:47:44 -040057#include "Constants.h"
David Neto78383442018-06-15 20:31:56 -040058#include "DescriptorCounter.h"
alan-baker56f7aff2019-05-22 08:06:42 -040059#include "NormalizeGlobalVariable.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040060#include "Passes.h"
alan-bakerce179f12019-12-06 19:02:22 -050061#include "Types.h"
David Neto48f56a42017-10-06 16:44:25 -040062
David Neto22f144c2017-06-12 14:26:21 -040063#if defined(_MSC_VER)
64#pragma warning(pop)
65#endif
66
67using namespace llvm;
68using namespace clspv;
David Neto156783e2017-07-05 15:39:41 -040069using namespace mdconst;
David Neto22f144c2017-06-12 14:26:21 -040070
71namespace {
David Netocd8ca5f2017-10-02 23:34:11 -040072
David Neto862b7d82018-06-14 18:48:37 -040073cl::opt<bool> ShowResourceVars("show-rv", cl::init(false), cl::Hidden,
74 cl::desc("Show resource variable creation"));
75
76// These hacks exist to help transition code generation algorithms
77// without making huge noise in detailed test output.
78const bool Hack_generate_runtime_array_stride_early = true;
79
David Neto3fbb4072017-10-16 11:28:14 -040080// The value of 1/pi. This value is from MSDN
81// https://msdn.microsoft.com/en-us/library/4hwaceh6.aspx
82const double kOneOverPi = 0.318309886183790671538;
83const glsl::ExtInst kGlslExtInstBad = static_cast<glsl::ExtInst>(0);
84
alan-bakerb6b09dc2018-11-08 16:59:28 -050085const char *kCompositeConstructFunctionPrefix = "clspv.composite_construct.";
David Netoab03f432017-11-03 17:00:44 -040086
David Neto22f144c2017-06-12 14:26:21 -040087enum SPIRVOperandType {
88 NUMBERID,
89 LITERAL_INTEGER,
90 LITERAL_STRING,
91 LITERAL_FLOAT
92};
93
94struct SPIRVOperand {
95 explicit SPIRVOperand(SPIRVOperandType Ty, uint32_t Num)
96 : Type(Ty), LiteralNum(1, Num) {}
97 explicit SPIRVOperand(SPIRVOperandType Ty, const char *Str)
98 : Type(Ty), LiteralStr(Str) {}
99 explicit SPIRVOperand(SPIRVOperandType Ty, StringRef Str)
100 : Type(Ty), LiteralStr(Str) {}
101 explicit SPIRVOperand(SPIRVOperandType Ty, ArrayRef<uint32_t> NumVec)
102 : Type(Ty), LiteralNum(NumVec.begin(), NumVec.end()) {}
103
James Price11010dc2019-12-19 13:53:09 -0500104 SPIRVOperandType getType() const { return Type; };
105 uint32_t getNumID() const { return LiteralNum[0]; };
106 std::string getLiteralStr() const { return LiteralStr; };
107 ArrayRef<uint32_t> getLiteralNum() const { return LiteralNum; };
David Neto22f144c2017-06-12 14:26:21 -0400108
David Neto87846742018-04-11 17:36:22 -0400109 uint32_t GetNumWords() const {
110 switch (Type) {
111 case NUMBERID:
112 return 1;
113 case LITERAL_INTEGER:
114 case LITERAL_FLOAT:
David Netoee2660d2018-06-28 16:31:29 -0400115 return uint32_t(LiteralNum.size());
David Neto87846742018-04-11 17:36:22 -0400116 case LITERAL_STRING:
117 // Account for the terminating null character.
David Netoee2660d2018-06-28 16:31:29 -0400118 return uint32_t((LiteralStr.size() + 4) / 4);
David Neto87846742018-04-11 17:36:22 -0400119 }
120 llvm_unreachable("Unhandled case in SPIRVOperand::GetNumWords()");
121 }
122
David Neto22f144c2017-06-12 14:26:21 -0400123private:
124 SPIRVOperandType Type;
125 std::string LiteralStr;
126 SmallVector<uint32_t, 4> LiteralNum;
127};
128
David Netoc6f3ab22018-04-06 18:02:31 -0400129class SPIRVOperandList {
130public:
David Netoef5ba2b2019-12-20 08:35:54 -0500131 typedef std::unique_ptr<SPIRVOperand> element_type;
132 typedef SmallVector<element_type, 8> container_type;
133 typedef container_type::iterator iterator;
David Netoc6f3ab22018-04-06 18:02:31 -0400134 SPIRVOperandList() {}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500135 SPIRVOperandList(const SPIRVOperandList &other) = delete;
136 SPIRVOperandList(SPIRVOperandList &&other) {
David Netoc6f3ab22018-04-06 18:02:31 -0400137 contents_ = std::move(other.contents_);
138 other.contents_.clear();
139 }
David Netoef5ba2b2019-12-20 08:35:54 -0500140 iterator begin() { return contents_.begin(); }
141 iterator end() { return contents_.end(); }
142 operator ArrayRef<element_type>() { return contents_; }
143 void push_back(element_type op) { contents_.push_back(std::move(op)); }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500144 void clear() { contents_.clear(); }
David Netoc6f3ab22018-04-06 18:02:31 -0400145 size_t size() const { return contents_.size(); }
James Price11010dc2019-12-19 13:53:09 -0500146 const SPIRVOperand *operator[](size_t i) { return contents_[i].get(); }
David Netoc6f3ab22018-04-06 18:02:31 -0400147
David Netoef5ba2b2019-12-20 08:35:54 -0500148 const container_type &getOperands() const { return contents_; }
David Neto87846742018-04-11 17:36:22 -0400149
David Netoc6f3ab22018-04-06 18:02:31 -0400150private:
David Netoef5ba2b2019-12-20 08:35:54 -0500151 container_type contents_;
David Netoc6f3ab22018-04-06 18:02:31 -0400152};
153
James Price11010dc2019-12-19 13:53:09 -0500154SPIRVOperandList &operator<<(SPIRVOperandList &list,
David Netoef5ba2b2019-12-20 08:35:54 -0500155 std::unique_ptr<SPIRVOperand> elem) {
156 list.push_back(std::move(elem));
David Netoc6f3ab22018-04-06 18:02:31 -0400157 return list;
158}
159
David Netoef5ba2b2019-12-20 08:35:54 -0500160std::unique_ptr<SPIRVOperand> MkNum(uint32_t num) {
161 return std::make_unique<SPIRVOperand>(LITERAL_INTEGER, num);
David Netoc6f3ab22018-04-06 18:02:31 -0400162}
David Netoef5ba2b2019-12-20 08:35:54 -0500163std::unique_ptr<SPIRVOperand> MkInteger(ArrayRef<uint32_t> num_vec) {
164 return std::make_unique<SPIRVOperand>(LITERAL_INTEGER, num_vec);
David Neto257c3892018-04-11 13:19:45 -0400165}
David Netoef5ba2b2019-12-20 08:35:54 -0500166std::unique_ptr<SPIRVOperand> MkFloat(ArrayRef<uint32_t> num_vec) {
167 return std::make_unique<SPIRVOperand>(LITERAL_FLOAT, num_vec);
David Neto257c3892018-04-11 13:19:45 -0400168}
David Netoef5ba2b2019-12-20 08:35:54 -0500169std::unique_ptr<SPIRVOperand> MkId(uint32_t id) {
170 return std::make_unique<SPIRVOperand>(NUMBERID, id);
James Price11010dc2019-12-19 13:53:09 -0500171}
David Netoef5ba2b2019-12-20 08:35:54 -0500172std::unique_ptr<SPIRVOperand> MkString(StringRef str) {
173 return std::make_unique<SPIRVOperand>(LITERAL_STRING, str);
David Neto257c3892018-04-11 13:19:45 -0400174}
David Netoc6f3ab22018-04-06 18:02:31 -0400175
David Neto22f144c2017-06-12 14:26:21 -0400176struct SPIRVInstruction {
David Netoef5ba2b2019-12-20 08:35:54 -0500177 // Creates an instruction with an opcode and no result ID, and with the given
178 // operands. This computes its own word count. Takes ownership of the
179 // operands and clears |Ops|.
180 SPIRVInstruction(spv::Op Opc, SPIRVOperandList &Ops)
181 : WordCount(1), Opcode(static_cast<uint16_t>(Opc)), ResultID(0) {
James Price11010dc2019-12-19 13:53:09 -0500182 for (auto &operand : Ops) {
David Netoee2660d2018-06-28 16:31:29 -0400183 WordCount += uint16_t(operand->GetNumWords());
David Neto87846742018-04-11 17:36:22 -0400184 }
David Netoef5ba2b2019-12-20 08:35:54 -0500185 Operands.reserve(Ops.size());
186 for (auto &ptr : Ops) {
187 Operands.emplace_back(std::move(ptr));
188 ptr.reset(nullptr);
David Neto87846742018-04-11 17:36:22 -0400189 }
David Netoef5ba2b2019-12-20 08:35:54 -0500190 Ops.clear();
191 }
192 // Creates an instruction with an opcode and a no-zero result ID, and
193 // with the given operands. This computes its own word count. Takes ownership
194 // of the operands and clears |Ops|.
195 SPIRVInstruction(spv::Op Opc, uint32_t ResID, SPIRVOperandList &Ops)
196 : WordCount(2), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID) {
James Price11010dc2019-12-19 13:53:09 -0500197 for (auto &operand : Ops) {
David Neto87846742018-04-11 17:36:22 -0400198 WordCount += operand->GetNumWords();
199 }
David Netoef5ba2b2019-12-20 08:35:54 -0500200 Operands.reserve(Ops.size());
201 for (auto &ptr : Ops) {
202 Operands.emplace_back(std::move(ptr));
203 ptr.reset(nullptr);
204 }
205 if (ResID == 0) {
206 llvm_unreachable("Result ID of 0 was provided");
207 }
208 Ops.clear();
David Neto87846742018-04-11 17:36:22 -0400209 }
David Neto22f144c2017-06-12 14:26:21 -0400210
David Netoef5ba2b2019-12-20 08:35:54 -0500211 // Creates an instruction with an opcode and no result ID, and with the single
212 // operand. This computes its own word count.
213 SPIRVInstruction(spv::Op Opc, SPIRVOperandList::element_type operand)
214 : WordCount(1), Opcode(static_cast<uint16_t>(Opc)), ResultID(0) {
215 WordCount += operand->GetNumWords();
216 Operands.emplace_back(std::move(operand));
217 operand.reset(nullptr);
218 }
219 // Creates an instruction with an opcode and a non-zero result ID, and
220 // with the single operand. This computes its own word count.
221 SPIRVInstruction(spv::Op Opc, uint32_t ResID,
222 SPIRVOperandList::element_type operand)
223 : WordCount(2), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID) {
224 WordCount += operand->GetNumWords();
225 if (ResID == 0) {
226 llvm_unreachable("Result ID of 0 was provided");
227 }
228 Operands.emplace_back(std::move(operand));
229 operand.reset(nullptr);
230 }
231 // Creates an instruction with an opcode and a no-zero result ID, and no
232 // operands.
233 SPIRVInstruction(spv::Op Opc, uint32_t ResID)
234 : WordCount(2), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID) {
235 if (ResID == 0) {
236 llvm_unreachable("Result ID of 0 was provided");
237 }
238 }
239 // Creates an instruction with an opcode, no result ID, no type ID, and no
240 // operands.
241 SPIRVInstruction(spv::Op Opc)
242 : WordCount(1), Opcode(static_cast<uint16_t>(Opc)), ResultID(0) {}
243
David Netoee2660d2018-06-28 16:31:29 -0400244 uint32_t getWordCount() const { return WordCount; }
David Neto22f144c2017-06-12 14:26:21 -0400245 uint16_t getOpcode() const { return Opcode; }
246 uint32_t getResultID() const { return ResultID; }
David Netoef5ba2b2019-12-20 08:35:54 -0500247 ArrayRef<std::unique_ptr<SPIRVOperand>> getOperands() const {
James Price11010dc2019-12-19 13:53:09 -0500248 return Operands;
249 }
David Neto22f144c2017-06-12 14:26:21 -0400250
251private:
David Netoee2660d2018-06-28 16:31:29 -0400252 uint32_t WordCount; // Check the 16-bit bound at code generation time.
David Neto22f144c2017-06-12 14:26:21 -0400253 uint16_t Opcode;
254 uint32_t ResultID;
David Netoef5ba2b2019-12-20 08:35:54 -0500255 SmallVector<std::unique_ptr<SPIRVOperand>, 4> Operands;
David Neto22f144c2017-06-12 14:26:21 -0400256};
257
258struct SPIRVProducerPass final : public ModulePass {
David Neto22f144c2017-06-12 14:26:21 -0400259 typedef DenseMap<Type *, uint32_t> TypeMapType;
260 typedef UniqueVector<Type *> TypeList;
261 typedef DenseMap<Value *, uint32_t> ValueMapType;
David Netofb9a7972017-08-25 17:08:24 -0400262 typedef UniqueVector<Value *> ValueList;
David Neto22f144c2017-06-12 14:26:21 -0400263 typedef std::vector<std::pair<Value *, uint32_t>> EntryPointVecType;
264 typedef std::list<SPIRVInstruction *> SPIRVInstructionList;
David Neto87846742018-04-11 17:36:22 -0400265 // A vector of tuples, each of which is:
266 // - the LLVM instruction that we will later generate SPIR-V code for
267 // - where the SPIR-V instruction should be inserted
268 // - the result ID of the SPIR-V instruction
David Neto22f144c2017-06-12 14:26:21 -0400269 typedef std::vector<
270 std::tuple<Value *, SPIRVInstructionList::iterator, uint32_t>>
271 DeferredInstVecType;
272 typedef DenseMap<FunctionType *, std::pair<FunctionType *, uint32_t>>
273 GlobalConstFuncMapType;
274
David Neto44795152017-07-13 15:45:28 -0400275 explicit SPIRVProducerPass(
alan-bakerf5e5f692018-11-27 08:33:24 -0500276 raw_pwrite_stream &out,
277 std::vector<clspv::version0::DescriptorMapEntry> *descriptor_map_entries,
alan-baker00e7a582019-06-07 12:54:21 -0400278 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
David Neto44795152017-07-13 15:45:28 -0400279 bool outputCInitList)
David Netoc2c368d2017-06-30 16:50:17 -0400280 : ModulePass(ID), samplerMap(samplerMap), out(out),
David Neto0676e6f2017-07-11 18:47:44 -0400281 binaryTempOut(binaryTempUnderlyingVector), binaryOut(&out),
alan-baker00e7a582019-06-07 12:54:21 -0400282 descriptorMapEntries(descriptor_map_entries),
David Neto0676e6f2017-07-11 18:47:44 -0400283 outputCInitList(outputCInitList), patchBoundOffset(0), nextID(1),
alan-baker5b86ed72019-02-15 08:26:50 -0500284 OpExtInstImportID(0), HasVariablePointersStorageBuffer(false),
285 HasVariablePointers(false), SamplerTy(nullptr), WorkgroupSizeValueID(0),
Kévin Petit89a525c2019-06-15 08:13:07 +0100286 WorkgroupSizeVarID(0), max_local_spec_id_(0) {}
David Neto22f144c2017-06-12 14:26:21 -0400287
James Price11010dc2019-12-19 13:53:09 -0500288 virtual ~SPIRVProducerPass() {
289 for (auto *Inst : SPIRVInsts) {
290 delete Inst;
291 }
292 }
293
David Neto22f144c2017-06-12 14:26:21 -0400294 void getAnalysisUsage(AnalysisUsage &AU) const override {
295 AU.addRequired<DominatorTreeWrapperPass>();
296 AU.addRequired<LoopInfoWrapperPass>();
297 }
298
299 virtual bool runOnModule(Module &module) override;
300
301 // output the SPIR-V header block
302 void outputHeader();
303
304 // patch the SPIR-V header block
305 void patchHeader();
306
307 uint32_t lookupType(Type *Ty) {
308 if (Ty->isPointerTy() &&
309 (Ty->getPointerAddressSpace() != AddressSpace::UniformConstant)) {
310 auto PointeeTy = Ty->getPointerElementType();
311 if (PointeeTy->isStructTy() &&
312 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
313 Ty = PointeeTy;
314 }
315 }
316
David Neto862b7d82018-06-14 18:48:37 -0400317 auto where = TypeMap.find(Ty);
318 if (where == TypeMap.end()) {
319 if (Ty) {
320 errs() << "Unhandled type " << *Ty << "\n";
321 } else {
322 errs() << "Unhandled type (null)\n";
323 }
David Netoe439d702018-03-23 13:14:08 -0700324 llvm_unreachable("\nUnhandled type!");
David Neto22f144c2017-06-12 14:26:21 -0400325 }
326
David Neto862b7d82018-06-14 18:48:37 -0400327 return where->second;
David Neto22f144c2017-06-12 14:26:21 -0400328 }
329 TypeMapType &getImageTypeMap() { return ImageTypeMap; }
alan-bakerabd82722019-12-03 17:14:51 -0500330 TypeList &getImageTypeList() { return ImageTypeList; }
David Neto22f144c2017-06-12 14:26:21 -0400331 TypeList &getTypeList() { return Types; };
332 ValueList &getConstantList() { return Constants; };
333 ValueMapType &getValueMap() { return ValueMap; }
334 ValueMapType &getAllocatedValueMap() { return AllocatedValueMap; }
335 SPIRVInstructionList &getSPIRVInstList() { return SPIRVInsts; };
David Neto22f144c2017-06-12 14:26:21 -0400336 EntryPointVecType &getEntryPointVec() { return EntryPointVec; };
337 DeferredInstVecType &getDeferredInstVec() { return DeferredInstVec; };
338 ValueList &getEntryPointInterfacesVec() { return EntryPointInterfacesVec; };
339 uint32_t &getOpExtInstImportID() { return OpExtInstImportID; };
340 std::vector<uint32_t> &getBuiltinDimVec() { return BuiltinDimensionVec; };
alan-baker5b86ed72019-02-15 08:26:50 -0500341 bool hasVariablePointersStorageBuffer() {
342 return HasVariablePointersStorageBuffer;
343 }
344 void setVariablePointersStorageBuffer(bool Val) {
345 HasVariablePointersStorageBuffer = Val;
346 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400347 bool hasVariablePointers() { return HasVariablePointers; };
David Neto22f144c2017-06-12 14:26:21 -0400348 void setVariablePointers(bool Val) { HasVariablePointers = Val; };
alan-bakerb6b09dc2018-11-08 16:59:28 -0500349 ArrayRef<std::pair<unsigned, std::string>> &getSamplerMap() {
350 return samplerMap;
351 }
David Neto22f144c2017-06-12 14:26:21 -0400352 GlobalConstFuncMapType &getGlobalConstFuncTypeMap() {
353 return GlobalConstFuncTypeMap;
354 }
355 SmallPtrSet<Value *, 16> &getGlobalConstArgSet() {
356 return GlobalConstArgumentSet;
357 }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500358 TypeList &getTypesNeedingArrayStride() { return TypesNeedingArrayStride; }
David Neto22f144c2017-06-12 14:26:21 -0400359
David Netoc6f3ab22018-04-06 18:02:31 -0400360 void GenerateLLVMIRInfo(Module &M, const DataLayout &DL);
alan-bakerb6b09dc2018-11-08 16:59:28 -0500361 // Populate GlobalConstFuncTypeMap. Also, if module-scope __constant will
362 // *not* be converted to a storage buffer, replace each such global variable
363 // with one in the storage class expecgted by SPIR-V.
David Neto862b7d82018-06-14 18:48:37 -0400364 void FindGlobalConstVars(Module &M, const DataLayout &DL);
365 // Populate ResourceVarInfoList, FunctionToResourceVarsMap, and
366 // ModuleOrderedResourceVars.
367 void FindResourceVars(Module &M, const DataLayout &DL);
Alan Baker202c8c72018-08-13 13:47:44 -0400368 void FindWorkgroupVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400369 bool FindExtInst(Module &M);
370 void FindTypePerGlobalVar(GlobalVariable &GV);
371 void FindTypePerFunc(Function &F);
David Neto862b7d82018-06-14 18:48:37 -0400372 void FindTypesForSamplerMap(Module &M);
373 void FindTypesForResourceVars(Module &M);
alan-bakerb6b09dc2018-11-08 16:59:28 -0500374 // Inserts |Ty| and relevant sub-types into the |Types| member, indicating
375 // that |Ty| and its subtypes will need a corresponding SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400376 void FindType(Type *Ty);
377 void FindConstantPerGlobalVar(GlobalVariable &GV);
378 void FindConstantPerFunc(Function &F);
379 void FindConstant(Value *V);
380 void GenerateExtInstImport();
David Neto19a1bad2017-08-25 15:01:41 -0400381 // Generates instructions for SPIR-V types corresponding to the LLVM types
382 // saved in the |Types| member. A type follows its subtypes. IDs are
383 // allocated sequentially starting with the current value of nextID, and
384 // with a type following its subtypes. Also updates nextID to just beyond
385 // the last generated ID.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500386 void GenerateSPIRVTypes(LLVMContext &context, Module &module);
David Neto22f144c2017-06-12 14:26:21 -0400387 void GenerateSPIRVConstants();
David Neto5c22a252018-03-15 16:07:41 -0400388 void GenerateModuleInfo(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400389 void GenerateGlobalVar(GlobalVariable &GV);
David Netoc6f3ab22018-04-06 18:02:31 -0400390 void GenerateWorkgroupVars();
David Neto862b7d82018-06-14 18:48:37 -0400391 // Generate descriptor map entries for resource variables associated with
392 // arguments to F.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500393 void GenerateDescriptorMapInfo(const DataLayout &DL, Function &F);
David Neto22f144c2017-06-12 14:26:21 -0400394 void GenerateSamplers(Module &M);
David Neto862b7d82018-06-14 18:48:37 -0400395 // Generate OpVariables for %clspv.resource.var.* calls.
396 void GenerateResourceVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400397 void GenerateFuncPrologue(Function &F);
398 void GenerateFuncBody(Function &F);
David Netob6e2e062018-04-25 10:32:06 -0400399 void GenerateEntryPointInitialStores();
David Neto22f144c2017-06-12 14:26:21 -0400400 spv::Op GetSPIRVCmpOpcode(CmpInst *CmpI);
401 spv::Op GetSPIRVCastOpcode(Instruction &I);
402 spv::Op GetSPIRVBinaryOpcode(Instruction &I);
403 void GenerateInstruction(Instruction &I);
404 void GenerateFuncEpilogue();
405 void HandleDeferredInstruction();
alan-bakerb6b09dc2018-11-08 16:59:28 -0500406 void HandleDeferredDecorations(const DataLayout &DL);
David Neto22f144c2017-06-12 14:26:21 -0400407 bool is4xi8vec(Type *Ty) const;
408 spv::StorageClass GetStorageClass(unsigned AddrSpace) const;
David Neto862b7d82018-06-14 18:48:37 -0400409 spv::StorageClass GetStorageClassForArgKind(clspv::ArgKind arg_kind) const;
David Neto22f144c2017-06-12 14:26:21 -0400410 spv::BuiltIn GetBuiltin(StringRef globalVarName) const;
David Neto3fbb4072017-10-16 11:28:14 -0400411 // Returns the GLSL extended instruction enum that the given function
412 // call maps to. If none, then returns the 0 value, i.e. GLSLstd4580Bad.
David Neto22f144c2017-06-12 14:26:21 -0400413 glsl::ExtInst getExtInstEnum(StringRef Name);
David Neto3fbb4072017-10-16 11:28:14 -0400414 // Returns the GLSL extended instruction enum indirectly used by the given
415 // function. That is, to implement the given function, we use an extended
416 // instruction plus one more instruction. If none, then returns the 0 value,
417 // i.e. GLSLstd4580Bad.
418 glsl::ExtInst getIndirectExtInstEnum(StringRef Name);
419 // Returns the single GLSL extended instruction used directly or
420 // indirectly by the given function call.
421 glsl::ExtInst getDirectOrIndirectExtInstEnum(StringRef Name);
David Neto22f144c2017-06-12 14:26:21 -0400422 void WriteOneWord(uint32_t Word);
423 void WriteResultID(SPIRVInstruction *Inst);
424 void WriteWordCountAndOpcode(SPIRVInstruction *Inst);
David Netoef5ba2b2019-12-20 08:35:54 -0500425 void WriteOperand(const std::unique_ptr<SPIRVOperand> &Op);
David Neto22f144c2017-06-12 14:26:21 -0400426 void WriteSPIRVBinary();
427
Alan Baker9bf93fb2018-08-28 16:59:26 -0400428 // Returns true if |type| is compatible with OpConstantNull.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500429 bool IsTypeNullable(const Type *type) const;
Alan Baker9bf93fb2018-08-28 16:59:26 -0400430
Alan Bakerfcda9482018-10-02 17:09:59 -0400431 // Populate UBO remapped type maps.
432 void PopulateUBOTypeMaps(Module &module);
433
alan-baker06cad652019-12-03 17:56:47 -0500434 // Populate the merge and continue block maps.
435 void PopulateStructuredCFGMaps(Module &module);
436
Alan Bakerfcda9482018-10-02 17:09:59 -0400437 // Wrapped methods of DataLayout accessors. If |type| was remapped for UBOs,
438 // uses the internal map, otherwise it falls back on the data layout.
439 uint64_t GetTypeSizeInBits(Type *type, const DataLayout &DL);
440 uint64_t GetTypeStoreSize(Type *type, const DataLayout &DL);
441 uint64_t GetTypeAllocSize(Type *type, const DataLayout &DL);
442
alan-baker5b86ed72019-02-15 08:26:50 -0500443 // Returns the base pointer of |v|.
444 Value *GetBasePointer(Value *v);
445
446 // Sets |HasVariablePointersStorageBuffer| or |HasVariablePointers| base on
447 // |address_space|.
448 void setVariablePointersCapabilities(unsigned address_space);
449
450 // Returns true if |lhs| and |rhs| represent the same resource or workgroup
451 // variable.
452 bool sameResource(Value *lhs, Value *rhs) const;
453
454 // Returns true if |inst| is phi or select that selects from the same
455 // structure (or null).
456 bool selectFromSameObject(Instruction *inst);
457
alan-bakere9308012019-03-15 10:25:13 -0400458 // Returns true if |Arg| is called with a coherent resource.
459 bool CalledWithCoherentResource(Argument &Arg);
460
David Neto22f144c2017-06-12 14:26:21 -0400461private:
462 static char ID;
David Neto44795152017-07-13 15:45:28 -0400463 ArrayRef<std::pair<unsigned, std::string>> samplerMap;
David Neto22f144c2017-06-12 14:26:21 -0400464 raw_pwrite_stream &out;
David Neto0676e6f2017-07-11 18:47:44 -0400465
466 // TODO(dneto): Wouldn't it be better to always just emit a binary, and then
467 // convert to other formats on demand?
468
469 // When emitting a C initialization list, the WriteSPIRVBinary method
470 // will actually write its words to this vector via binaryTempOut.
471 SmallVector<char, 100> binaryTempUnderlyingVector;
472 raw_svector_ostream binaryTempOut;
473
474 // Binary output writes to this stream, which might be |out| or
475 // |binaryTempOut|. It's the latter when we really want to write a C
476 // initializer list.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400477 raw_pwrite_stream *binaryOut;
alan-bakerf5e5f692018-11-27 08:33:24 -0500478 std::vector<version0::DescriptorMapEntry> *descriptorMapEntries;
David Neto0676e6f2017-07-11 18:47:44 -0400479 const bool outputCInitList; // If true, output look like {0x7023, ... , 5}
David Neto22f144c2017-06-12 14:26:21 -0400480 uint64_t patchBoundOffset;
481 uint32_t nextID;
482
alan-bakerf67468c2019-11-25 15:51:49 -0500483 // ID for OpTypeInt 32 1.
484 uint32_t int32ID = 0;
485 // ID for OpTypeVector %int 4.
486 uint32_t v4int32ID = 0;
487
David Neto19a1bad2017-08-25 15:01:41 -0400488 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400489 TypeMapType TypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400490 // Maps an LLVM image type to its SPIR-V ID.
David Neto22f144c2017-06-12 14:26:21 -0400491 TypeMapType ImageTypeMap;
alan-bakerabd82722019-12-03 17:14:51 -0500492 // A unique-vector of LLVM image types. This list is used to provide
493 // deterministic traversal of image types.
494 TypeList ImageTypeList;
David Neto19a1bad2017-08-25 15:01:41 -0400495 // A unique-vector of LLVM types that map to a SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400496 TypeList Types;
497 ValueList Constants;
David Neto19a1bad2017-08-25 15:01:41 -0400498 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400499 ValueMapType ValueMap;
500 ValueMapType AllocatedValueMap;
501 SPIRVInstructionList SPIRVInsts;
David Neto862b7d82018-06-14 18:48:37 -0400502
David Neto22f144c2017-06-12 14:26:21 -0400503 EntryPointVecType EntryPointVec;
504 DeferredInstVecType DeferredInstVec;
505 ValueList EntryPointInterfacesVec;
506 uint32_t OpExtInstImportID;
507 std::vector<uint32_t> BuiltinDimensionVec;
alan-baker5b86ed72019-02-15 08:26:50 -0500508 bool HasVariablePointersStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -0400509 bool HasVariablePointers;
510 Type *SamplerTy;
alan-baker09cb9802019-12-10 13:16:27 -0500511 DenseMap<unsigned, unsigned> SamplerLiteralToIDMap;
David Netoc77d9e22018-03-24 06:30:28 -0700512
513 // If a function F has a pointer-to-__constant parameter, then this variable
David Neto9ed8e2f2018-03-24 06:47:24 -0700514 // will map F's type to (G, index of the parameter), where in a first phase
515 // G is F's type. During FindTypePerFunc, G will be changed to F's type
516 // but replacing the pointer-to-constant parameter with
517 // pointer-to-ModuleScopePrivate.
David Netoc77d9e22018-03-24 06:30:28 -0700518 // TODO(dneto): This doesn't seem general enough? A function might have
519 // more than one such parameter.
David Neto22f144c2017-06-12 14:26:21 -0400520 GlobalConstFuncMapType GlobalConstFuncTypeMap;
521 SmallPtrSet<Value *, 16> GlobalConstArgumentSet;
David Neto1a1a0582017-07-07 12:01:44 -0400522 // An ordered set of pointer types of Base arguments to OpPtrAccessChain,
David Neto85082642018-03-24 06:55:20 -0700523 // or array types, and which point into transparent memory (StorageBuffer
524 // storage class). These will require an ArrayStride decoration.
David Neto1a1a0582017-07-07 12:01:44 -0400525 // See SPV_KHR_variable_pointers rev 13.
David Neto85082642018-03-24 06:55:20 -0700526 TypeList TypesNeedingArrayStride;
David Netoa60b00b2017-09-15 16:34:09 -0400527
528 // This is truly ugly, but works around what look like driver bugs.
529 // For get_local_size, an earlier part of the flow has created a module-scope
530 // variable in Private address space to hold the value for the workgroup
531 // size. Its intializer is a uint3 value marked as builtin WorkgroupSize.
532 // When this is present, save the IDs of the initializer value and variable
533 // in these two variables. We only ever do a vector load from it, and
534 // when we see one of those, substitute just the value of the intializer.
535 // This mimics what Glslang does, and that's what drivers are used to.
David Neto66cfe642018-03-24 06:13:56 -0700536 // TODO(dneto): Remove this once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -0400537 uint32_t WorkgroupSizeValueID;
538 uint32_t WorkgroupSizeVarID;
David Neto26aaf622017-10-23 18:11:53 -0400539
David Neto862b7d82018-06-14 18:48:37 -0400540 // Bookkeeping for mapping kernel arguments to resource variables.
541 struct ResourceVarInfo {
542 ResourceVarInfo(int index_arg, unsigned set_arg, unsigned binding_arg,
alan-bakere9308012019-03-15 10:25:13 -0400543 Function *fn, clspv::ArgKind arg_kind_arg, int coherent_arg)
David Neto862b7d82018-06-14 18:48:37 -0400544 : index(index_arg), descriptor_set(set_arg), binding(binding_arg),
alan-bakere9308012019-03-15 10:25:13 -0400545 var_fn(fn), arg_kind(arg_kind_arg), coherent(coherent_arg),
David Neto862b7d82018-06-14 18:48:37 -0400546 addr_space(fn->getReturnType()->getPointerAddressSpace()) {}
547 const int index; // Index into ResourceVarInfoList
548 const unsigned descriptor_set;
549 const unsigned binding;
550 Function *const var_fn; // The @clspv.resource.var.* function.
551 const clspv::ArgKind arg_kind;
alan-bakere9308012019-03-15 10:25:13 -0400552 const int coherent;
David Neto862b7d82018-06-14 18:48:37 -0400553 const unsigned addr_space; // The LLVM address space
554 // The SPIR-V ID of the OpVariable. Not populated at construction time.
555 uint32_t var_id = 0;
556 };
557 // A list of resource var info. Each one correponds to a module-scope
558 // resource variable we will have to create. Resource var indices are
559 // indices into this vector.
560 SmallVector<std::unique_ptr<ResourceVarInfo>, 8> ResourceVarInfoList;
561 // This is a vector of pointers of all the resource vars, but ordered by
562 // kernel function, and then by argument.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500563 UniqueVector<ResourceVarInfo *> ModuleOrderedResourceVars;
David Neto862b7d82018-06-14 18:48:37 -0400564 // Map a function to the ordered list of resource variables it uses, one for
565 // each argument. If an argument does not use a resource variable, it
566 // will have a null pointer entry.
567 using FunctionToResourceVarsMapType =
568 DenseMap<Function *, SmallVector<ResourceVarInfo *, 8>>;
569 FunctionToResourceVarsMapType FunctionToResourceVarsMap;
570
571 // What LLVM types map to SPIR-V types needing layout? These are the
572 // arrays and structures supporting storage buffers and uniform buffers.
573 TypeList TypesNeedingLayout;
574 // What LLVM struct types map to a SPIR-V struct type with Block decoration?
575 UniqueVector<StructType *> StructTypesNeedingBlock;
576 // For a call that represents a load from an opaque type (samplers, images),
577 // map it to the variable id it should load from.
578 DenseMap<CallInst *, uint32_t> ResourceVarDeferredLoadCalls;
David Neto85082642018-03-24 06:55:20 -0700579
Alan Baker202c8c72018-08-13 13:47:44 -0400580 // One larger than the maximum used SpecId for pointer-to-local arguments.
581 int max_local_spec_id_;
David Netoc6f3ab22018-04-06 18:02:31 -0400582 // An ordered list of the kernel arguments of type pointer-to-local.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500583 using LocalArgList = SmallVector<Argument *, 8>;
David Netoc6f3ab22018-04-06 18:02:31 -0400584 LocalArgList LocalArgs;
585 // Information about a pointer-to-local argument.
586 struct LocalArgInfo {
587 // The SPIR-V ID of the array variable.
588 uint32_t variable_id;
589 // The element type of the
alan-bakerb6b09dc2018-11-08 16:59:28 -0500590 Type *elem_type;
David Netoc6f3ab22018-04-06 18:02:31 -0400591 // The ID of the array type.
592 uint32_t array_size_id;
593 // The ID of the array type.
594 uint32_t array_type_id;
595 // The ID of the pointer to the array type.
596 uint32_t ptr_array_type_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400597 // The specialization constant ID of the array size.
598 int spec_id;
599 };
Alan Baker202c8c72018-08-13 13:47:44 -0400600 // A mapping from Argument to its assigned SpecId.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500601 DenseMap<const Argument *, int> LocalArgSpecIds;
Alan Baker202c8c72018-08-13 13:47:44 -0400602 // A mapping from SpecId to its LocalArgInfo.
603 DenseMap<int, LocalArgInfo> LocalSpecIdInfoMap;
Alan Bakerfcda9482018-10-02 17:09:59 -0400604 // A mapping from a remapped type to its real offsets.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500605 DenseMap<Type *, std::vector<uint32_t>> RemappedUBOTypeOffsets;
Alan Bakerfcda9482018-10-02 17:09:59 -0400606 // A mapping from a remapped type to its real sizes.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500607 DenseMap<Type *, std::tuple<uint64_t, uint64_t, uint64_t>>
608 RemappedUBOTypeSizes;
alan-baker06cad652019-12-03 17:56:47 -0500609
610 // Maps basic block to its merge block.
611 DenseMap<BasicBlock *, BasicBlock *> MergeBlocks;
612 // Maps basic block to its continue block.
613 DenseMap<BasicBlock *, BasicBlock *> ContinueBlocks;
David Neto22f144c2017-06-12 14:26:21 -0400614};
615
616char SPIRVProducerPass::ID;
David Netoc6f3ab22018-04-06 18:02:31 -0400617
alan-bakerb6b09dc2018-11-08 16:59:28 -0500618} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400619
620namespace clspv {
alan-bakerf5e5f692018-11-27 08:33:24 -0500621ModulePass *createSPIRVProducerPass(
622 raw_pwrite_stream &out,
623 std::vector<version0::DescriptorMapEntry> *descriptor_map_entries,
alan-baker00e7a582019-06-07 12:54:21 -0400624 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
alan-bakerf5e5f692018-11-27 08:33:24 -0500625 bool outputCInitList) {
626 return new SPIRVProducerPass(out, descriptor_map_entries, samplerMap,
alan-baker00e7a582019-06-07 12:54:21 -0400627 outputCInitList);
David Neto22f144c2017-06-12 14:26:21 -0400628}
David Netoc2c368d2017-06-30 16:50:17 -0400629} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400630
631bool SPIRVProducerPass::runOnModule(Module &module) {
David Neto0676e6f2017-07-11 18:47:44 -0400632 binaryOut = outputCInitList ? &binaryTempOut : &out;
633
Alan Bakerfcda9482018-10-02 17:09:59 -0400634 PopulateUBOTypeMaps(module);
alan-baker06cad652019-12-03 17:56:47 -0500635 PopulateStructuredCFGMaps(module);
Alan Bakerfcda9482018-10-02 17:09:59 -0400636
David Neto22f144c2017-06-12 14:26:21 -0400637 // SPIR-V always begins with its header information
638 outputHeader();
639
David Netoc6f3ab22018-04-06 18:02:31 -0400640 const DataLayout &DL = module.getDataLayout();
641
David Neto22f144c2017-06-12 14:26:21 -0400642 // Gather information from the LLVM IR that we require.
David Netoc6f3ab22018-04-06 18:02:31 -0400643 GenerateLLVMIRInfo(module, DL);
David Neto22f144c2017-06-12 14:26:21 -0400644
David Neto22f144c2017-06-12 14:26:21 -0400645 // Collect information on global variables too.
646 for (GlobalVariable &GV : module.globals()) {
647 // If the GV is one of our special __spirv_* variables, remove the
648 // initializer as it was only placed there to force LLVM to not throw the
649 // value away.
650 if (GV.getName().startswith("__spirv_")) {
651 GV.setInitializer(nullptr);
652 }
653
654 // Collect types' information from global variable.
655 FindTypePerGlobalVar(GV);
656
657 // Collect constant information from global variable.
658 FindConstantPerGlobalVar(GV);
659
660 // If the variable is an input, entry points need to know about it.
661 if (AddressSpace::Input == GV.getType()->getPointerAddressSpace()) {
David Netofb9a7972017-08-25 17:08:24 -0400662 getEntryPointInterfacesVec().insert(&GV);
David Neto22f144c2017-06-12 14:26:21 -0400663 }
664 }
665
666 // If there are extended instructions, generate OpExtInstImport.
667 if (FindExtInst(module)) {
668 GenerateExtInstImport();
669 }
670
671 // Generate SPIRV instructions for types.
Alan Bakerfcda9482018-10-02 17:09:59 -0400672 GenerateSPIRVTypes(module.getContext(), module);
David Neto22f144c2017-06-12 14:26:21 -0400673
674 // Generate SPIRV constants.
675 GenerateSPIRVConstants();
676
alan-baker09cb9802019-12-10 13:16:27 -0500677 // Generate literal samplers if necessary.
678 GenerateSamplers(module);
David Neto22f144c2017-06-12 14:26:21 -0400679
680 // Generate SPIRV variables.
681 for (GlobalVariable &GV : module.globals()) {
682 GenerateGlobalVar(GV);
683 }
David Neto862b7d82018-06-14 18:48:37 -0400684 GenerateResourceVars(module);
David Netoc6f3ab22018-04-06 18:02:31 -0400685 GenerateWorkgroupVars();
David Neto22f144c2017-06-12 14:26:21 -0400686
687 // Generate SPIRV instructions for each function.
688 for (Function &F : module) {
689 if (F.isDeclaration()) {
690 continue;
691 }
692
David Neto862b7d82018-06-14 18:48:37 -0400693 GenerateDescriptorMapInfo(DL, F);
694
David Neto22f144c2017-06-12 14:26:21 -0400695 // Generate Function Prologue.
696 GenerateFuncPrologue(F);
697
698 // Generate SPIRV instructions for function body.
699 GenerateFuncBody(F);
700
701 // Generate Function Epilogue.
702 GenerateFuncEpilogue();
703 }
704
705 HandleDeferredInstruction();
David Neto1a1a0582017-07-07 12:01:44 -0400706 HandleDeferredDecorations(DL);
David Neto22f144c2017-06-12 14:26:21 -0400707
708 // Generate SPIRV module information.
David Neto5c22a252018-03-15 16:07:41 -0400709 GenerateModuleInfo(module);
David Neto22f144c2017-06-12 14:26:21 -0400710
alan-baker00e7a582019-06-07 12:54:21 -0400711 WriteSPIRVBinary();
David Neto22f144c2017-06-12 14:26:21 -0400712
713 // We need to patch the SPIR-V header to set bound correctly.
714 patchHeader();
David Neto0676e6f2017-07-11 18:47:44 -0400715
716 if (outputCInitList) {
717 bool first = true;
David Neto0676e6f2017-07-11 18:47:44 -0400718 std::ostringstream os;
719
David Neto57fb0b92017-08-04 15:35:09 -0400720 auto emit_word = [&os, &first](uint32_t word) {
David Neto0676e6f2017-07-11 18:47:44 -0400721 if (!first)
David Neto57fb0b92017-08-04 15:35:09 -0400722 os << ",\n";
723 os << word;
David Neto0676e6f2017-07-11 18:47:44 -0400724 first = false;
725 };
726
727 os << "{";
David Neto57fb0b92017-08-04 15:35:09 -0400728 const std::string str(binaryTempOut.str());
729 for (unsigned i = 0; i < str.size(); i += 4) {
730 const uint32_t a = static_cast<unsigned char>(str[i]);
731 const uint32_t b = static_cast<unsigned char>(str[i + 1]);
732 const uint32_t c = static_cast<unsigned char>(str[i + 2]);
733 const uint32_t d = static_cast<unsigned char>(str[i + 3]);
734 emit_word(a | (b << 8) | (c << 16) | (d << 24));
David Neto0676e6f2017-07-11 18:47:44 -0400735 }
736 os << "}\n";
737 out << os.str();
738 }
739
David Neto22f144c2017-06-12 14:26:21 -0400740 return false;
741}
742
743void SPIRVProducerPass::outputHeader() {
alan-baker00e7a582019-06-07 12:54:21 -0400744 binaryOut->write(reinterpret_cast<const char *>(&spv::MagicNumber),
745 sizeof(spv::MagicNumber));
746 binaryOut->write(reinterpret_cast<const char *>(&spv::Version),
747 sizeof(spv::Version));
David Neto22f144c2017-06-12 14:26:21 -0400748
alan-baker0c18ab02019-06-12 10:23:21 -0400749 // use Google's vendor ID
750 const uint32_t vendor = 21 << 16;
alan-baker00e7a582019-06-07 12:54:21 -0400751 binaryOut->write(reinterpret_cast<const char *>(&vendor), sizeof(vendor));
David Neto22f144c2017-06-12 14:26:21 -0400752
alan-baker00e7a582019-06-07 12:54:21 -0400753 // we record where we need to come back to and patch in the bound value
754 patchBoundOffset = binaryOut->tell();
David Neto22f144c2017-06-12 14:26:21 -0400755
alan-baker00e7a582019-06-07 12:54:21 -0400756 // output a bad bound for now
757 binaryOut->write(reinterpret_cast<const char *>(&nextID), sizeof(nextID));
David Neto22f144c2017-06-12 14:26:21 -0400758
alan-baker00e7a582019-06-07 12:54:21 -0400759 // output the schema (reserved for use and must be 0)
760 const uint32_t schema = 0;
761 binaryOut->write(reinterpret_cast<const char *>(&schema), sizeof(schema));
David Neto22f144c2017-06-12 14:26:21 -0400762}
763
764void SPIRVProducerPass::patchHeader() {
alan-baker00e7a582019-06-07 12:54:21 -0400765 // for a binary we just write the value of nextID over bound
766 binaryOut->pwrite(reinterpret_cast<char *>(&nextID), sizeof(nextID),
767 patchBoundOffset);
David Neto22f144c2017-06-12 14:26:21 -0400768}
769
David Netoc6f3ab22018-04-06 18:02:31 -0400770void SPIRVProducerPass::GenerateLLVMIRInfo(Module &M, const DataLayout &DL) {
David Neto22f144c2017-06-12 14:26:21 -0400771 // This function generates LLVM IR for function such as global variable for
772 // argument, constant and pointer type for argument access. These information
773 // is artificial one because we need Vulkan SPIR-V output. This function is
774 // executed ahead of FindType and FindConstant.
David Neto22f144c2017-06-12 14:26:21 -0400775 LLVMContext &Context = M.getContext();
776
David Neto862b7d82018-06-14 18:48:37 -0400777 FindGlobalConstVars(M, DL);
David Neto5c22a252018-03-15 16:07:41 -0400778
David Neto862b7d82018-06-14 18:48:37 -0400779 FindResourceVars(M, DL);
David Neto22f144c2017-06-12 14:26:21 -0400780
781 bool HasWorkGroupBuiltin = false;
782 for (GlobalVariable &GV : M.globals()) {
783 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
784 if (spv::BuiltInWorkgroupSize == BuiltinType) {
785 HasWorkGroupBuiltin = true;
786 }
787 }
788
David Neto862b7d82018-06-14 18:48:37 -0400789 FindTypesForSamplerMap(M);
790 FindTypesForResourceVars(M);
Alan Baker202c8c72018-08-13 13:47:44 -0400791 FindWorkgroupVars(M);
David Neto22f144c2017-06-12 14:26:21 -0400792
793 for (Function &F : M) {
Kévin Petitabef4522019-03-27 13:08:01 +0000794 if (F.isDeclaration()) {
David Neto22f144c2017-06-12 14:26:21 -0400795 continue;
796 }
797
798 for (BasicBlock &BB : F) {
799 for (Instruction &I : BB) {
800 if (I.getOpcode() == Instruction::ZExt ||
801 I.getOpcode() == Instruction::SExt ||
802 I.getOpcode() == Instruction::UIToFP) {
803 // If there is zext with i1 type, it will be changed to OpSelect. The
804 // OpSelect needs constant 0 and 1 so the constants are added here.
805
806 auto OpTy = I.getOperand(0)->getType();
807
Kévin Petit24272b62018-10-18 19:16:12 +0000808 if (OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -0400809 if (I.getOpcode() == Instruction::ZExt) {
David Neto22f144c2017-06-12 14:26:21 -0400810 FindConstant(Constant::getNullValue(I.getType()));
Kévin Petit7bfb8992019-02-26 13:45:08 +0000811 FindConstant(ConstantInt::get(I.getType(), 1));
David Neto22f144c2017-06-12 14:26:21 -0400812 } else if (I.getOpcode() == Instruction::SExt) {
David Neto22f144c2017-06-12 14:26:21 -0400813 FindConstant(Constant::getNullValue(I.getType()));
Kévin Petit7bfb8992019-02-26 13:45:08 +0000814 FindConstant(ConstantInt::getSigned(I.getType(), -1));
David Neto22f144c2017-06-12 14:26:21 -0400815 } else {
816 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
817 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
818 }
819 }
820 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
David Neto862b7d82018-06-14 18:48:37 -0400821 StringRef callee_name = Call->getCalledFunction()->getName();
David Neto22f144c2017-06-12 14:26:21 -0400822
823 // Handle image type specially.
alan-bakerf67468c2019-11-25 15:51:49 -0500824 if (clspv::IsSampledImageRead(callee_name)) {
David Neto22f144c2017-06-12 14:26:21 -0400825 TypeMapType &OpImageTypeMap = getImageTypeMap();
826 Type *ImageTy =
827 Call->getArgOperand(0)->getType()->getPointerElementType();
828 OpImageTypeMap[ImageTy] = 0;
alan-bakerabd82722019-12-03 17:14:51 -0500829 getImageTypeList().insert(ImageTy);
David Neto22f144c2017-06-12 14:26:21 -0400830
alan-bakerf67468c2019-11-25 15:51:49 -0500831 // All sampled reads need a floating point 0 for the Lod operand.
David Neto22f144c2017-06-12 14:26:21 -0400832 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
833 }
David Neto5c22a252018-03-15 16:07:41 -0400834
alan-bakerce179f12019-12-06 19:02:22 -0500835 if (clspv::IsImageQuery(callee_name)) {
836 Type *ImageTy = Call->getOperand(0)->getType();
837 const uint32_t dim = ImageDimensionality(ImageTy);
838 uint32_t components = dim;
839 if (components > 1) {
840 // OpImageQuerySize* return |components| components.
841 FindType(VectorType::get(Type::getInt32Ty(Context), components));
842 if (dim == 3 && IsGetImageDim(callee_name)) {
843 // get_image_dim for 3D images returns an int4.
844 FindType(
845 VectorType::get(Type::getInt32Ty(Context), components + 1));
846 }
847 }
848
849 if (clspv::IsSampledImageType(ImageTy)) {
850 // All sampled image queries need a integer 0 for the Lod
851 // operand.
852 FindConstant(ConstantInt::get(Context, APInt(32, 0)));
853 }
David Neto5c22a252018-03-15 16:07:41 -0400854 }
David Neto22f144c2017-06-12 14:26:21 -0400855 }
856 }
857 }
858
Kévin Petitabef4522019-03-27 13:08:01 +0000859 // More things to do on kernel functions
860 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
861 if (const MDNode *MD =
862 dyn_cast<Function>(&F)->getMetadata("reqd_work_group_size")) {
863 // We generate constants if the WorkgroupSize builtin is being used.
864 if (HasWorkGroupBuiltin) {
865 // Collect constant information for work group size.
866 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(0)));
867 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(1)));
868 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(2)));
David Neto22f144c2017-06-12 14:26:21 -0400869 }
870 }
871 }
872
alan-bakerf67468c2019-11-25 15:51:49 -0500873 // TODO(alan-baker): make this better.
alan-bakerf906d2b2019-12-10 11:26:23 -0500874 if (M.getTypeByName("opencl.image1d_ro_t.float") ||
875 M.getTypeByName("opencl.image1d_ro_t.float.sampled") ||
876 M.getTypeByName("opencl.image1d_wo_t.float") ||
877 M.getTypeByName("opencl.image2d_ro_t.float") ||
alan-bakerf67468c2019-11-25 15:51:49 -0500878 M.getTypeByName("opencl.image2d_ro_t.float.sampled") ||
879 M.getTypeByName("opencl.image2d_wo_t.float") ||
880 M.getTypeByName("opencl.image3d_ro_t.float") ||
881 M.getTypeByName("opencl.image3d_ro_t.float.sampled") ||
882 M.getTypeByName("opencl.image3d_wo_t.float")) {
883 FindType(Type::getFloatTy(Context));
alan-bakerf906d2b2019-12-10 11:26:23 -0500884 } else if (M.getTypeByName("opencl.image1d_ro_t.uint") ||
885 M.getTypeByName("opencl.image1d_ro_t.uint.sampled") ||
886 M.getTypeByName("opencl.image1d_wo_t.uint") ||
887 M.getTypeByName("opencl.image2d_ro_t.uint") ||
alan-bakerf67468c2019-11-25 15:51:49 -0500888 M.getTypeByName("opencl.image2d_ro_t.uint.sampled") ||
889 M.getTypeByName("opencl.image2d_wo_t.uint") ||
890 M.getTypeByName("opencl.image3d_ro_t.uint") ||
891 M.getTypeByName("opencl.image3d_ro_t.uint.sampled") ||
892 M.getTypeByName("opencl.image3d_wo_t.uint")) {
893 FindType(Type::getInt32Ty(Context));
alan-bakerf906d2b2019-12-10 11:26:23 -0500894 } else if (M.getTypeByName("opencl.image1d_ro_t.int") ||
895 M.getTypeByName("opencl.image1d_ro_t.int.sampled") ||
896 M.getTypeByName("opencl.image1d_wo_t.int") ||
897 M.getTypeByName("opencl.image2d_ro_t.int") ||
alan-bakerf67468c2019-11-25 15:51:49 -0500898 M.getTypeByName("opencl.image2d_ro_t.int.sampled") ||
899 M.getTypeByName("opencl.image2d_wo_t.int") ||
900 M.getTypeByName("opencl.image3d_ro_t.int") ||
901 M.getTypeByName("opencl.image3d_ro_t.int.sampled") ||
902 M.getTypeByName("opencl.image3d_wo_t.int")) {
903 // Nothing for now...
904 } else {
905 // This was likely an UndefValue.
David Neto22f144c2017-06-12 14:26:21 -0400906 FindType(Type::getFloatTy(Context));
907 }
908
909 // Collect types' information from function.
910 FindTypePerFunc(F);
911
912 // Collect constant information from function.
913 FindConstantPerFunc(F);
914 }
915}
916
David Neto862b7d82018-06-14 18:48:37 -0400917void SPIRVProducerPass::FindGlobalConstVars(Module &M, const DataLayout &DL) {
alan-baker56f7aff2019-05-22 08:06:42 -0400918 clspv::NormalizeGlobalVariables(M);
919
David Neto862b7d82018-06-14 18:48:37 -0400920 SmallVector<GlobalVariable *, 8> GVList;
921 SmallVector<GlobalVariable *, 8> DeadGVList;
922 for (GlobalVariable &GV : M.globals()) {
923 if (GV.getType()->getAddressSpace() == AddressSpace::Constant) {
924 if (GV.use_empty()) {
925 DeadGVList.push_back(&GV);
926 } else {
927 GVList.push_back(&GV);
928 }
929 }
930 }
931
932 // Remove dead global __constant variables.
933 for (auto GV : DeadGVList) {
934 GV->eraseFromParent();
935 }
936 DeadGVList.clear();
937
938 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
939 // For now, we only support a single storage buffer.
940 if (GVList.size() > 0) {
941 assert(GVList.size() == 1);
942 const auto *GV = GVList[0];
943 const auto constants_byte_size =
Alan Bakerfcda9482018-10-02 17:09:59 -0400944 (GetTypeSizeInBits(GV->getInitializer()->getType(), DL)) / 8;
David Neto862b7d82018-06-14 18:48:37 -0400945 const size_t kConstantMaxSize = 65536;
946 if (constants_byte_size > kConstantMaxSize) {
947 outs() << "Max __constant capacity of " << kConstantMaxSize
948 << " bytes exceeded: " << constants_byte_size << " bytes used\n";
949 llvm_unreachable("Max __constant capacity exceeded");
950 }
951 }
952 } else {
953 // Change global constant variable's address space to ModuleScopePrivate.
954 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
955 for (auto GV : GVList) {
956 // Create new gv with ModuleScopePrivate address space.
957 Type *NewGVTy = GV->getType()->getPointerElementType();
958 GlobalVariable *NewGV = new GlobalVariable(
959 M, NewGVTy, false, GV->getLinkage(), GV->getInitializer(), "",
960 nullptr, GV->getThreadLocalMode(), AddressSpace::ModuleScopePrivate);
961 NewGV->takeName(GV);
962
963 const SmallVector<User *, 8> GVUsers(GV->user_begin(), GV->user_end());
964 SmallVector<User *, 8> CandidateUsers;
965
966 auto record_called_function_type_as_user =
967 [&GlobalConstFuncTyMap](Value *gv, CallInst *call) {
968 // Find argument index.
969 unsigned index = 0;
970 for (unsigned i = 0; i < call->getNumArgOperands(); i++) {
971 if (gv == call->getOperand(i)) {
972 // TODO(dneto): Should we break here?
973 index = i;
974 }
975 }
976
977 // Record function type with global constant.
978 GlobalConstFuncTyMap[call->getFunctionType()] =
979 std::make_pair(call->getFunctionType(), index);
980 };
981
982 for (User *GVU : GVUsers) {
983 if (CallInst *Call = dyn_cast<CallInst>(GVU)) {
984 record_called_function_type_as_user(GV, Call);
985 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(GVU)) {
986 // Check GEP users.
987 for (User *GEPU : GEP->users()) {
988 if (CallInst *GEPCall = dyn_cast<CallInst>(GEPU)) {
989 record_called_function_type_as_user(GEP, GEPCall);
990 }
991 }
992 }
993
994 CandidateUsers.push_back(GVU);
995 }
996
997 for (User *U : CandidateUsers) {
998 // Update users of gv with new gv.
alan-bakered80f572019-02-11 17:28:26 -0500999 if (!isa<Constant>(U)) {
1000 // #254: Can't change operands of a constant, but this shouldn't be
1001 // something that sticks around in the module.
1002 U->replaceUsesOfWith(GV, NewGV);
1003 }
David Neto862b7d82018-06-14 18:48:37 -04001004 }
1005
1006 // Delete original gv.
1007 GV->eraseFromParent();
1008 }
1009 }
1010}
1011
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001012void SPIRVProducerPass::FindResourceVars(Module &M, const DataLayout &) {
David Neto862b7d82018-06-14 18:48:37 -04001013 ResourceVarInfoList.clear();
1014 FunctionToResourceVarsMap.clear();
1015 ModuleOrderedResourceVars.reset();
1016 // Normally, there is one resource variable per clspv.resource.var.*
1017 // function, since that is unique'd by arg type and index. By design,
1018 // we can share these resource variables across kernels because all
1019 // kernels use the same descriptor set.
1020 //
1021 // But if the user requested distinct descriptor sets per kernel, then
1022 // the descriptor allocator has made different (set,binding) pairs for
1023 // the same (type,arg_index) pair. Since we can decorate a resource
1024 // variable with only exactly one DescriptorSet and Binding, we are
1025 // forced in this case to make distinct resource variables whenever
1026 // the same clspv.reource.var.X function is seen with disintct
1027 // (set,binding) values.
1028 const bool always_distinct_sets =
1029 clspv::Option::DistinctKernelDescriptorSets();
1030 for (Function &F : M) {
1031 // Rely on the fact the resource var functions have a stable ordering
1032 // in the module.
Alan Baker202c8c72018-08-13 13:47:44 -04001033 if (F.getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001034 // Find all calls to this function with distinct set and binding pairs.
1035 // Save them in ResourceVarInfoList.
1036
1037 // Determine uniqueness of the (set,binding) pairs only withing this
1038 // one resource-var builtin function.
1039 using SetAndBinding = std::pair<unsigned, unsigned>;
1040 // Maps set and binding to the resource var info.
1041 DenseMap<SetAndBinding, ResourceVarInfo *> set_and_binding_map;
1042 bool first_use = true;
1043 for (auto &U : F.uses()) {
1044 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
1045 const auto set = unsigned(
1046 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
1047 const auto binding = unsigned(
1048 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
1049 const auto arg_kind = clspv::ArgKind(
1050 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
1051 const auto arg_index = unsigned(
1052 dyn_cast<ConstantInt>(call->getArgOperand(3))->getZExtValue());
alan-bakere9308012019-03-15 10:25:13 -04001053 const auto coherent = unsigned(
1054 dyn_cast<ConstantInt>(call->getArgOperand(5))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04001055
1056 // Find or make the resource var info for this combination.
1057 ResourceVarInfo *rv = nullptr;
1058 if (always_distinct_sets) {
1059 // Make a new resource var any time we see a different
1060 // (set,binding) pair.
1061 SetAndBinding key{set, binding};
1062 auto where = set_and_binding_map.find(key);
1063 if (where == set_and_binding_map.end()) {
1064 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
alan-bakere9308012019-03-15 10:25:13 -04001065 binding, &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001066 ResourceVarInfoList.emplace_back(rv);
1067 set_and_binding_map[key] = rv;
1068 } else {
1069 rv = where->second;
1070 }
1071 } else {
1072 // The default is to make exactly one resource for each
1073 // clspv.resource.var.* function.
1074 if (first_use) {
1075 first_use = false;
1076 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
alan-bakere9308012019-03-15 10:25:13 -04001077 binding, &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001078 ResourceVarInfoList.emplace_back(rv);
1079 } else {
1080 rv = ResourceVarInfoList.back().get();
1081 }
1082 }
1083
1084 // Now populate FunctionToResourceVarsMap.
1085 auto &mapping =
1086 FunctionToResourceVarsMap[call->getParent()->getParent()];
1087 while (mapping.size() <= arg_index) {
1088 mapping.push_back(nullptr);
1089 }
1090 mapping[arg_index] = rv;
1091 }
1092 }
1093 }
1094 }
1095
1096 // Populate ModuleOrderedResourceVars.
1097 for (Function &F : M) {
1098 auto where = FunctionToResourceVarsMap.find(&F);
1099 if (where != FunctionToResourceVarsMap.end()) {
1100 for (auto &rv : where->second) {
1101 if (rv != nullptr) {
1102 ModuleOrderedResourceVars.insert(rv);
1103 }
1104 }
1105 }
1106 }
1107 if (ShowResourceVars) {
1108 for (auto *info : ModuleOrderedResourceVars) {
1109 outs() << "MORV index " << info->index << " (" << info->descriptor_set
1110 << "," << info->binding << ") " << *(info->var_fn->getReturnType())
1111 << "\n";
1112 }
1113 }
1114}
1115
David Neto22f144c2017-06-12 14:26:21 -04001116bool SPIRVProducerPass::FindExtInst(Module &M) {
1117 LLVMContext &Context = M.getContext();
1118 bool HasExtInst = false;
1119
1120 for (Function &F : M) {
1121 for (BasicBlock &BB : F) {
1122 for (Instruction &I : BB) {
1123 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1124 Function *Callee = Call->getCalledFunction();
1125 // Check whether this call is for extend instructions.
David Neto3fbb4072017-10-16 11:28:14 -04001126 auto callee_name = Callee->getName();
1127 const glsl::ExtInst EInst = getExtInstEnum(callee_name);
1128 const glsl::ExtInst IndirectEInst =
1129 getIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04001130
David Neto3fbb4072017-10-16 11:28:14 -04001131 HasExtInst |=
1132 (EInst != kGlslExtInstBad) || (IndirectEInst != kGlslExtInstBad);
1133
1134 if (IndirectEInst) {
1135 // Register extra constants if needed.
1136
1137 // Registers a type and constant for computing the result of the
1138 // given instruction. If the result of the instruction is a vector,
1139 // then make a splat vector constant with the same number of
1140 // elements.
1141 auto register_constant = [this, &I](Constant *constant) {
1142 FindType(constant->getType());
1143 FindConstant(constant);
1144 if (auto *vectorTy = dyn_cast<VectorType>(I.getType())) {
1145 // Register the splat vector of the value with the same
1146 // width as the result of the instruction.
1147 auto *vec_constant = ConstantVector::getSplat(
1148 static_cast<unsigned>(vectorTy->getNumElements()),
1149 constant);
1150 FindConstant(vec_constant);
1151 FindType(vec_constant->getType());
1152 }
1153 };
1154 switch (IndirectEInst) {
1155 case glsl::ExtInstFindUMsb:
1156 // clz needs OpExtInst and OpISub with constant 31, or splat
1157 // vector of 31. Add it to the constant list here.
1158 register_constant(
1159 ConstantInt::get(Type::getInt32Ty(Context), 31));
1160 break;
1161 case glsl::ExtInstAcos:
1162 case glsl::ExtInstAsin:
Kévin Petiteb9f90a2018-09-29 12:29:34 +01001163 case glsl::ExtInstAtan:
David Neto3fbb4072017-10-16 11:28:14 -04001164 case glsl::ExtInstAtan2:
1165 // We need 1/pi for acospi, asinpi, atan2pi.
1166 register_constant(
1167 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
1168 break;
1169 default:
1170 assert(false && "internally inconsistent");
1171 }
David Neto22f144c2017-06-12 14:26:21 -04001172 }
1173 }
1174 }
1175 }
1176 }
1177
1178 return HasExtInst;
1179}
1180
1181void SPIRVProducerPass::FindTypePerGlobalVar(GlobalVariable &GV) {
1182 // Investigate global variable's type.
1183 FindType(GV.getType());
1184}
1185
1186void SPIRVProducerPass::FindTypePerFunc(Function &F) {
1187 // Investigate function's type.
1188 FunctionType *FTy = F.getFunctionType();
1189
1190 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
1191 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
David Neto9ed8e2f2018-03-24 06:47:24 -07001192 // Handle a regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04001193 if (GlobalConstFuncTyMap.count(FTy)) {
1194 uint32_t GVCstArgIdx = GlobalConstFuncTypeMap[FTy].second;
1195 SmallVector<Type *, 4> NewFuncParamTys;
1196 for (unsigned i = 0; i < FTy->getNumParams(); i++) {
1197 Type *ParamTy = FTy->getParamType(i);
1198 if (i == GVCstArgIdx) {
1199 Type *EleTy = ParamTy->getPointerElementType();
1200 ParamTy = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1201 }
1202
1203 NewFuncParamTys.push_back(ParamTy);
1204 }
1205
1206 FunctionType *NewFTy =
1207 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1208 GlobalConstFuncTyMap[FTy] = std::make_pair(NewFTy, GVCstArgIdx);
1209 FTy = NewFTy;
1210 }
1211
1212 FindType(FTy);
1213 } else {
1214 // As kernel functions do not have parameters, create new function type and
1215 // add it to type map.
1216 SmallVector<Type *, 4> NewFuncParamTys;
1217 FunctionType *NewFTy =
1218 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1219 FindType(NewFTy);
1220 }
1221
1222 // Investigate instructions' type in function body.
1223 for (BasicBlock &BB : F) {
1224 for (Instruction &I : BB) {
1225 if (isa<ShuffleVectorInst>(I)) {
1226 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1227 // Ignore type for mask of shuffle vector instruction.
1228 if (i == 2) {
1229 continue;
1230 }
1231
1232 Value *Op = I.getOperand(i);
1233 if (!isa<MetadataAsValue>(Op)) {
1234 FindType(Op->getType());
1235 }
1236 }
1237
1238 FindType(I.getType());
1239 continue;
1240 }
1241
David Neto862b7d82018-06-14 18:48:37 -04001242 CallInst *Call = dyn_cast<CallInst>(&I);
1243
1244 if (Call && Call->getCalledFunction()->getName().startswith(
Alan Baker202c8c72018-08-13 13:47:44 -04001245 clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001246 // This is a fake call representing access to a resource variable.
1247 // We handle that elsewhere.
1248 continue;
1249 }
1250
Alan Baker202c8c72018-08-13 13:47:44 -04001251 if (Call && Call->getCalledFunction()->getName().startswith(
1252 clspv::WorkgroupAccessorFunction())) {
1253 // This is a fake call representing access to a workgroup variable.
1254 // We handle that elsewhere.
1255 continue;
1256 }
1257
David Neto22f144c2017-06-12 14:26:21 -04001258 // Work through the operands of the instruction.
1259 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1260 Value *const Op = I.getOperand(i);
1261 // If any of the operands is a constant, find the type!
1262 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1263 FindType(Op->getType());
1264 }
1265 }
1266
1267 for (Use &Op : I.operands()) {
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001268 if (isa<CallInst>(&I)) {
David Neto22f144c2017-06-12 14:26:21 -04001269 // Avoid to check call instruction's type.
1270 break;
1271 }
Alan Baker202c8c72018-08-13 13:47:44 -04001272 if (CallInst *OpCall = dyn_cast<CallInst>(Op)) {
1273 if (OpCall && OpCall->getCalledFunction()->getName().startswith(
1274 clspv::WorkgroupAccessorFunction())) {
1275 // This is a fake call representing access to a workgroup variable.
1276 // We handle that elsewhere.
1277 continue;
1278 }
1279 }
David Neto22f144c2017-06-12 14:26:21 -04001280 if (!isa<MetadataAsValue>(&Op)) {
1281 FindType(Op->getType());
1282 continue;
1283 }
1284 }
1285
David Neto22f144c2017-06-12 14:26:21 -04001286 // We don't want to track the type of this call as we are going to replace
1287 // it.
Kévin Petitdf71de32019-04-09 14:09:50 +01001288 if (Call && (clspv::LiteralSamplerFunction() ==
David Neto22f144c2017-06-12 14:26:21 -04001289 Call->getCalledFunction()->getName())) {
1290 continue;
1291 }
1292
1293 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1294 // If gep's base operand has ModuleScopePrivate address space, make gep
1295 // return ModuleScopePrivate address space.
1296 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate) {
1297 // Add pointer type with private address space for global constant to
1298 // type list.
1299 Type *EleTy = I.getType()->getPointerElementType();
1300 Type *NewPTy =
1301 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1302
1303 FindType(NewPTy);
1304 continue;
1305 }
1306 }
1307
1308 FindType(I.getType());
1309 }
1310 }
1311}
1312
David Neto862b7d82018-06-14 18:48:37 -04001313void SPIRVProducerPass::FindTypesForSamplerMap(Module &M) {
1314 // If we are using a sampler map, find the type of the sampler.
Kévin Petitdf71de32019-04-09 14:09:50 +01001315 if (M.getFunction(clspv::LiteralSamplerFunction()) ||
David Neto862b7d82018-06-14 18:48:37 -04001316 0 < getSamplerMap().size()) {
1317 auto SamplerStructTy = M.getTypeByName("opencl.sampler_t");
1318 if (!SamplerStructTy) {
1319 SamplerStructTy = StructType::create(M.getContext(), "opencl.sampler_t");
1320 }
1321
1322 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
1323
1324 FindType(SamplerTy);
1325 }
1326}
1327
1328void SPIRVProducerPass::FindTypesForResourceVars(Module &M) {
1329 // Record types so they are generated.
1330 TypesNeedingLayout.reset();
1331 StructTypesNeedingBlock.reset();
1332
1333 // To match older clspv codegen, generate the float type first if required
1334 // for images.
1335 for (const auto *info : ModuleOrderedResourceVars) {
1336 if (info->arg_kind == clspv::ArgKind::ReadOnlyImage ||
1337 info->arg_kind == clspv::ArgKind::WriteOnlyImage) {
alan-bakerf67468c2019-11-25 15:51:49 -05001338 if (IsIntImageType(info->var_fn->getReturnType())) {
1339 // Nothing for now...
1340 } else if (IsUintImageType(info->var_fn->getReturnType())) {
1341 FindType(Type::getInt32Ty(M.getContext()));
1342 }
1343
1344 // We need "float" either for the sampled type or for the Lod operand.
David Neto862b7d82018-06-14 18:48:37 -04001345 FindType(Type::getFloatTy(M.getContext()));
David Neto862b7d82018-06-14 18:48:37 -04001346 }
1347 }
1348
1349 for (const auto *info : ModuleOrderedResourceVars) {
1350 Type *type = info->var_fn->getReturnType();
1351
1352 switch (info->arg_kind) {
1353 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04001354 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04001355 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1356 StructTypesNeedingBlock.insert(sty);
1357 } else {
1358 errs() << *type << "\n";
1359 llvm_unreachable("Buffer arguments must map to structures!");
1360 }
1361 break;
1362 case clspv::ArgKind::Pod:
1363 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1364 StructTypesNeedingBlock.insert(sty);
1365 } else {
1366 errs() << *type << "\n";
1367 llvm_unreachable("POD arguments must map to structures!");
1368 }
1369 break;
1370 case clspv::ArgKind::ReadOnlyImage:
1371 case clspv::ArgKind::WriteOnlyImage:
1372 case clspv::ArgKind::Sampler:
1373 // Sampler and image types map to the pointee type but
1374 // in the uniform constant address space.
1375 type = PointerType::get(type->getPointerElementType(),
1376 clspv::AddressSpace::UniformConstant);
1377 break;
1378 default:
1379 break;
1380 }
1381
1382 // The converted type is the type of the OpVariable we will generate.
1383 // If the pointee type is an array of size zero, FindType will convert it
1384 // to a runtime array.
1385 FindType(type);
1386 }
1387
alan-bakerdcd97412019-09-16 15:32:30 -04001388 // If module constants are clustered in a storage buffer then that struct
1389 // needs layout decorations.
1390 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
1391 for (GlobalVariable &GV : M.globals()) {
1392 PointerType *PTy = cast<PointerType>(GV.getType());
1393 const auto AS = PTy->getAddressSpace();
1394 const bool module_scope_constant_external_init =
1395 (AS == AddressSpace::Constant) && GV.hasInitializer();
1396 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
1397 if (module_scope_constant_external_init &&
1398 spv::BuiltInMax == BuiltinType) {
1399 StructTypesNeedingBlock.insert(
1400 cast<StructType>(PTy->getPointerElementType()));
1401 }
1402 }
1403 }
1404
David Neto862b7d82018-06-14 18:48:37 -04001405 // Traverse the arrays and structures underneath each Block, and
1406 // mark them as needing layout.
1407 std::vector<Type *> work_list(StructTypesNeedingBlock.begin(),
1408 StructTypesNeedingBlock.end());
1409 while (!work_list.empty()) {
1410 Type *type = work_list.back();
1411 work_list.pop_back();
1412 TypesNeedingLayout.insert(type);
1413 switch (type->getTypeID()) {
1414 case Type::ArrayTyID:
1415 work_list.push_back(type->getArrayElementType());
1416 if (!Hack_generate_runtime_array_stride_early) {
1417 // Remember this array type for deferred decoration.
1418 TypesNeedingArrayStride.insert(type);
1419 }
1420 break;
1421 case Type::StructTyID:
1422 for (auto *elem_ty : cast<StructType>(type)->elements()) {
1423 work_list.push_back(elem_ty);
1424 }
1425 default:
1426 // This type and its contained types don't get layout.
1427 break;
1428 }
1429 }
1430}
1431
Alan Baker202c8c72018-08-13 13:47:44 -04001432void SPIRVProducerPass::FindWorkgroupVars(Module &M) {
1433 // The SpecId assignment for pointer-to-local arguments is recorded in
1434 // module-level metadata. Translate that information into local argument
1435 // information.
1436 NamedMDNode *nmd = M.getNamedMetadata(clspv::LocalSpecIdMetadataName());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001437 if (!nmd)
1438 return;
Alan Baker202c8c72018-08-13 13:47:44 -04001439 for (auto operand : nmd->operands()) {
1440 MDTuple *tuple = cast<MDTuple>(operand);
1441 ValueAsMetadata *fn_md = cast<ValueAsMetadata>(tuple->getOperand(0));
1442 Function *func = cast<Function>(fn_md->getValue());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001443 ConstantAsMetadata *arg_index_md =
1444 cast<ConstantAsMetadata>(tuple->getOperand(1));
1445 int arg_index = static_cast<int>(
1446 cast<ConstantInt>(arg_index_md->getValue())->getSExtValue());
1447 Argument *arg = &*(func->arg_begin() + arg_index);
Alan Baker202c8c72018-08-13 13:47:44 -04001448
1449 ConstantAsMetadata *spec_id_md =
1450 cast<ConstantAsMetadata>(tuple->getOperand(2));
alan-bakerb6b09dc2018-11-08 16:59:28 -05001451 int spec_id = static_cast<int>(
1452 cast<ConstantInt>(spec_id_md->getValue())->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04001453
1454 max_local_spec_id_ = std::max(max_local_spec_id_, spec_id + 1);
1455 LocalArgSpecIds[arg] = spec_id;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001456 if (LocalSpecIdInfoMap.count(spec_id))
1457 continue;
Alan Baker202c8c72018-08-13 13:47:44 -04001458
1459 // We haven't seen this SpecId yet, so generate the LocalArgInfo for it.
1460 LocalArgInfo info{nextID, arg->getType()->getPointerElementType(),
1461 nextID + 1, nextID + 2,
1462 nextID + 3, spec_id};
1463 LocalSpecIdInfoMap[spec_id] = info;
1464 nextID += 4;
1465
1466 // Ensure the types necessary for this argument get generated.
1467 Type *IdxTy = Type::getInt32Ty(M.getContext());
1468 FindConstant(ConstantInt::get(IdxTy, 0));
1469 FindType(IdxTy);
1470 FindType(arg->getType());
1471 }
1472}
1473
David Neto22f144c2017-06-12 14:26:21 -04001474void SPIRVProducerPass::FindType(Type *Ty) {
1475 TypeList &TyList = getTypeList();
1476
1477 if (0 != TyList.idFor(Ty)) {
1478 return;
1479 }
1480
1481 if (Ty->isPointerTy()) {
1482 auto AddrSpace = Ty->getPointerAddressSpace();
1483 if ((AddressSpace::Constant == AddrSpace) ||
1484 (AddressSpace::Global == AddrSpace)) {
1485 auto PointeeTy = Ty->getPointerElementType();
1486
1487 if (PointeeTy->isStructTy() &&
1488 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1489 FindType(PointeeTy);
1490 auto ActualPointerTy =
1491 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1492 FindType(ActualPointerTy);
1493 return;
1494 }
1495 }
1496 }
1497
David Neto862b7d82018-06-14 18:48:37 -04001498 // By convention, LLVM array type with 0 elements will map to
1499 // OpTypeRuntimeArray. Otherwise, it will map to OpTypeArray, which
1500 // has a constant number of elements. We need to support type of the
1501 // constant.
1502 if (auto *arrayTy = dyn_cast<ArrayType>(Ty)) {
1503 if (arrayTy->getNumElements() > 0) {
1504 LLVMContext &Context = Ty->getContext();
1505 FindType(Type::getInt32Ty(Context));
1506 }
David Neto22f144c2017-06-12 14:26:21 -04001507 }
1508
1509 for (Type *SubTy : Ty->subtypes()) {
1510 FindType(SubTy);
1511 }
1512
1513 TyList.insert(Ty);
1514}
1515
1516void SPIRVProducerPass::FindConstantPerGlobalVar(GlobalVariable &GV) {
1517 // If the global variable has a (non undef) initializer.
1518 if (GV.hasInitializer() && !isa<UndefValue>(GV.getInitializer())) {
David Neto862b7d82018-06-14 18:48:37 -04001519 // Generate the constant if it's not the initializer to a module scope
1520 // constant that we will expect in a storage buffer.
1521 const bool module_scope_constant_external_init =
1522 (GV.getType()->getPointerAddressSpace() == AddressSpace::Constant) &&
1523 clspv::Option::ModuleConstantsInStorageBuffer();
1524 if (!module_scope_constant_external_init) {
1525 FindConstant(GV.getInitializer());
1526 }
David Neto22f144c2017-06-12 14:26:21 -04001527 }
1528}
1529
1530void SPIRVProducerPass::FindConstantPerFunc(Function &F) {
1531 // Investigate constants in function body.
1532 for (BasicBlock &BB : F) {
1533 for (Instruction &I : BB) {
David Neto862b7d82018-06-14 18:48:37 -04001534 if (auto *call = dyn_cast<CallInst>(&I)) {
1535 auto name = call->getCalledFunction()->getName();
Kévin Petitdf71de32019-04-09 14:09:50 +01001536 if (name == clspv::LiteralSamplerFunction()) {
David Neto862b7d82018-06-14 18:48:37 -04001537 // We've handled these constants elsewhere, so skip it.
1538 continue;
1539 }
Alan Baker202c8c72018-08-13 13:47:44 -04001540 if (name.startswith(clspv::ResourceAccessorFunction())) {
1541 continue;
1542 }
1543 if (name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001544 continue;
1545 }
Kévin Petit617a76d2019-04-04 13:54:16 +01001546 if (name.startswith(clspv::SPIRVOpIntrinsicFunction())) {
1547 // Skip the first operand that has the SPIR-V Opcode
1548 for (unsigned i = 1; i < I.getNumOperands(); i++) {
1549 if (isa<Constant>(I.getOperand(i)) &&
1550 !isa<GlobalValue>(I.getOperand(i))) {
1551 FindConstant(I.getOperand(i));
1552 }
1553 }
1554 continue;
1555 }
David Neto22f144c2017-06-12 14:26:21 -04001556 }
1557
1558 if (isa<AllocaInst>(I)) {
1559 // Alloca instruction has constant for the number of element. Ignore it.
1560 continue;
1561 } else if (isa<ShuffleVectorInst>(I)) {
1562 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1563 // Ignore constant for mask of shuffle vector instruction.
1564 if (i == 2) {
1565 continue;
1566 }
1567
1568 if (isa<Constant>(I.getOperand(i)) &&
1569 !isa<GlobalValue>(I.getOperand(i))) {
1570 FindConstant(I.getOperand(i));
1571 }
1572 }
1573
1574 continue;
1575 } else if (isa<InsertElementInst>(I)) {
1576 // Handle InsertElement with <4 x i8> specially.
1577 Type *CompositeTy = I.getOperand(0)->getType();
1578 if (is4xi8vec(CompositeTy)) {
1579 LLVMContext &Context = CompositeTy->getContext();
1580 if (isa<Constant>(I.getOperand(0))) {
1581 FindConstant(I.getOperand(0));
1582 }
1583
1584 if (isa<Constant>(I.getOperand(1))) {
1585 FindConstant(I.getOperand(1));
1586 }
1587
1588 // Add mask constant 0xFF.
1589 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1590 FindConstant(CstFF);
1591
1592 // Add shift amount constant.
1593 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
1594 uint64_t Idx = CI->getZExtValue();
1595 Constant *CstShiftAmount =
1596 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1597 FindConstant(CstShiftAmount);
1598 }
1599
1600 continue;
1601 }
1602
1603 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1604 // Ignore constant for index of InsertElement instruction.
1605 if (i == 2) {
1606 continue;
1607 }
1608
1609 if (isa<Constant>(I.getOperand(i)) &&
1610 !isa<GlobalValue>(I.getOperand(i))) {
1611 FindConstant(I.getOperand(i));
1612 }
1613 }
1614
1615 continue;
1616 } else if (isa<ExtractElementInst>(I)) {
1617 // Handle ExtractElement with <4 x i8> specially.
1618 Type *CompositeTy = I.getOperand(0)->getType();
1619 if (is4xi8vec(CompositeTy)) {
1620 LLVMContext &Context = CompositeTy->getContext();
1621 if (isa<Constant>(I.getOperand(0))) {
1622 FindConstant(I.getOperand(0));
1623 }
1624
1625 // Add mask constant 0xFF.
1626 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1627 FindConstant(CstFF);
1628
1629 // Add shift amount constant.
1630 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1631 uint64_t Idx = CI->getZExtValue();
1632 Constant *CstShiftAmount =
1633 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1634 FindConstant(CstShiftAmount);
1635 } else {
1636 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
1637 FindConstant(Cst8);
1638 }
1639
1640 continue;
1641 }
1642
1643 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1644 // Ignore constant for index of ExtractElement instruction.
1645 if (i == 1) {
1646 continue;
1647 }
1648
1649 if (isa<Constant>(I.getOperand(i)) &&
1650 !isa<GlobalValue>(I.getOperand(i))) {
1651 FindConstant(I.getOperand(i));
1652 }
1653 }
1654
1655 continue;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001656 } else if ((Instruction::Xor == I.getOpcode()) &&
1657 I.getType()->isIntegerTy(1)) {
1658 // We special case for Xor where the type is i1 and one of the arguments
1659 // is a constant 1 (true), this is an OpLogicalNot in SPIR-V, and we
1660 // don't need the constant
David Neto22f144c2017-06-12 14:26:21 -04001661 bool foundConstantTrue = false;
1662 for (Use &Op : I.operands()) {
1663 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1664 auto CI = cast<ConstantInt>(Op);
1665
1666 if (CI->isZero() || foundConstantTrue) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05001667 // If we already found the true constant, we might (probably only
1668 // on -O0) have an OpLogicalNot which is taking a constant
1669 // argument, so discover it anyway.
David Neto22f144c2017-06-12 14:26:21 -04001670 FindConstant(Op);
1671 } else {
1672 foundConstantTrue = true;
1673 }
1674 }
1675 }
1676
1677 continue;
David Netod2de94a2017-08-28 17:27:47 -04001678 } else if (isa<TruncInst>(I)) {
alan-bakerb39c8262019-03-08 14:03:37 -05001679 // Special case if i8 is not generally handled.
1680 if (!clspv::Option::Int8Support()) {
1681 // For truncation to i8 we mask against 255.
1682 Type *ToTy = I.getType();
1683 if (8u == ToTy->getPrimitiveSizeInBits()) {
1684 LLVMContext &Context = ToTy->getContext();
1685 Constant *Cst255 =
1686 ConstantInt::get(Type::getInt32Ty(Context), 0xff);
1687 FindConstant(Cst255);
1688 }
David Netod2de94a2017-08-28 17:27:47 -04001689 }
Neil Henning39672102017-09-29 14:33:13 +01001690 } else if (isa<AtomicRMWInst>(I)) {
1691 LLVMContext &Context = I.getContext();
1692
1693 FindConstant(
1694 ConstantInt::get(Type::getInt32Ty(Context), spv::ScopeDevice));
1695 FindConstant(ConstantInt::get(
1696 Type::getInt32Ty(Context),
1697 spv::MemorySemanticsUniformMemoryMask |
1698 spv::MemorySemanticsSequentiallyConsistentMask));
David Neto22f144c2017-06-12 14:26:21 -04001699 }
1700
1701 for (Use &Op : I.operands()) {
1702 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1703 FindConstant(Op);
1704 }
1705 }
1706 }
1707 }
1708}
1709
1710void SPIRVProducerPass::FindConstant(Value *V) {
David Neto22f144c2017-06-12 14:26:21 -04001711 ValueList &CstList = getConstantList();
1712
David Netofb9a7972017-08-25 17:08:24 -04001713 // If V is already tracked, ignore it.
1714 if (0 != CstList.idFor(V)) {
David Neto22f144c2017-06-12 14:26:21 -04001715 return;
1716 }
1717
David Neto862b7d82018-06-14 18:48:37 -04001718 if (isa<GlobalValue>(V) && clspv::Option::ModuleConstantsInStorageBuffer()) {
1719 return;
1720 }
1721
David Neto22f144c2017-06-12 14:26:21 -04001722 Constant *Cst = cast<Constant>(V);
David Neto862b7d82018-06-14 18:48:37 -04001723 Type *CstTy = Cst->getType();
David Neto22f144c2017-06-12 14:26:21 -04001724
1725 // Handle constant with <4 x i8> type specially.
David Neto22f144c2017-06-12 14:26:21 -04001726 if (is4xi8vec(CstTy)) {
1727 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001728 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001729 }
1730 }
1731
1732 if (Cst->getNumOperands()) {
1733 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end(); I != E;
1734 ++I) {
1735 FindConstant(*I);
1736 }
1737
David Netofb9a7972017-08-25 17:08:24 -04001738 CstList.insert(Cst);
David Neto22f144c2017-06-12 14:26:21 -04001739 return;
1740 } else if (const ConstantDataSequential *CDS =
1741 dyn_cast<ConstantDataSequential>(Cst)) {
1742 // Add constants for each element to constant list.
1743 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
1744 Constant *EleCst = CDS->getElementAsConstant(i);
1745 FindConstant(EleCst);
1746 }
1747 }
1748
1749 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001750 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001751 }
1752}
1753
1754spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1755 switch (AddrSpace) {
1756 default:
1757 llvm_unreachable("Unsupported OpenCL address space");
1758 case AddressSpace::Private:
1759 return spv::StorageClassFunction;
1760 case AddressSpace::Global:
David Neto22f144c2017-06-12 14:26:21 -04001761 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001762 case AddressSpace::Constant:
1763 return clspv::Option::ConstantArgsInUniformBuffer()
1764 ? spv::StorageClassUniform
1765 : spv::StorageClassStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -04001766 case AddressSpace::Input:
1767 return spv::StorageClassInput;
1768 case AddressSpace::Local:
1769 return spv::StorageClassWorkgroup;
1770 case AddressSpace::UniformConstant:
1771 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001772 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001773 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001774 case AddressSpace::ModuleScopePrivate:
1775 return spv::StorageClassPrivate;
1776 }
1777}
1778
David Neto862b7d82018-06-14 18:48:37 -04001779spv::StorageClass
1780SPIRVProducerPass::GetStorageClassForArgKind(clspv::ArgKind arg_kind) const {
1781 switch (arg_kind) {
1782 case clspv::ArgKind::Buffer:
1783 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001784 case clspv::ArgKind::BufferUBO:
1785 return spv::StorageClassUniform;
David Neto862b7d82018-06-14 18:48:37 -04001786 case clspv::ArgKind::Pod:
1787 return clspv::Option::PodArgsInUniformBuffer()
1788 ? spv::StorageClassUniform
1789 : spv::StorageClassStorageBuffer;
1790 case clspv::ArgKind::Local:
1791 return spv::StorageClassWorkgroup;
1792 case clspv::ArgKind::ReadOnlyImage:
1793 case clspv::ArgKind::WriteOnlyImage:
1794 case clspv::ArgKind::Sampler:
1795 return spv::StorageClassUniformConstant;
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001796 default:
1797 llvm_unreachable("Unsupported storage class for argument kind");
David Neto862b7d82018-06-14 18:48:37 -04001798 }
1799}
1800
David Neto22f144c2017-06-12 14:26:21 -04001801spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1802 return StringSwitch<spv::BuiltIn>(Name)
1803 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1804 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1805 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1806 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1807 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
1808 .Default(spv::BuiltInMax);
1809}
1810
1811void SPIRVProducerPass::GenerateExtInstImport() {
1812 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1813 uint32_t &ExtInstImportID = getOpExtInstImportID();
1814
1815 //
1816 // Generate OpExtInstImport.
1817 //
1818 // Ops[0] ... Ops[n] = Name (Literal String)
David Neto22f144c2017-06-12 14:26:21 -04001819 ExtInstImportID = nextID;
David Neto87846742018-04-11 17:36:22 -04001820 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpExtInstImport, nextID++,
1821 MkString("GLSL.std.450")));
David Neto22f144c2017-06-12 14:26:21 -04001822}
1823
alan-bakerb6b09dc2018-11-08 16:59:28 -05001824void SPIRVProducerPass::GenerateSPIRVTypes(LLVMContext &Context,
1825 Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04001826 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1827 ValueMapType &VMap = getValueMap();
1828 ValueMapType &AllocatedVMap = getAllocatedValueMap();
Alan Bakerfcda9482018-10-02 17:09:59 -04001829 const auto &DL = module.getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04001830
1831 // Map for OpTypeRuntimeArray. If argument has pointer type, 2 spirv type
1832 // instructions are generated. They are OpTypePointer and OpTypeRuntimeArray.
1833 DenseMap<Type *, uint32_t> OpRuntimeTyMap;
1834
1835 for (Type *Ty : getTypeList()) {
1836 // Update TypeMap with nextID for reference later.
1837 TypeMap[Ty] = nextID;
1838
1839 switch (Ty->getTypeID()) {
1840 default: {
1841 Ty->print(errs());
1842 llvm_unreachable("Unsupported type???");
1843 break;
1844 }
1845 case Type::MetadataTyID:
1846 case Type::LabelTyID: {
1847 // Ignore these types.
1848 break;
1849 }
1850 case Type::PointerTyID: {
1851 PointerType *PTy = cast<PointerType>(Ty);
1852 unsigned AddrSpace = PTy->getAddressSpace();
1853
1854 // For the purposes of our Vulkan SPIR-V type system, constant and global
1855 // are conflated.
1856 bool UseExistingOpTypePointer = false;
1857 if (AddressSpace::Constant == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001858 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1859 AddrSpace = AddressSpace::Global;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001860 // Check to see if we already created this type (for instance, if we
1861 // had a constant <type>* and a global <type>*, the type would be
1862 // created by one of these types, and shared by both).
Alan Bakerfcda9482018-10-02 17:09:59 -04001863 auto GlobalTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1864 if (0 < TypeMap.count(GlobalTy)) {
1865 TypeMap[PTy] = TypeMap[GlobalTy];
1866 UseExistingOpTypePointer = true;
1867 break;
1868 }
David Neto22f144c2017-06-12 14:26:21 -04001869 }
1870 } else if (AddressSpace::Global == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001871 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1872 AddrSpace = AddressSpace::Constant;
David Neto22f144c2017-06-12 14:26:21 -04001873
alan-bakerb6b09dc2018-11-08 16:59:28 -05001874 // Check to see if we already created this type (for instance, if we
1875 // had a constant <type>* and a global <type>*, the type would be
1876 // created by one of these types, and shared by both).
1877 auto ConstantTy =
1878 PTy->getPointerElementType()->getPointerTo(AddrSpace);
Alan Bakerfcda9482018-10-02 17:09:59 -04001879 if (0 < TypeMap.count(ConstantTy)) {
1880 TypeMap[PTy] = TypeMap[ConstantTy];
1881 UseExistingOpTypePointer = true;
1882 }
David Neto22f144c2017-06-12 14:26:21 -04001883 }
1884 }
1885
David Neto862b7d82018-06-14 18:48:37 -04001886 const bool HasArgUser = true;
David Neto22f144c2017-06-12 14:26:21 -04001887
David Neto862b7d82018-06-14 18:48:37 -04001888 if (HasArgUser && !UseExistingOpTypePointer) {
David Neto22f144c2017-06-12 14:26:21 -04001889 //
1890 // Generate OpTypePointer.
1891 //
1892
1893 // OpTypePointer
1894 // Ops[0] = Storage Class
1895 // Ops[1] = Element Type ID
1896 SPIRVOperandList Ops;
1897
David Neto257c3892018-04-11 13:19:45 -04001898 Ops << MkNum(GetStorageClass(AddrSpace))
1899 << MkId(lookupType(PTy->getElementType()));
David Neto22f144c2017-06-12 14:26:21 -04001900
David Neto87846742018-04-11 17:36:22 -04001901 auto *Inst = new SPIRVInstruction(spv::OpTypePointer, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001902 SPIRVInstList.push_back(Inst);
1903 }
David Neto22f144c2017-06-12 14:26:21 -04001904 break;
1905 }
1906 case Type::StructTyID: {
David Neto22f144c2017-06-12 14:26:21 -04001907 StructType *STy = cast<StructType>(Ty);
1908
1909 // Handle sampler type.
1910 if (STy->isOpaque()) {
1911 if (STy->getName().equals("opencl.sampler_t")) {
1912 //
1913 // Generate OpTypeSampler
1914 //
1915 // Empty Ops.
1916 SPIRVOperandList Ops;
1917
David Neto87846742018-04-11 17:36:22 -04001918 auto *Inst = new SPIRVInstruction(spv::OpTypeSampler, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001919 SPIRVInstList.push_back(Inst);
1920 break;
alan-bakerf906d2b2019-12-10 11:26:23 -05001921 } else if (STy->getName().startswith("opencl.image1d_ro_t") ||
1922 STy->getName().startswith("opencl.image1d_wo_t") ||
1923 STy->getName().startswith("opencl.image2d_ro_t") ||
alan-bakerf67468c2019-11-25 15:51:49 -05001924 STy->getName().startswith("opencl.image2d_wo_t") ||
1925 STy->getName().startswith("opencl.image3d_ro_t") ||
1926 STy->getName().startswith("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04001927 //
1928 // Generate OpTypeImage
1929 //
1930 // Ops[0] = Sampled Type ID
1931 // Ops[1] = Dim ID
1932 // Ops[2] = Depth (Literal Number)
1933 // Ops[3] = Arrayed (Literal Number)
1934 // Ops[4] = MS (Literal Number)
1935 // Ops[5] = Sampled (Literal Number)
1936 // Ops[6] = Image Format ID
1937 //
1938 SPIRVOperandList Ops;
1939
alan-bakerf67468c2019-11-25 15:51:49 -05001940 uint32_t ImageTyID = nextID++;
1941 uint32_t SampledTyID = 0;
1942 if (STy->getName().contains(".float")) {
1943 SampledTyID = lookupType(Type::getFloatTy(Context));
1944 } else if (STy->getName().contains(".uint")) {
1945 SampledTyID = lookupType(Type::getInt32Ty(Context));
1946 } else if (STy->getName().contains(".int")) {
1947 // Generate a signed 32-bit integer if necessary.
1948 if (int32ID == 0) {
1949 int32ID = nextID++;
1950 SPIRVOperandList intOps;
1951 intOps << MkNum(32);
1952 intOps << MkNum(1);
1953 auto signed_int =
1954 new SPIRVInstruction(spv::OpTypeInt, int32ID, intOps);
1955 SPIRVInstList.push_back(signed_int);
1956 }
1957 SampledTyID = int32ID;
1958
1959 // Generate a vec4 of the signed int if necessary.
1960 if (v4int32ID == 0) {
1961 v4int32ID = nextID++;
1962 SPIRVOperandList vecOps;
1963 vecOps << MkId(int32ID);
1964 vecOps << MkNum(4);
1965 auto int_vec =
1966 new SPIRVInstruction(spv::OpTypeVector, v4int32ID, vecOps);
1967 SPIRVInstList.push_back(int_vec);
1968 }
1969 } else {
1970 // This was likely an UndefValue.
1971 SampledTyID = lookupType(Type::getFloatTy(Context));
1972 }
David Neto257c3892018-04-11 13:19:45 -04001973 Ops << MkId(SampledTyID);
David Neto22f144c2017-06-12 14:26:21 -04001974
1975 spv::Dim DimID = spv::Dim2D;
alan-bakerf906d2b2019-12-10 11:26:23 -05001976 if (STy->getName().startswith("opencl.image1d_ro_t") ||
1977 STy->getName().startswith("opencl.image1d_wo_t")) {
1978 DimID = spv::Dim1D;
1979 } else if (STy->getName().startswith("opencl.image3d_ro_t") ||
1980 STy->getName().startswith("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04001981 DimID = spv::Dim3D;
1982 }
David Neto257c3892018-04-11 13:19:45 -04001983 Ops << MkNum(DimID);
David Neto22f144c2017-06-12 14:26:21 -04001984
1985 // TODO: Set up Depth.
David Neto257c3892018-04-11 13:19:45 -04001986 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001987
1988 // TODO: Set up Arrayed.
David Neto257c3892018-04-11 13:19:45 -04001989 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001990
1991 // TODO: Set up MS.
David Neto257c3892018-04-11 13:19:45 -04001992 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001993
1994 // TODO: Set up Sampled.
1995 //
1996 // From Spec
1997 //
1998 // 0 indicates this is only known at run time, not at compile time
1999 // 1 indicates will be used with sampler
2000 // 2 indicates will be used without a sampler (a storage image)
2001 uint32_t Sampled = 1;
alan-bakerf67468c2019-11-25 15:51:49 -05002002 if (!STy->getName().contains(".sampled")) {
David Neto22f144c2017-06-12 14:26:21 -04002003 Sampled = 2;
2004 }
David Neto257c3892018-04-11 13:19:45 -04002005 Ops << MkNum(Sampled);
David Neto22f144c2017-06-12 14:26:21 -04002006
2007 // TODO: Set up Image Format.
David Neto257c3892018-04-11 13:19:45 -04002008 Ops << MkNum(spv::ImageFormatUnknown);
David Neto22f144c2017-06-12 14:26:21 -04002009
alan-bakerf67468c2019-11-25 15:51:49 -05002010 auto *Inst = new SPIRVInstruction(spv::OpTypeImage, ImageTyID, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002011 SPIRVInstList.push_back(Inst);
2012 break;
2013 }
2014 }
2015
2016 //
2017 // Generate OpTypeStruct
2018 //
2019 // Ops[0] ... Ops[n] = Member IDs
2020 SPIRVOperandList Ops;
2021
2022 for (auto *EleTy : STy->elements()) {
David Neto862b7d82018-06-14 18:48:37 -04002023 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04002024 }
2025
David Neto22f144c2017-06-12 14:26:21 -04002026 uint32_t STyID = nextID;
2027
alan-bakerb6b09dc2018-11-08 16:59:28 -05002028 auto *Inst = new SPIRVInstruction(spv::OpTypeStruct, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002029 SPIRVInstList.push_back(Inst);
2030
2031 // Generate OpMemberDecorate.
2032 auto DecoInsertPoint =
2033 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2034 [](SPIRVInstruction *Inst) -> bool {
2035 return Inst->getOpcode() != spv::OpDecorate &&
2036 Inst->getOpcode() != spv::OpMemberDecorate &&
2037 Inst->getOpcode() != spv::OpExtInstImport;
2038 });
2039
David Netoc463b372017-08-10 15:32:21 -04002040 const auto StructLayout = DL.getStructLayout(STy);
Alan Bakerfcda9482018-10-02 17:09:59 -04002041 // Search for the correct offsets if this type was remapped.
2042 std::vector<uint32_t> *offsets = nullptr;
2043 auto iter = RemappedUBOTypeOffsets.find(STy);
2044 if (iter != RemappedUBOTypeOffsets.end()) {
2045 offsets = &iter->second;
2046 }
David Netoc463b372017-08-10 15:32:21 -04002047
David Neto862b7d82018-06-14 18:48:37 -04002048 // #error TODO(dneto): Only do this if in TypesNeedingLayout.
David Neto22f144c2017-06-12 14:26:21 -04002049 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
2050 MemberIdx++) {
2051 // Ops[0] = Structure Type ID
2052 // Ops[1] = Member Index(Literal Number)
2053 // Ops[2] = Decoration (Offset)
2054 // Ops[3] = Byte Offset (Literal Number)
2055 Ops.clear();
2056
David Neto257c3892018-04-11 13:19:45 -04002057 Ops << MkId(STyID) << MkNum(MemberIdx) << MkNum(spv::DecorationOffset);
David Neto22f144c2017-06-12 14:26:21 -04002058
alan-bakerb6b09dc2018-11-08 16:59:28 -05002059 auto ByteOffset =
2060 static_cast<uint32_t>(StructLayout->getElementOffset(MemberIdx));
Alan Bakerfcda9482018-10-02 17:09:59 -04002061 if (offsets) {
2062 ByteOffset = (*offsets)[MemberIdx];
2063 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05002064 // const auto ByteOffset =
Alan Bakerfcda9482018-10-02 17:09:59 -04002065 // uint32_t(StructLayout->getElementOffset(MemberIdx));
David Neto257c3892018-04-11 13:19:45 -04002066 Ops << MkNum(ByteOffset);
David Neto22f144c2017-06-12 14:26:21 -04002067
David Neto87846742018-04-11 17:36:22 -04002068 auto *DecoInst = new SPIRVInstruction(spv::OpMemberDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002069 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04002070 }
2071
2072 // Generate OpDecorate.
David Neto862b7d82018-06-14 18:48:37 -04002073 if (StructTypesNeedingBlock.idFor(STy)) {
2074 Ops.clear();
2075 // Use Block decorations with StorageBuffer storage class.
2076 Ops << MkId(STyID) << MkNum(spv::DecorationBlock);
David Neto22f144c2017-06-12 14:26:21 -04002077
David Neto862b7d82018-06-14 18:48:37 -04002078 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
2079 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04002080 }
2081 break;
2082 }
2083 case Type::IntegerTyID: {
alan-baker0e64a592019-11-18 13:36:25 -05002084 uint32_t BitWidth = static_cast<uint32_t>(Ty->getPrimitiveSizeInBits());
David Neto22f144c2017-06-12 14:26:21 -04002085
2086 if (BitWidth == 1) {
David Netoef5ba2b2019-12-20 08:35:54 -05002087 auto *Inst = new SPIRVInstruction(spv::OpTypeBool, nextID++);
David Neto22f144c2017-06-12 14:26:21 -04002088 SPIRVInstList.push_back(Inst);
2089 } else {
alan-bakerb39c8262019-03-08 14:03:37 -05002090 if (!clspv::Option::Int8Support()) {
2091 // i8 is added to TypeMap as i32.
2092 // No matter what LLVM type is requested first, always alias the
2093 // second one's SPIR-V type to be the same as the one we generated
2094 // first.
2095 unsigned aliasToWidth = 0;
2096 if (BitWidth == 8) {
2097 aliasToWidth = 32;
2098 BitWidth = 32;
2099 } else if (BitWidth == 32) {
2100 aliasToWidth = 8;
2101 }
2102 if (aliasToWidth) {
2103 Type *otherType = Type::getIntNTy(Ty->getContext(), aliasToWidth);
2104 auto where = TypeMap.find(otherType);
2105 if (where == TypeMap.end()) {
2106 // Go ahead and make it, but also map the other type to it.
2107 TypeMap[otherType] = nextID;
2108 } else {
2109 // Alias this SPIR-V type the existing type.
2110 TypeMap[Ty] = where->second;
2111 break;
2112 }
David Neto391aeb12017-08-26 15:51:58 -04002113 }
David Neto22f144c2017-06-12 14:26:21 -04002114 }
2115
David Neto257c3892018-04-11 13:19:45 -04002116 SPIRVOperandList Ops;
2117 Ops << MkNum(BitWidth) << MkNum(0 /* not signed */);
David Neto22f144c2017-06-12 14:26:21 -04002118
2119 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002120 new SPIRVInstruction(spv::OpTypeInt, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002121 }
2122 break;
2123 }
2124 case Type::HalfTyID:
2125 case Type::FloatTyID:
2126 case Type::DoubleTyID: {
alan-baker0e64a592019-11-18 13:36:25 -05002127 uint32_t BitWidth = static_cast<uint32_t>(Ty->getPrimitiveSizeInBits());
James Price11010dc2019-12-19 13:53:09 -05002128 auto WidthOp = MkNum(BitWidth);
David Neto22f144c2017-06-12 14:26:21 -04002129
2130 SPIRVInstList.push_back(
David Netoef5ba2b2019-12-20 08:35:54 -05002131 new SPIRVInstruction(spv::OpTypeFloat, nextID++, std::move(WidthOp)));
David Neto22f144c2017-06-12 14:26:21 -04002132 break;
2133 }
2134 case Type::ArrayTyID: {
David Neto22f144c2017-06-12 14:26:21 -04002135 ArrayType *ArrTy = cast<ArrayType>(Ty);
David Neto862b7d82018-06-14 18:48:37 -04002136 const uint64_t Length = ArrTy->getArrayNumElements();
2137 if (Length == 0) {
2138 // By convention, map it to a RuntimeArray.
David Neto22f144c2017-06-12 14:26:21 -04002139
David Neto862b7d82018-06-14 18:48:37 -04002140 // Only generate the type once.
2141 // TODO(dneto): Can it ever be generated more than once?
2142 // Doesn't LLVM type uniqueness guarantee we'll only see this
2143 // once?
2144 Type *EleTy = ArrTy->getArrayElementType();
2145 if (OpRuntimeTyMap.count(EleTy) == 0) {
2146 uint32_t OpTypeRuntimeArrayID = nextID;
2147 OpRuntimeTyMap[Ty] = nextID;
David Neto22f144c2017-06-12 14:26:21 -04002148
David Neto862b7d82018-06-14 18:48:37 -04002149 //
2150 // Generate OpTypeRuntimeArray.
2151 //
David Neto22f144c2017-06-12 14:26:21 -04002152
David Neto862b7d82018-06-14 18:48:37 -04002153 // OpTypeRuntimeArray
2154 // Ops[0] = Element Type ID
2155 SPIRVOperandList Ops;
2156 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04002157
David Neto862b7d82018-06-14 18:48:37 -04002158 SPIRVInstList.push_back(
2159 new SPIRVInstruction(spv::OpTypeRuntimeArray, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002160
David Neto862b7d82018-06-14 18:48:37 -04002161 if (Hack_generate_runtime_array_stride_early) {
2162 // Generate OpDecorate.
2163 auto DecoInsertPoint = std::find_if(
2164 SPIRVInstList.begin(), SPIRVInstList.end(),
2165 [](SPIRVInstruction *Inst) -> bool {
2166 return Inst->getOpcode() != spv::OpDecorate &&
2167 Inst->getOpcode() != spv::OpMemberDecorate &&
2168 Inst->getOpcode() != spv::OpExtInstImport;
2169 });
David Neto22f144c2017-06-12 14:26:21 -04002170
David Neto862b7d82018-06-14 18:48:37 -04002171 // Ops[0] = Target ID
2172 // Ops[1] = Decoration (ArrayStride)
2173 // Ops[2] = Stride Number(Literal Number)
2174 Ops.clear();
David Neto85082642018-03-24 06:55:20 -07002175
David Neto862b7d82018-06-14 18:48:37 -04002176 Ops << MkId(OpTypeRuntimeArrayID)
2177 << MkNum(spv::DecorationArrayStride)
Alan Bakerfcda9482018-10-02 17:09:59 -04002178 << MkNum(static_cast<uint32_t>(GetTypeAllocSize(EleTy, DL)));
David Neto22f144c2017-06-12 14:26:21 -04002179
David Neto862b7d82018-06-14 18:48:37 -04002180 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
2181 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
2182 }
2183 }
David Neto22f144c2017-06-12 14:26:21 -04002184
David Neto862b7d82018-06-14 18:48:37 -04002185 } else {
David Neto22f144c2017-06-12 14:26:21 -04002186
David Neto862b7d82018-06-14 18:48:37 -04002187 //
2188 // Generate OpConstant and OpTypeArray.
2189 //
2190
2191 //
2192 // Generate OpConstant for array length.
2193 //
2194 // Ops[0] = Result Type ID
2195 // Ops[1] .. Ops[n] = Values LiteralNumber
2196 SPIRVOperandList Ops;
2197
2198 Type *LengthTy = Type::getInt32Ty(Context);
2199 uint32_t ResTyID = lookupType(LengthTy);
2200 Ops << MkId(ResTyID);
2201
2202 assert(Length < UINT32_MAX);
2203 Ops << MkNum(static_cast<uint32_t>(Length));
2204
2205 // Add constant for length to constant list.
2206 Constant *CstLength = ConstantInt::get(LengthTy, Length);
2207 AllocatedVMap[CstLength] = nextID;
2208 VMap[CstLength] = nextID;
2209 uint32_t LengthID = nextID;
2210
2211 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
2212 SPIRVInstList.push_back(CstInst);
2213
2214 // Remember to generate ArrayStride later
2215 getTypesNeedingArrayStride().insert(Ty);
2216
2217 //
2218 // Generate OpTypeArray.
2219 //
2220 // Ops[0] = Element Type ID
2221 // Ops[1] = Array Length Constant ID
2222 Ops.clear();
2223
2224 uint32_t EleTyID = lookupType(ArrTy->getElementType());
2225 Ops << MkId(EleTyID) << MkId(LengthID);
2226
2227 // Update TypeMap with nextID.
2228 TypeMap[Ty] = nextID;
2229
2230 auto *ArrayInst = new SPIRVInstruction(spv::OpTypeArray, nextID++, Ops);
2231 SPIRVInstList.push_back(ArrayInst);
2232 }
David Neto22f144c2017-06-12 14:26:21 -04002233 break;
2234 }
2235 case Type::VectorTyID: {
alan-bakerb39c8262019-03-08 14:03:37 -05002236 // <4 x i8> is changed to i32 if i8 is not generally supported.
2237 if (!clspv::Option::Int8Support() &&
2238 Ty->getVectorElementType() == Type::getInt8Ty(Context)) {
David Neto22f144c2017-06-12 14:26:21 -04002239 if (Ty->getVectorNumElements() == 4) {
2240 TypeMap[Ty] = lookupType(Ty->getVectorElementType());
2241 break;
2242 } else {
2243 Ty->print(errs());
2244 llvm_unreachable("Support above i8 vector type");
2245 }
2246 }
2247
2248 // Ops[0] = Component Type ID
2249 // Ops[1] = Component Count (Literal Number)
David Neto257c3892018-04-11 13:19:45 -04002250 SPIRVOperandList Ops;
2251 Ops << MkId(lookupType(Ty->getVectorElementType()))
2252 << MkNum(Ty->getVectorNumElements());
David Neto22f144c2017-06-12 14:26:21 -04002253
alan-bakerb6b09dc2018-11-08 16:59:28 -05002254 SPIRVInstruction *inst =
2255 new SPIRVInstruction(spv::OpTypeVector, nextID++, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002256 SPIRVInstList.push_back(inst);
David Neto22f144c2017-06-12 14:26:21 -04002257 break;
2258 }
2259 case Type::VoidTyID: {
David Netoef5ba2b2019-12-20 08:35:54 -05002260 auto *Inst = new SPIRVInstruction(spv::OpTypeVoid, nextID++);
David Neto22f144c2017-06-12 14:26:21 -04002261 SPIRVInstList.push_back(Inst);
2262 break;
2263 }
2264 case Type::FunctionTyID: {
2265 // Generate SPIRV instruction for function type.
2266 FunctionType *FTy = cast<FunctionType>(Ty);
2267
2268 // Ops[0] = Return Type ID
2269 // Ops[1] ... Ops[n] = Parameter Type IDs
2270 SPIRVOperandList Ops;
2271
2272 // Find SPIRV instruction for return type
David Netoc6f3ab22018-04-06 18:02:31 -04002273 Ops << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04002274
2275 // Find SPIRV instructions for parameter types
2276 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
2277 // Find SPIRV instruction for parameter type.
2278 auto ParamTy = FTy->getParamType(k);
2279 if (ParamTy->isPointerTy()) {
2280 auto PointeeTy = ParamTy->getPointerElementType();
2281 if (PointeeTy->isStructTy() &&
2282 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
2283 ParamTy = PointeeTy;
2284 }
2285 }
2286
David Netoc6f3ab22018-04-06 18:02:31 -04002287 Ops << MkId(lookupType(ParamTy));
David Neto22f144c2017-06-12 14:26:21 -04002288 }
2289
David Neto87846742018-04-11 17:36:22 -04002290 auto *Inst = new SPIRVInstruction(spv::OpTypeFunction, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002291 SPIRVInstList.push_back(Inst);
2292 break;
2293 }
2294 }
2295 }
2296
2297 // Generate OpTypeSampledImage.
alan-bakerabd82722019-12-03 17:14:51 -05002298 for (auto &ImgTy : getImageTypeList()) {
David Neto22f144c2017-06-12 14:26:21 -04002299 //
2300 // Generate OpTypeSampledImage.
2301 //
2302 // Ops[0] = Image Type ID
2303 //
2304 SPIRVOperandList Ops;
2305
David Netoc6f3ab22018-04-06 18:02:31 -04002306 Ops << MkId(TypeMap[ImgTy]);
David Neto22f144c2017-06-12 14:26:21 -04002307
alan-bakerabd82722019-12-03 17:14:51 -05002308 // Update the image type map.
2309 getImageTypeMap()[ImgTy] = nextID;
David Neto22f144c2017-06-12 14:26:21 -04002310
David Neto87846742018-04-11 17:36:22 -04002311 auto *Inst = new SPIRVInstruction(spv::OpTypeSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002312 SPIRVInstList.push_back(Inst);
2313 }
David Netoc6f3ab22018-04-06 18:02:31 -04002314
2315 // Generate types for pointer-to-local arguments.
Alan Baker202c8c72018-08-13 13:47:44 -04002316 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2317 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002318 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002319
2320 // Generate the spec constant.
2321 SPIRVOperandList Ops;
2322 Ops << MkId(lookupType(Type::getInt32Ty(Context))) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04002323 SPIRVInstList.push_back(
2324 new SPIRVInstruction(spv::OpSpecConstant, arg_info.array_size_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002325
2326 // Generate the array type.
2327 Ops.clear();
2328 // The element type must have been created.
2329 uint32_t elem_ty_id = lookupType(arg_info.elem_type);
2330 assert(elem_ty_id);
2331 Ops << MkId(elem_ty_id) << MkId(arg_info.array_size_id);
2332
2333 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002334 new SPIRVInstruction(spv::OpTypeArray, arg_info.array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002335
2336 Ops.clear();
2337 Ops << MkNum(spv::StorageClassWorkgroup) << MkId(arg_info.array_type_id);
David Neto87846742018-04-11 17:36:22 -04002338 SPIRVInstList.push_back(new SPIRVInstruction(
2339 spv::OpTypePointer, arg_info.ptr_array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002340 }
David Neto22f144c2017-06-12 14:26:21 -04002341}
2342
2343void SPIRVProducerPass::GenerateSPIRVConstants() {
2344 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2345 ValueMapType &VMap = getValueMap();
2346 ValueMapType &AllocatedVMap = getAllocatedValueMap();
2347 ValueList &CstList = getConstantList();
David Neto482550a2018-03-24 05:21:07 -07002348 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04002349
2350 for (uint32_t i = 0; i < CstList.size(); i++) {
David Netofb9a7972017-08-25 17:08:24 -04002351 // UniqueVector ids are 1-based.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002352 Constant *Cst = cast<Constant>(CstList[i + 1]);
David Neto22f144c2017-06-12 14:26:21 -04002353
2354 // OpTypeArray's constant was already generated.
David Netofb9a7972017-08-25 17:08:24 -04002355 if (AllocatedVMap.find_as(Cst) != AllocatedVMap.end()) {
David Neto22f144c2017-06-12 14:26:21 -04002356 continue;
2357 }
2358
David Netofb9a7972017-08-25 17:08:24 -04002359 // Set ValueMap with nextID for reference later.
David Neto22f144c2017-06-12 14:26:21 -04002360 VMap[Cst] = nextID;
2361
2362 //
2363 // Generate OpConstant.
2364 //
2365
2366 // Ops[0] = Result Type ID
2367 // Ops[1] .. Ops[n] = Values LiteralNumber
2368 SPIRVOperandList Ops;
2369
David Neto257c3892018-04-11 13:19:45 -04002370 Ops << MkId(lookupType(Cst->getType()));
David Neto22f144c2017-06-12 14:26:21 -04002371
2372 std::vector<uint32_t> LiteralNum;
David Neto22f144c2017-06-12 14:26:21 -04002373 spv::Op Opcode = spv::OpNop;
2374
2375 if (isa<UndefValue>(Cst)) {
2376 // Ops[0] = Result Type ID
David Netoc66b3352017-10-20 14:28:46 -04002377 Opcode = spv::OpUndef;
Alan Baker9bf93fb2018-08-28 16:59:26 -04002378 if (hack_undef && IsTypeNullable(Cst->getType())) {
2379 Opcode = spv::OpConstantNull;
David Netoc66b3352017-10-20 14:28:46 -04002380 }
David Neto22f144c2017-06-12 14:26:21 -04002381 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
2382 unsigned BitWidth = CI->getBitWidth();
2383 if (BitWidth == 1) {
2384 // If the bitwidth of constant is 1, generate OpConstantTrue or
2385 // OpConstantFalse.
2386 if (CI->getZExtValue()) {
2387 // Ops[0] = Result Type ID
2388 Opcode = spv::OpConstantTrue;
2389 } else {
2390 // Ops[0] = Result Type ID
2391 Opcode = spv::OpConstantFalse;
2392 }
David Neto22f144c2017-06-12 14:26:21 -04002393 } else {
2394 auto V = CI->getZExtValue();
2395 LiteralNum.push_back(V & 0xFFFFFFFF);
2396
2397 if (BitWidth > 32) {
2398 LiteralNum.push_back(V >> 32);
2399 }
2400
2401 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002402
David Neto257c3892018-04-11 13:19:45 -04002403 Ops << MkInteger(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002404 }
2405 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2406 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2407 Type *CFPTy = CFP->getType();
2408 if (CFPTy->isFloatTy()) {
2409 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
Kévin Petit02ee34e2019-04-04 19:03:22 +01002410 } else if (CFPTy->isDoubleTy()) {
2411 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2412 LiteralNum.push_back(FPVal >> 32);
David Neto22f144c2017-06-12 14:26:21 -04002413 } else {
2414 CFPTy->print(errs());
2415 llvm_unreachable("Implement this ConstantFP Type");
2416 }
2417
2418 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002419
David Neto257c3892018-04-11 13:19:45 -04002420 Ops << MkFloat(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002421 } else if (isa<ConstantDataSequential>(Cst) &&
2422 cast<ConstantDataSequential>(Cst)->isString()) {
2423 Cst->print(errs());
2424 llvm_unreachable("Implement this Constant");
2425
2426 } else if (const ConstantDataSequential *CDS =
2427 dyn_cast<ConstantDataSequential>(Cst)) {
David Neto49351ac2017-08-26 17:32:20 -04002428 // Let's convert <4 x i8> constant to int constant specially.
2429 // This case occurs when all the values are specified as constant
2430 // ints.
2431 Type *CstTy = Cst->getType();
2432 if (is4xi8vec(CstTy)) {
2433 LLVMContext &Context = CstTy->getContext();
2434
2435 //
2436 // Generate OpConstant with OpTypeInt 32 0.
2437 //
Neil Henning39672102017-09-29 14:33:13 +01002438 uint32_t IntValue = 0;
2439 for (unsigned k = 0; k < 4; k++) {
2440 const uint64_t Val = CDS->getElementAsInteger(k);
David Neto49351ac2017-08-26 17:32:20 -04002441 IntValue = (IntValue << 8) | (Val & 0xffu);
2442 }
2443
2444 Type *i32 = Type::getInt32Ty(Context);
2445 Constant *CstInt = ConstantInt::get(i32, IntValue);
2446 // If this constant is already registered on VMap, use it.
2447 if (VMap.count(CstInt)) {
2448 uint32_t CstID = VMap[CstInt];
2449 VMap[Cst] = CstID;
2450 continue;
2451 }
2452
David Neto257c3892018-04-11 13:19:45 -04002453 Ops << MkNum(IntValue);
David Neto49351ac2017-08-26 17:32:20 -04002454
David Neto87846742018-04-11 17:36:22 -04002455 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto49351ac2017-08-26 17:32:20 -04002456 SPIRVInstList.push_back(CstInst);
2457
2458 continue;
2459 }
2460
2461 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002462 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
2463 Constant *EleCst = CDS->getElementAsConstant(k);
2464 uint32_t EleCstID = VMap[EleCst];
David Neto257c3892018-04-11 13:19:45 -04002465 Ops << MkId(EleCstID);
David Neto22f144c2017-06-12 14:26:21 -04002466 }
2467
2468 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002469 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2470 // Let's convert <4 x i8> constant to int constant specially.
David Neto49351ac2017-08-26 17:32:20 -04002471 // This case occurs when at least one of the values is an undef.
David Neto22f144c2017-06-12 14:26:21 -04002472 Type *CstTy = Cst->getType();
2473 if (is4xi8vec(CstTy)) {
2474 LLVMContext &Context = CstTy->getContext();
2475
2476 //
2477 // Generate OpConstant with OpTypeInt 32 0.
2478 //
Neil Henning39672102017-09-29 14:33:13 +01002479 uint32_t IntValue = 0;
David Neto22f144c2017-06-12 14:26:21 -04002480 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2481 I != E; ++I) {
2482 uint64_t Val = 0;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002483 const Value *CV = *I;
Neil Henning39672102017-09-29 14:33:13 +01002484 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2485 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002486 }
David Neto49351ac2017-08-26 17:32:20 -04002487 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002488 }
2489
David Neto49351ac2017-08-26 17:32:20 -04002490 Type *i32 = Type::getInt32Ty(Context);
2491 Constant *CstInt = ConstantInt::get(i32, IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002492 // If this constant is already registered on VMap, use it.
2493 if (VMap.count(CstInt)) {
2494 uint32_t CstID = VMap[CstInt];
2495 VMap[Cst] = CstID;
David Neto19a1bad2017-08-25 15:01:41 -04002496 continue;
David Neto22f144c2017-06-12 14:26:21 -04002497 }
2498
David Neto257c3892018-04-11 13:19:45 -04002499 Ops << MkNum(IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002500
David Neto87846742018-04-11 17:36:22 -04002501 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002502 SPIRVInstList.push_back(CstInst);
2503
David Neto19a1bad2017-08-25 15:01:41 -04002504 continue;
David Neto22f144c2017-06-12 14:26:21 -04002505 }
2506
2507 // We use a constant composite in SPIR-V for our constant aggregate in
2508 // LLVM.
2509 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002510
2511 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
2512 // Look up the ID of the element of this aggregate (which we will
2513 // previously have created a constant for).
2514 uint32_t ElementConstantID = VMap[CA->getAggregateElement(k)];
2515
2516 // And add an operand to the composite we are constructing
David Neto257c3892018-04-11 13:19:45 -04002517 Ops << MkId(ElementConstantID);
David Neto22f144c2017-06-12 14:26:21 -04002518 }
2519 } else if (Cst->isNullValue()) {
2520 Opcode = spv::OpConstantNull;
David Neto22f144c2017-06-12 14:26:21 -04002521 } else {
2522 Cst->print(errs());
2523 llvm_unreachable("Unsupported Constant???");
2524 }
2525
alan-baker5b86ed72019-02-15 08:26:50 -05002526 if (Opcode == spv::OpConstantNull && Cst->getType()->isPointerTy()) {
2527 // Null pointer requires variable pointers.
2528 setVariablePointersCapabilities(Cst->getType()->getPointerAddressSpace());
2529 }
2530
David Neto87846742018-04-11 17:36:22 -04002531 auto *CstInst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002532 SPIRVInstList.push_back(CstInst);
2533 }
2534}
2535
2536void SPIRVProducerPass::GenerateSamplers(Module &M) {
2537 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto22f144c2017-06-12 14:26:21 -04002538
alan-bakerb6b09dc2018-11-08 16:59:28 -05002539 auto &sampler_map = getSamplerMap();
alan-baker09cb9802019-12-10 13:16:27 -05002540 SamplerLiteralToIDMap.clear();
David Neto862b7d82018-06-14 18:48:37 -04002541 DenseMap<unsigned, unsigned> SamplerLiteralToDescriptorSetMap;
2542 DenseMap<unsigned, unsigned> SamplerLiteralToBindingMap;
David Neto22f144c2017-06-12 14:26:21 -04002543
David Neto862b7d82018-06-14 18:48:37 -04002544 // We might have samplers in the sampler map that are not used
2545 // in the translation unit. We need to allocate variables
2546 // for them and bindings too.
2547 DenseSet<unsigned> used_bindings;
David Neto22f144c2017-06-12 14:26:21 -04002548
Kévin Petitdf71de32019-04-09 14:09:50 +01002549 auto *var_fn = M.getFunction(clspv::LiteralSamplerFunction());
alan-baker09cb9802019-12-10 13:16:27 -05002550 // Return if there are no literal samplers.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002551 if (!var_fn)
2552 return;
alan-baker09cb9802019-12-10 13:16:27 -05002553
David Neto862b7d82018-06-14 18:48:37 -04002554 for (auto user : var_fn->users()) {
2555 // Populate SamplerLiteralToDescriptorSetMap and
2556 // SamplerLiteralToBindingMap.
2557 //
2558 // Look for calls like
2559 // call %opencl.sampler_t addrspace(2)*
2560 // @clspv.sampler.var.literal(
2561 // i32 descriptor,
2562 // i32 binding,
alan-baker09cb9802019-12-10 13:16:27 -05002563 // i32 (index-into-sampler-map|sampler_mask))
alan-bakerb6b09dc2018-11-08 16:59:28 -05002564 if (auto *call = dyn_cast<CallInst>(user)) {
alan-baker09cb9802019-12-10 13:16:27 -05002565 const auto third_param = static_cast<unsigned>(
alan-bakerb6b09dc2018-11-08 16:59:28 -05002566 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
alan-baker09cb9802019-12-10 13:16:27 -05002567 auto sampler_value = third_param;
2568 if (clspv::Option::UseSamplerMap()) {
2569 if (third_param >= sampler_map.size()) {
2570 errs() << "Out of bounds index to sampler map: " << third_param;
2571 llvm_unreachable("bad sampler init: out of bounds");
2572 }
2573 sampler_value = sampler_map[third_param].first;
David Neto862b7d82018-06-14 18:48:37 -04002574 }
2575
David Neto862b7d82018-06-14 18:48:37 -04002576 const auto descriptor_set = static_cast<unsigned>(
2577 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
2578 const auto binding = static_cast<unsigned>(
2579 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
2580
2581 SamplerLiteralToDescriptorSetMap[sampler_value] = descriptor_set;
2582 SamplerLiteralToBindingMap[sampler_value] = binding;
2583 used_bindings.insert(binding);
2584 }
2585 }
2586
alan-baker09cb9802019-12-10 13:16:27 -05002587 DenseSet<size_t> seen;
2588 for (auto user : var_fn->users()) {
2589 if (!isa<CallInst>(user))
2590 continue;
2591
2592 auto call = cast<CallInst>(user);
2593 const unsigned third_param = static_cast<unsigned>(
2594 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
2595
2596 // Already allocated a variable for this value.
2597 if (!seen.insert(third_param).second)
2598 continue;
2599
2600 auto sampler_value = third_param;
2601 if (clspv::Option::UseSamplerMap()) {
2602 sampler_value = sampler_map[third_param].first;
2603 }
2604
David Neto22f144c2017-06-12 14:26:21 -04002605 // Generate OpVariable.
2606 //
2607 // GIDOps[0] : Result Type ID
2608 // GIDOps[1] : Storage Class
2609 SPIRVOperandList Ops;
2610
David Neto257c3892018-04-11 13:19:45 -04002611 Ops << MkId(lookupType(SamplerTy))
2612 << MkNum(spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002613
David Neto862b7d82018-06-14 18:48:37 -04002614 auto sampler_var_id = nextID++;
2615 auto *Inst = new SPIRVInstruction(spv::OpVariable, sampler_var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002616 SPIRVInstList.push_back(Inst);
2617
alan-baker09cb9802019-12-10 13:16:27 -05002618 SamplerLiteralToIDMap[sampler_value] = sampler_var_id;
David Neto22f144c2017-06-12 14:26:21 -04002619
2620 // Find Insert Point for OpDecorate.
2621 auto DecoInsertPoint =
2622 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2623 [](SPIRVInstruction *Inst) -> bool {
2624 return Inst->getOpcode() != spv::OpDecorate &&
2625 Inst->getOpcode() != spv::OpMemberDecorate &&
2626 Inst->getOpcode() != spv::OpExtInstImport;
2627 });
2628
2629 // Ops[0] = Target ID
2630 // Ops[1] = Decoration (DescriptorSet)
2631 // Ops[2] = LiteralNumber according to Decoration
2632 Ops.clear();
2633
David Neto862b7d82018-06-14 18:48:37 -04002634 unsigned descriptor_set;
2635 unsigned binding;
alan-baker09cb9802019-12-10 13:16:27 -05002636 if (SamplerLiteralToBindingMap.find(sampler_value) ==
alan-bakerb6b09dc2018-11-08 16:59:28 -05002637 SamplerLiteralToBindingMap.end()) {
David Neto862b7d82018-06-14 18:48:37 -04002638 // This sampler is not actually used. Find the next one.
2639 for (binding = 0; used_bindings.count(binding); binding++)
2640 ;
2641 descriptor_set = 0; // Literal samplers always use descriptor set 0.
2642 used_bindings.insert(binding);
2643 } else {
alan-baker09cb9802019-12-10 13:16:27 -05002644 descriptor_set = SamplerLiteralToDescriptorSetMap[sampler_value];
2645 binding = SamplerLiteralToBindingMap[sampler_value];
alan-bakercff80152019-06-15 00:38:00 -04002646
alan-baker09cb9802019-12-10 13:16:27 -05002647 version0::DescriptorMapEntry::SamplerData sampler_data = {sampler_value};
alan-bakercff80152019-06-15 00:38:00 -04002648 descriptorMapEntries->emplace_back(std::move(sampler_data),
2649 descriptor_set, binding);
David Neto862b7d82018-06-14 18:48:37 -04002650 }
2651
2652 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationDescriptorSet)
2653 << MkNum(descriptor_set);
David Neto22f144c2017-06-12 14:26:21 -04002654
David Neto87846742018-04-11 17:36:22 -04002655 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002656 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2657
2658 // Ops[0] = Target ID
2659 // Ops[1] = Decoration (Binding)
2660 // Ops[2] = LiteralNumber according to Decoration
2661 Ops.clear();
David Neto862b7d82018-06-14 18:48:37 -04002662 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationBinding)
2663 << MkNum(binding);
David Neto22f144c2017-06-12 14:26:21 -04002664
David Neto87846742018-04-11 17:36:22 -04002665 auto *BindDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002666 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
2667 }
David Neto862b7d82018-06-14 18:48:37 -04002668}
David Neto22f144c2017-06-12 14:26:21 -04002669
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01002670void SPIRVProducerPass::GenerateResourceVars(Module &) {
David Neto862b7d82018-06-14 18:48:37 -04002671 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2672 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04002673
David Neto862b7d82018-06-14 18:48:37 -04002674 // Generate variables. Make one for each of resource var info object.
2675 for (auto *info : ModuleOrderedResourceVars) {
2676 Type *type = info->var_fn->getReturnType();
2677 // Remap the address space for opaque types.
2678 switch (info->arg_kind) {
2679 case clspv::ArgKind::Sampler:
2680 case clspv::ArgKind::ReadOnlyImage:
2681 case clspv::ArgKind::WriteOnlyImage:
2682 type = PointerType::get(type->getPointerElementType(),
2683 clspv::AddressSpace::UniformConstant);
2684 break;
2685 default:
2686 break;
2687 }
David Neto22f144c2017-06-12 14:26:21 -04002688
David Neto862b7d82018-06-14 18:48:37 -04002689 info->var_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04002690
David Neto862b7d82018-06-14 18:48:37 -04002691 const auto type_id = lookupType(type);
2692 const auto sc = GetStorageClassForArgKind(info->arg_kind);
2693 SPIRVOperandList Ops;
2694 Ops << MkId(type_id) << MkNum(sc);
David Neto22f144c2017-06-12 14:26:21 -04002695
David Neto862b7d82018-06-14 18:48:37 -04002696 auto *Inst = new SPIRVInstruction(spv::OpVariable, info->var_id, Ops);
2697 SPIRVInstList.push_back(Inst);
2698
2699 // Map calls to the variable-builtin-function.
2700 for (auto &U : info->var_fn->uses()) {
2701 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
2702 const auto set = unsigned(
2703 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
2704 const auto binding = unsigned(
2705 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
2706 if (set == info->descriptor_set && binding == info->binding) {
2707 switch (info->arg_kind) {
2708 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002709 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002710 case clspv::ArgKind::Pod:
2711 // The call maps to the variable directly.
2712 VMap[call] = info->var_id;
2713 break;
2714 case clspv::ArgKind::Sampler:
2715 case clspv::ArgKind::ReadOnlyImage:
2716 case clspv::ArgKind::WriteOnlyImage:
2717 // The call maps to a load we generate later.
2718 ResourceVarDeferredLoadCalls[call] = info->var_id;
2719 break;
2720 default:
2721 llvm_unreachable("Unhandled arg kind");
2722 }
2723 }
David Neto22f144c2017-06-12 14:26:21 -04002724 }
David Neto862b7d82018-06-14 18:48:37 -04002725 }
2726 }
David Neto22f144c2017-06-12 14:26:21 -04002727
David Neto862b7d82018-06-14 18:48:37 -04002728 // Generate associated decorations.
David Neto22f144c2017-06-12 14:26:21 -04002729
David Neto862b7d82018-06-14 18:48:37 -04002730 // Find Insert Point for OpDecorate.
2731 auto DecoInsertPoint =
2732 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2733 [](SPIRVInstruction *Inst) -> bool {
2734 return Inst->getOpcode() != spv::OpDecorate &&
2735 Inst->getOpcode() != spv::OpMemberDecorate &&
2736 Inst->getOpcode() != spv::OpExtInstImport;
2737 });
2738
2739 SPIRVOperandList Ops;
2740 for (auto *info : ModuleOrderedResourceVars) {
2741 // Decorate with DescriptorSet and Binding.
2742 Ops.clear();
2743 Ops << MkId(info->var_id) << MkNum(spv::DecorationDescriptorSet)
2744 << MkNum(info->descriptor_set);
2745 SPIRVInstList.insert(DecoInsertPoint,
2746 new SPIRVInstruction(spv::OpDecorate, Ops));
2747
2748 Ops.clear();
2749 Ops << MkId(info->var_id) << MkNum(spv::DecorationBinding)
2750 << MkNum(info->binding);
2751 SPIRVInstList.insert(DecoInsertPoint,
2752 new SPIRVInstruction(spv::OpDecorate, Ops));
2753
alan-bakere9308012019-03-15 10:25:13 -04002754 if (info->coherent) {
2755 // Decorate with Coherent if required for the variable.
2756 Ops.clear();
2757 Ops << MkId(info->var_id) << MkNum(spv::DecorationCoherent);
2758 SPIRVInstList.insert(DecoInsertPoint,
2759 new SPIRVInstruction(spv::OpDecorate, Ops));
2760 }
2761
David Neto862b7d82018-06-14 18:48:37 -04002762 // Generate NonWritable and NonReadable
2763 switch (info->arg_kind) {
2764 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002765 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002766 if (info->var_fn->getReturnType()->getPointerAddressSpace() ==
2767 clspv::AddressSpace::Constant) {
2768 Ops.clear();
2769 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
2770 SPIRVInstList.insert(DecoInsertPoint,
2771 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002772 }
David Neto862b7d82018-06-14 18:48:37 -04002773 break;
David Neto862b7d82018-06-14 18:48:37 -04002774 case clspv::ArgKind::WriteOnlyImage:
2775 Ops.clear();
2776 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonReadable);
2777 SPIRVInstList.insert(DecoInsertPoint,
2778 new SPIRVInstruction(spv::OpDecorate, Ops));
2779 break;
2780 default:
2781 break;
David Neto22f144c2017-06-12 14:26:21 -04002782 }
2783 }
2784}
2785
2786void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002787 Module &M = *GV.getParent();
David Neto22f144c2017-06-12 14:26:21 -04002788 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2789 ValueMapType &VMap = getValueMap();
2790 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07002791 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002792
2793 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2794 Type *Ty = GV.getType();
2795 PointerType *PTy = cast<PointerType>(Ty);
2796
2797 uint32_t InitializerID = 0;
2798
2799 // Workgroup size is handled differently (it goes into a constant)
2800 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2801 std::vector<bool> HasMDVec;
2802 uint32_t PrevXDimCst = 0xFFFFFFFF;
2803 uint32_t PrevYDimCst = 0xFFFFFFFF;
2804 uint32_t PrevZDimCst = 0xFFFFFFFF;
2805 for (Function &Func : *GV.getParent()) {
2806 if (Func.isDeclaration()) {
2807 continue;
2808 }
2809
2810 // We only need to check kernels.
2811 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2812 continue;
2813 }
2814
2815 if (const MDNode *MD =
2816 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2817 uint32_t CurXDimCst = static_cast<uint32_t>(
2818 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2819 uint32_t CurYDimCst = static_cast<uint32_t>(
2820 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2821 uint32_t CurZDimCst = static_cast<uint32_t>(
2822 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2823
2824 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2825 PrevZDimCst == 0xFFFFFFFF) {
2826 PrevXDimCst = CurXDimCst;
2827 PrevYDimCst = CurYDimCst;
2828 PrevZDimCst = CurZDimCst;
2829 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2830 CurZDimCst != PrevZDimCst) {
2831 llvm_unreachable(
2832 "reqd_work_group_size must be the same across all kernels");
2833 } else {
2834 continue;
2835 }
2836
2837 //
2838 // Generate OpConstantComposite.
2839 //
2840 // Ops[0] : Result Type ID
2841 // Ops[1] : Constant size for x dimension.
2842 // Ops[2] : Constant size for y dimension.
2843 // Ops[3] : Constant size for z dimension.
2844 SPIRVOperandList Ops;
2845
2846 uint32_t XDimCstID =
2847 VMap[mdconst::extract<ConstantInt>(MD->getOperand(0))];
2848 uint32_t YDimCstID =
2849 VMap[mdconst::extract<ConstantInt>(MD->getOperand(1))];
2850 uint32_t ZDimCstID =
2851 VMap[mdconst::extract<ConstantInt>(MD->getOperand(2))];
2852
2853 InitializerID = nextID;
2854
David Neto257c3892018-04-11 13:19:45 -04002855 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2856 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002857
David Neto87846742018-04-11 17:36:22 -04002858 auto *Inst =
2859 new SPIRVInstruction(spv::OpConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002860 SPIRVInstList.push_back(Inst);
2861
2862 HasMDVec.push_back(true);
2863 } else {
2864 HasMDVec.push_back(false);
2865 }
2866 }
2867
2868 // Check all kernels have same definitions for work_group_size.
2869 bool HasMD = false;
2870 if (!HasMDVec.empty()) {
2871 HasMD = HasMDVec[0];
2872 for (uint32_t i = 1; i < HasMDVec.size(); i++) {
2873 if (HasMD != HasMDVec[i]) {
2874 llvm_unreachable(
2875 "Kernels should have consistent work group size definition");
2876 }
2877 }
2878 }
2879
2880 // If all kernels do not have metadata for reqd_work_group_size, generate
2881 // OpSpecConstants for x/y/z dimension.
2882 if (!HasMD) {
2883 //
2884 // Generate OpSpecConstants for x/y/z dimension.
2885 //
2886 // Ops[0] : Result Type ID
2887 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
2888 uint32_t XDimCstID = 0;
2889 uint32_t YDimCstID = 0;
2890 uint32_t ZDimCstID = 0;
2891
David Neto22f144c2017-06-12 14:26:21 -04002892 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04002893 uint32_t result_type_id =
2894 lookupType(Ty->getPointerElementType()->getSequentialElementType());
David Neto22f144c2017-06-12 14:26:21 -04002895
David Neto257c3892018-04-11 13:19:45 -04002896 // X Dimension
2897 Ops << MkId(result_type_id) << MkNum(1);
2898 XDimCstID = nextID++;
2899 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002900 new SPIRVInstruction(spv::OpSpecConstant, XDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002901
2902 // Y Dimension
2903 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002904 Ops << MkId(result_type_id) << MkNum(1);
2905 YDimCstID = nextID++;
2906 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002907 new SPIRVInstruction(spv::OpSpecConstant, YDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002908
2909 // Z Dimension
2910 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002911 Ops << MkId(result_type_id) << MkNum(1);
2912 ZDimCstID = nextID++;
2913 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002914 new SPIRVInstruction(spv::OpSpecConstant, ZDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002915
David Neto257c3892018-04-11 13:19:45 -04002916 BuiltinDimVec.push_back(XDimCstID);
2917 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002918 BuiltinDimVec.push_back(ZDimCstID);
2919
David Neto22f144c2017-06-12 14:26:21 -04002920 //
2921 // Generate OpSpecConstantComposite.
2922 //
2923 // Ops[0] : Result Type ID
2924 // Ops[1] : Constant size for x dimension.
2925 // Ops[2] : Constant size for y dimension.
2926 // Ops[3] : Constant size for z dimension.
2927 InitializerID = nextID;
2928
2929 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002930 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2931 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002932
David Neto87846742018-04-11 17:36:22 -04002933 auto *Inst =
2934 new SPIRVInstruction(spv::OpSpecConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002935 SPIRVInstList.push_back(Inst);
2936 }
2937 }
2938
David Neto22f144c2017-06-12 14:26:21 -04002939 VMap[&GV] = nextID;
2940
2941 //
2942 // Generate OpVariable.
2943 //
2944 // GIDOps[0] : Result Type ID
2945 // GIDOps[1] : Storage Class
2946 SPIRVOperandList Ops;
2947
David Neto85082642018-03-24 06:55:20 -07002948 const auto AS = PTy->getAddressSpace();
David Netoc6f3ab22018-04-06 18:02:31 -04002949 Ops << MkId(lookupType(Ty)) << MkNum(GetStorageClass(AS));
David Neto22f144c2017-06-12 14:26:21 -04002950
David Neto85082642018-03-24 06:55:20 -07002951 const bool module_scope_constant_external_init =
David Neto862b7d82018-06-14 18:48:37 -04002952 (AS == AddressSpace::Constant) && GV.hasInitializer() &&
David Neto85082642018-03-24 06:55:20 -07002953 clspv::Option::ModuleConstantsInStorageBuffer();
2954
Kévin Petit23d5f182019-08-13 16:21:29 +01002955 if (GV.hasInitializer()) {
2956 auto GVInit = GV.getInitializer();
2957 if (!isa<UndefValue>(GVInit) && !module_scope_constant_external_init) {
2958 assert(VMap.count(GVInit) == 1);
2959 InitializerID = VMap[GVInit];
David Neto85082642018-03-24 06:55:20 -07002960 }
2961 }
Kévin Petit23d5f182019-08-13 16:21:29 +01002962
2963 if (0 != InitializerID) {
2964 // Emit the ID of the intiializer as part of the variable definition.
2965 Ops << MkId(InitializerID);
2966 }
David Neto85082642018-03-24 06:55:20 -07002967 const uint32_t var_id = nextID++;
2968
David Neto87846742018-04-11 17:36:22 -04002969 auto *Inst = new SPIRVInstruction(spv::OpVariable, var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002970 SPIRVInstList.push_back(Inst);
2971
2972 // If we have a builtin.
2973 if (spv::BuiltInMax != BuiltinType) {
2974 // Find Insert Point for OpDecorate.
2975 auto DecoInsertPoint =
2976 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2977 [](SPIRVInstruction *Inst) -> bool {
2978 return Inst->getOpcode() != spv::OpDecorate &&
2979 Inst->getOpcode() != spv::OpMemberDecorate &&
2980 Inst->getOpcode() != spv::OpExtInstImport;
2981 });
2982 //
2983 // Generate OpDecorate.
2984 //
2985 // DOps[0] = Target ID
2986 // DOps[1] = Decoration (Builtin)
2987 // DOps[2] = BuiltIn ID
2988 uint32_t ResultID;
2989
2990 // WorkgroupSize is different, we decorate the constant composite that has
2991 // its value, rather than the variable that we use to access the value.
2992 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2993 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04002994 // Save both the value and variable IDs for later.
2995 WorkgroupSizeValueID = InitializerID;
2996 WorkgroupSizeVarID = VMap[&GV];
David Neto22f144c2017-06-12 14:26:21 -04002997 } else {
2998 ResultID = VMap[&GV];
2999 }
3000
3001 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04003002 DOps << MkId(ResultID) << MkNum(spv::DecorationBuiltIn)
3003 << MkNum(BuiltinType);
David Neto22f144c2017-06-12 14:26:21 -04003004
David Neto87846742018-04-11 17:36:22 -04003005 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, DOps);
David Neto22f144c2017-06-12 14:26:21 -04003006 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
David Neto85082642018-03-24 06:55:20 -07003007 } else if (module_scope_constant_external_init) {
3008 // This module scope constant is initialized from a storage buffer with data
3009 // provided by the host at binding 0 of the next descriptor set.
David Neto78383442018-06-15 20:31:56 -04003010 const uint32_t descriptor_set = TakeDescriptorIndex(&M);
David Neto85082642018-03-24 06:55:20 -07003011
David Neto862b7d82018-06-14 18:48:37 -04003012 // Emit the intializer to the descriptor map file.
David Neto85082642018-03-24 06:55:20 -07003013 // Use "kind,buffer" to indicate storage buffer. We might want to expand
3014 // that later to other types, like uniform buffer.
alan-bakerf5e5f692018-11-27 08:33:24 -05003015 std::string hexbytes;
3016 llvm::raw_string_ostream str(hexbytes);
3017 clspv::ConstantEmitter(DL, str).Emit(GV.getInitializer());
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003018 version0::DescriptorMapEntry::ConstantData constant_data = {ArgKind::Buffer,
3019 str.str()};
3020 descriptorMapEntries->emplace_back(std::move(constant_data), descriptor_set,
3021 0);
David Neto85082642018-03-24 06:55:20 -07003022
3023 // Find Insert Point for OpDecorate.
3024 auto DecoInsertPoint =
3025 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
3026 [](SPIRVInstruction *Inst) -> bool {
3027 return Inst->getOpcode() != spv::OpDecorate &&
3028 Inst->getOpcode() != spv::OpMemberDecorate &&
3029 Inst->getOpcode() != spv::OpExtInstImport;
3030 });
3031
David Neto257c3892018-04-11 13:19:45 -04003032 // OpDecorate %var Binding <binding>
David Neto85082642018-03-24 06:55:20 -07003033 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04003034 DOps << MkId(var_id) << MkNum(spv::DecorationBinding) << MkNum(0);
3035 DecoInsertPoint = SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003036 DecoInsertPoint, new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto85082642018-03-24 06:55:20 -07003037
3038 // OpDecorate %var DescriptorSet <descriptor_set>
3039 DOps.clear();
David Neto257c3892018-04-11 13:19:45 -04003040 DOps << MkId(var_id) << MkNum(spv::DecorationDescriptorSet)
3041 << MkNum(descriptor_set);
David Netoc6f3ab22018-04-06 18:02:31 -04003042 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04003043 new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto22f144c2017-06-12 14:26:21 -04003044 }
3045}
3046
David Netoc6f3ab22018-04-06 18:02:31 -04003047void SPIRVProducerPass::GenerateWorkgroupVars() {
3048 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
Alan Baker202c8c72018-08-13 13:47:44 -04003049 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
3050 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05003051 LocalArgInfo &info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04003052
3053 // Generate OpVariable.
3054 //
3055 // GIDOps[0] : Result Type ID
3056 // GIDOps[1] : Storage Class
3057 SPIRVOperandList Ops;
3058 Ops << MkId(info.ptr_array_type_id) << MkNum(spv::StorageClassWorkgroup);
3059
3060 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04003061 new SPIRVInstruction(spv::OpVariable, info.variable_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04003062 }
3063}
3064
David Neto862b7d82018-06-14 18:48:37 -04003065void SPIRVProducerPass::GenerateDescriptorMapInfo(const DataLayout &DL,
3066 Function &F) {
David Netoc5fb5242018-07-30 13:28:31 -04003067 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3068 return;
3069 }
David Neto862b7d82018-06-14 18:48:37 -04003070 // Gather the list of resources that are used by this function's arguments.
3071 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
3072
alan-bakerf5e5f692018-11-27 08:33:24 -05003073 // TODO(alan-baker): This should become unnecessary by fixing the rest of the
3074 // flow to generate pod_ubo arguments earlier.
David Neto862b7d82018-06-14 18:48:37 -04003075 auto remap_arg_kind = [](StringRef argKind) {
alan-bakerf5e5f692018-11-27 08:33:24 -05003076 std::string kind =
3077 clspv::Option::PodArgsInUniformBuffer() && argKind.equals("pod")
3078 ? "pod_ubo"
3079 : argKind;
3080 return GetArgKindFromName(kind);
David Neto862b7d82018-06-14 18:48:37 -04003081 };
3082
3083 auto *fty = F.getType()->getPointerElementType();
3084 auto *func_ty = dyn_cast<FunctionType>(fty);
3085
alan-baker038e9242019-04-19 22:14:41 -04003086 // If we've clustered POD arguments, then argument details are in metadata.
David Neto862b7d82018-06-14 18:48:37 -04003087 // If an argument maps to a resource variable, then get descriptor set and
3088 // binding from the resoure variable. Other info comes from the metadata.
3089 const auto *arg_map = F.getMetadata("kernel_arg_map");
3090 if (arg_map) {
3091 for (const auto &arg : arg_map->operands()) {
3092 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
Kévin PETITa353c832018-03-20 23:21:21 +00003093 assert(arg_node->getNumOperands() == 7);
David Neto862b7d82018-06-14 18:48:37 -04003094 const auto name =
3095 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
3096 const auto old_index =
3097 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
3098 // Remapped argument index
alan-bakerb6b09dc2018-11-08 16:59:28 -05003099 const size_t new_index = static_cast<size_t>(
3100 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04003101 const auto offset =
3102 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
Kévin PETITa353c832018-03-20 23:21:21 +00003103 const auto arg_size =
3104 dyn_extract<ConstantInt>(arg_node->getOperand(4))->getZExtValue();
David Neto862b7d82018-06-14 18:48:37 -04003105 const auto argKind = remap_arg_kind(
Kévin PETITa353c832018-03-20 23:21:21 +00003106 dyn_cast<MDString>(arg_node->getOperand(5))->getString());
David Neto862b7d82018-06-14 18:48:37 -04003107 const auto spec_id =
Kévin PETITa353c832018-03-20 23:21:21 +00003108 dyn_extract<ConstantInt>(arg_node->getOperand(6))->getSExtValue();
alan-bakerf5e5f692018-11-27 08:33:24 -05003109
3110 uint32_t descriptor_set = 0;
3111 uint32_t binding = 0;
3112 version0::DescriptorMapEntry::KernelArgData kernel_data = {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003113 F.getName(), name, static_cast<uint32_t>(old_index), argKind,
alan-bakerf5e5f692018-11-27 08:33:24 -05003114 static_cast<uint32_t>(spec_id),
3115 // This will be set below for pointer-to-local args.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003116 0, static_cast<uint32_t>(offset), static_cast<uint32_t>(arg_size)};
David Neto862b7d82018-06-14 18:48:37 -04003117 if (spec_id > 0) {
alan-bakerf5e5f692018-11-27 08:33:24 -05003118 kernel_data.local_element_size = static_cast<uint32_t>(GetTypeAllocSize(
3119 func_ty->getParamType(unsigned(new_index))->getPointerElementType(),
3120 DL));
David Neto862b7d82018-06-14 18:48:37 -04003121 } else {
3122 auto *info = resource_var_at_index[new_index];
3123 assert(info);
alan-bakerf5e5f692018-11-27 08:33:24 -05003124 descriptor_set = info->descriptor_set;
3125 binding = info->binding;
David Neto862b7d82018-06-14 18:48:37 -04003126 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003127 descriptorMapEntries->emplace_back(std::move(kernel_data), descriptor_set,
3128 binding);
David Neto862b7d82018-06-14 18:48:37 -04003129 }
3130 } else {
3131 // There is no argument map.
3132 // Take descriptor info from the resource variable calls.
Kévin PETITa353c832018-03-20 23:21:21 +00003133 // Take argument name and size from the arguments list.
David Neto862b7d82018-06-14 18:48:37 -04003134
3135 SmallVector<Argument *, 4> arguments;
3136 for (auto &arg : F.args()) {
3137 arguments.push_back(&arg);
3138 }
3139
3140 unsigned arg_index = 0;
3141 for (auto *info : resource_var_at_index) {
3142 if (info) {
Kévin PETITa353c832018-03-20 23:21:21 +00003143 auto arg = arguments[arg_index];
alan-bakerb6b09dc2018-11-08 16:59:28 -05003144 unsigned arg_size = 0;
Kévin PETITa353c832018-03-20 23:21:21 +00003145 if (info->arg_kind == clspv::ArgKind::Pod) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05003146 arg_size = static_cast<uint32_t>(DL.getTypeStoreSize(arg->getType()));
Kévin PETITa353c832018-03-20 23:21:21 +00003147 }
3148
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003149 // Local pointer arguments are unused in this case. Offset is always
3150 // zero.
alan-bakerf5e5f692018-11-27 08:33:24 -05003151 version0::DescriptorMapEntry::KernelArgData kernel_data = {
3152 F.getName(), arg->getName(),
3153 arg_index, remap_arg_kind(clspv::GetArgKindName(info->arg_kind)),
3154 0, 0,
3155 0, arg_size};
3156 descriptorMapEntries->emplace_back(std::move(kernel_data),
3157 info->descriptor_set, info->binding);
David Neto862b7d82018-06-14 18:48:37 -04003158 }
3159 arg_index++;
3160 }
3161 // Generate mappings for pointer-to-local arguments.
3162 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
3163 Argument *arg = arguments[arg_index];
Alan Baker202c8c72018-08-13 13:47:44 -04003164 auto where = LocalArgSpecIds.find(arg);
3165 if (where != LocalArgSpecIds.end()) {
3166 auto &local_arg_info = LocalSpecIdInfoMap[where->second];
alan-bakerf5e5f692018-11-27 08:33:24 -05003167 // Pod arguments members are unused in this case.
3168 version0::DescriptorMapEntry::KernelArgData kernel_data = {
3169 F.getName(),
3170 arg->getName(),
3171 arg_index,
3172 ArgKind::Local,
3173 static_cast<uint32_t>(local_arg_info.spec_id),
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003174 static_cast<uint32_t>(
3175 GetTypeAllocSize(local_arg_info.elem_type, DL)),
alan-bakerf5e5f692018-11-27 08:33:24 -05003176 0,
3177 0};
3178 // Pointer-to-local arguments do not utilize descriptor set and binding.
3179 descriptorMapEntries->emplace_back(std::move(kernel_data), 0, 0);
David Neto862b7d82018-06-14 18:48:37 -04003180 }
3181 }
3182 }
3183}
3184
David Neto22f144c2017-06-12 14:26:21 -04003185void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
3186 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3187 ValueMapType &VMap = getValueMap();
3188 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04003189 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
3190 auto &GlobalConstArgSet = getGlobalConstArgSet();
3191
3192 FunctionType *FTy = F.getFunctionType();
3193
3194 //
David Neto22f144c2017-06-12 14:26:21 -04003195 // Generate OPFunction.
3196 //
3197
3198 // FOps[0] : Result Type ID
3199 // FOps[1] : Function Control
3200 // FOps[2] : Function Type ID
3201 SPIRVOperandList FOps;
3202
3203 // Find SPIRV instruction for return type.
David Neto257c3892018-04-11 13:19:45 -04003204 FOps << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04003205
3206 // Check function attributes for SPIRV Function Control.
3207 uint32_t FuncControl = spv::FunctionControlMaskNone;
3208 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
3209 FuncControl |= spv::FunctionControlInlineMask;
3210 }
3211 if (F.hasFnAttribute(Attribute::NoInline)) {
3212 FuncControl |= spv::FunctionControlDontInlineMask;
3213 }
3214 // TODO: Check llvm attribute for Function Control Pure.
3215 if (F.hasFnAttribute(Attribute::ReadOnly)) {
3216 FuncControl |= spv::FunctionControlPureMask;
3217 }
3218 // TODO: Check llvm attribute for Function Control Const.
3219 if (F.hasFnAttribute(Attribute::ReadNone)) {
3220 FuncControl |= spv::FunctionControlConstMask;
3221 }
3222
David Neto257c3892018-04-11 13:19:45 -04003223 FOps << MkNum(FuncControl);
David Neto22f144c2017-06-12 14:26:21 -04003224
3225 uint32_t FTyID;
3226 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3227 SmallVector<Type *, 4> NewFuncParamTys;
3228 FunctionType *NewFTy =
3229 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
3230 FTyID = lookupType(NewFTy);
3231 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07003232 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04003233 if (GlobalConstFuncTyMap.count(FTy)) {
3234 FTyID = lookupType(GlobalConstFuncTyMap[FTy].first);
3235 } else {
3236 FTyID = lookupType(FTy);
3237 }
3238 }
3239
David Neto257c3892018-04-11 13:19:45 -04003240 FOps << MkId(FTyID);
David Neto22f144c2017-06-12 14:26:21 -04003241
3242 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3243 EntryPoints.push_back(std::make_pair(&F, nextID));
3244 }
3245
3246 VMap[&F] = nextID;
3247
David Neto482550a2018-03-24 05:21:07 -07003248 if (clspv::Option::ShowIDs()) {
David Netob05675d2018-02-16 12:37:49 -05003249 errs() << "Function " << F.getName() << " is " << nextID << "\n";
3250 }
David Neto22f144c2017-06-12 14:26:21 -04003251 // Generate SPIRV instruction for function.
David Neto87846742018-04-11 17:36:22 -04003252 auto *FuncInst = new SPIRVInstruction(spv::OpFunction, nextID++, FOps);
David Neto22f144c2017-06-12 14:26:21 -04003253 SPIRVInstList.push_back(FuncInst);
3254
3255 //
3256 // Generate OpFunctionParameter for Normal function.
3257 //
3258
3259 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
alan-bakere9308012019-03-15 10:25:13 -04003260
3261 // Find Insert Point for OpDecorate.
3262 auto DecoInsertPoint =
3263 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
3264 [](SPIRVInstruction *Inst) -> bool {
3265 return Inst->getOpcode() != spv::OpDecorate &&
3266 Inst->getOpcode() != spv::OpMemberDecorate &&
3267 Inst->getOpcode() != spv::OpExtInstImport;
3268 });
3269
David Neto22f144c2017-06-12 14:26:21 -04003270 // Iterate Argument for name instead of param type from function type.
3271 unsigned ArgIdx = 0;
3272 for (Argument &Arg : F.args()) {
alan-bakere9308012019-03-15 10:25:13 -04003273 uint32_t param_id = nextID++;
3274 VMap[&Arg] = param_id;
3275
3276 if (CalledWithCoherentResource(Arg)) {
3277 // If the arg is passed a coherent resource ever, then decorate this
3278 // parameter with Coherent too.
3279 SPIRVOperandList decoration_ops;
3280 decoration_ops << MkId(param_id) << MkNum(spv::DecorationCoherent);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003281 SPIRVInstList.insert(
3282 DecoInsertPoint,
3283 new SPIRVInstruction(spv::OpDecorate, decoration_ops));
alan-bakere9308012019-03-15 10:25:13 -04003284 }
David Neto22f144c2017-06-12 14:26:21 -04003285
3286 // ParamOps[0] : Result Type ID
3287 SPIRVOperandList ParamOps;
3288
3289 // Find SPIRV instruction for parameter type.
3290 uint32_t ParamTyID = lookupType(Arg.getType());
3291 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
3292 if (GlobalConstFuncTyMap.count(FTy)) {
3293 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
3294 Type *EleTy = PTy->getPointerElementType();
3295 Type *ArgTy =
3296 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
3297 ParamTyID = lookupType(ArgTy);
3298 GlobalConstArgSet.insert(&Arg);
3299 }
3300 }
3301 }
David Neto257c3892018-04-11 13:19:45 -04003302 ParamOps << MkId(ParamTyID);
David Neto22f144c2017-06-12 14:26:21 -04003303
3304 // Generate SPIRV instruction for parameter.
David Neto87846742018-04-11 17:36:22 -04003305 auto *ParamInst =
alan-bakere9308012019-03-15 10:25:13 -04003306 new SPIRVInstruction(spv::OpFunctionParameter, param_id, ParamOps);
David Neto22f144c2017-06-12 14:26:21 -04003307 SPIRVInstList.push_back(ParamInst);
3308
3309 ArgIdx++;
3310 }
3311 }
3312}
3313
alan-bakerb6b09dc2018-11-08 16:59:28 -05003314void SPIRVProducerPass::GenerateModuleInfo(Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04003315 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3316 EntryPointVecType &EntryPoints = getEntryPointVec();
3317 ValueMapType &VMap = getValueMap();
3318 ValueList &EntryPointInterfaces = getEntryPointInterfacesVec();
3319 uint32_t &ExtInstImportID = getOpExtInstImportID();
3320 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
3321
3322 // Set up insert point.
3323 auto InsertPoint = SPIRVInstList.begin();
3324
3325 //
3326 // Generate OpCapability
3327 //
3328 // TODO: Which llvm information is mapped to SPIRV Capapbility?
3329
3330 // Ops[0] = Capability
3331 SPIRVOperandList Ops;
3332
David Neto87846742018-04-11 17:36:22 -04003333 auto *CapInst =
David Netoef5ba2b2019-12-20 08:35:54 -05003334 new SPIRVInstruction(spv::OpCapability, MkNum(spv::CapabilityShader));
David Neto22f144c2017-06-12 14:26:21 -04003335 SPIRVInstList.insert(InsertPoint, CapInst);
3336
alan-bakerf906d2b2019-12-10 11:26:23 -05003337 bool write_without_format = false;
3338 bool sampled_1d = false;
3339 bool image_1d = false;
David Neto22f144c2017-06-12 14:26:21 -04003340 for (Type *Ty : getTypeList()) {
alan-bakerb39c8262019-03-08 14:03:37 -05003341 if (clspv::Option::Int8Support() && Ty->isIntegerTy(8)) {
3342 // Generate OpCapability for i8 type.
David Netoef5ba2b2019-12-20 08:35:54 -05003343 SPIRVInstList.insert(
3344 InsertPoint,
3345 new SPIRVInstruction(spv::OpCapability, MkNum(spv::CapabilityInt8)));
alan-bakerb39c8262019-03-08 14:03:37 -05003346 } else if (Ty->isIntegerTy(16)) {
David Neto22f144c2017-06-12 14:26:21 -04003347 // Generate OpCapability for i16 type.
David Netoef5ba2b2019-12-20 08:35:54 -05003348 SPIRVInstList.insert(
3349 InsertPoint,
3350 new SPIRVInstruction(spv::OpCapability, MkNum(spv::CapabilityInt16)));
David Neto22f144c2017-06-12 14:26:21 -04003351 } else if (Ty->isIntegerTy(64)) {
3352 // Generate OpCapability for i64 type.
David Netoef5ba2b2019-12-20 08:35:54 -05003353 SPIRVInstList.insert(
3354 InsertPoint,
3355 new SPIRVInstruction(spv::OpCapability, MkNum(spv::CapabilityInt64)));
David Neto22f144c2017-06-12 14:26:21 -04003356 } else if (Ty->isHalfTy()) {
3357 // Generate OpCapability for half type.
David Netoef5ba2b2019-12-20 08:35:54 -05003358 SPIRVInstList.insert(InsertPoint,
3359 new SPIRVInstruction(spv::OpCapability,
3360 MkNum(spv::CapabilityFloat16)));
David Neto22f144c2017-06-12 14:26:21 -04003361 } else if (Ty->isDoubleTy()) {
3362 // Generate OpCapability for double type.
David Netoef5ba2b2019-12-20 08:35:54 -05003363 SPIRVInstList.insert(InsertPoint,
3364 new SPIRVInstruction(spv::OpCapability,
3365 MkNum(spv::CapabilityFloat64)));
David Neto22f144c2017-06-12 14:26:21 -04003366 } else if (auto *STy = dyn_cast<StructType>(Ty)) {
3367 if (STy->isOpaque()) {
alan-bakerf906d2b2019-12-10 11:26:23 -05003368 if (STy->getName().startswith("opencl.image1d_wo_t") ||
3369 STy->getName().startswith("opencl.image2d_wo_t") ||
alan-bakerf67468c2019-11-25 15:51:49 -05003370 STy->getName().startswith("opencl.image3d_wo_t")) {
alan-bakerf906d2b2019-12-10 11:26:23 -05003371 write_without_format = true;
3372 }
3373 if (STy->getName().startswith("opencl.image1d_ro_t") ||
3374 STy->getName().startswith("opencl.image1d_wo_t")) {
3375 if (STy->getName().contains(".sampled"))
3376 sampled_1d = true;
3377 else
3378 image_1d = true;
David Neto22f144c2017-06-12 14:26:21 -04003379 }
3380 }
3381 }
3382 }
3383
alan-bakerf906d2b2019-12-10 11:26:23 -05003384 if (write_without_format) {
3385 // Generate OpCapability for write only image type.
3386 SPIRVInstList.insert(
3387 InsertPoint,
3388 new SPIRVInstruction(
3389 spv::OpCapability,
3390 {MkNum(spv::CapabilityStorageImageWriteWithoutFormat)}));
3391 }
3392 if (image_1d) {
3393 // Generate OpCapability for unsampled 1D image type.
3394 SPIRVInstList.insert(InsertPoint,
3395 new SPIRVInstruction(spv::OpCapability,
3396 {MkNum(spv::CapabilityImage1D)}));
3397 } else if (sampled_1d) {
3398 // Generate OpCapability for sampled 1D image type.
3399 SPIRVInstList.insert(
3400 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3401 {MkNum(spv::CapabilitySampled1D)}));
3402 }
3403
David Neto5c22a252018-03-15 16:07:41 -04003404 { // OpCapability ImageQuery
3405 bool hasImageQuery = false;
alan-bakerf67468c2019-11-25 15:51:49 -05003406 for (const auto &SymVal : module.getValueSymbolTable()) {
3407 if (auto F = dyn_cast<Function>(SymVal.getValue())) {
alan-bakerce179f12019-12-06 19:02:22 -05003408 if (clspv::IsImageQuery(F)) {
alan-bakerf67468c2019-11-25 15:51:49 -05003409 hasImageQuery = true;
3410 break;
3411 }
David Neto5c22a252018-03-15 16:07:41 -04003412 }
3413 }
alan-bakerf67468c2019-11-25 15:51:49 -05003414
David Neto5c22a252018-03-15 16:07:41 -04003415 if (hasImageQuery) {
David Neto87846742018-04-11 17:36:22 -04003416 auto *ImageQueryCapInst = new SPIRVInstruction(
3417 spv::OpCapability, {MkNum(spv::CapabilityImageQuery)});
David Neto5c22a252018-03-15 16:07:41 -04003418 SPIRVInstList.insert(InsertPoint, ImageQueryCapInst);
3419 }
3420 }
3421
David Neto22f144c2017-06-12 14:26:21 -04003422 if (hasVariablePointers()) {
3423 //
David Neto22f144c2017-06-12 14:26:21 -04003424 // Generate OpCapability.
3425 //
3426 // Ops[0] = Capability
3427 //
3428 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003429 Ops << MkNum(spv::CapabilityVariablePointers);
David Neto22f144c2017-06-12 14:26:21 -04003430
David Neto87846742018-04-11 17:36:22 -04003431 SPIRVInstList.insert(InsertPoint,
3432 new SPIRVInstruction(spv::OpCapability, Ops));
alan-baker5b86ed72019-02-15 08:26:50 -05003433 } else if (hasVariablePointersStorageBuffer()) {
3434 //
3435 // Generate OpCapability.
3436 //
3437 // Ops[0] = Capability
3438 //
3439 Ops.clear();
3440 Ops << MkNum(spv::CapabilityVariablePointersStorageBuffer);
David Neto22f144c2017-06-12 14:26:21 -04003441
alan-baker5b86ed72019-02-15 08:26:50 -05003442 SPIRVInstList.insert(InsertPoint,
3443 new SPIRVInstruction(spv::OpCapability, Ops));
3444 }
3445
3446 // Always add the storage buffer extension
3447 {
David Neto22f144c2017-06-12 14:26:21 -04003448 //
3449 // Generate OpExtension.
3450 //
3451 // Ops[0] = Name (Literal String)
3452 //
alan-baker5b86ed72019-02-15 08:26:50 -05003453 auto *ExtensionInst = new SPIRVInstruction(
3454 spv::OpExtension, {MkString("SPV_KHR_storage_buffer_storage_class")});
3455 SPIRVInstList.insert(InsertPoint, ExtensionInst);
3456 }
David Neto22f144c2017-06-12 14:26:21 -04003457
alan-baker5b86ed72019-02-15 08:26:50 -05003458 if (hasVariablePointers() || hasVariablePointersStorageBuffer()) {
3459 //
3460 // Generate OpExtension.
3461 //
3462 // Ops[0] = Name (Literal String)
3463 //
3464 auto *ExtensionInst = new SPIRVInstruction(
3465 spv::OpExtension, {MkString("SPV_KHR_variable_pointers")});
3466 SPIRVInstList.insert(InsertPoint, ExtensionInst);
David Neto22f144c2017-06-12 14:26:21 -04003467 }
3468
3469 if (ExtInstImportID) {
3470 ++InsertPoint;
3471 }
3472
3473 //
3474 // Generate OpMemoryModel
3475 //
3476 // Memory model for Vulkan will always be GLSL450.
3477
3478 // Ops[0] = Addressing Model
3479 // Ops[1] = Memory Model
3480 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003481 Ops << MkNum(spv::AddressingModelLogical) << MkNum(spv::MemoryModelGLSL450);
David Neto22f144c2017-06-12 14:26:21 -04003482
David Neto87846742018-04-11 17:36:22 -04003483 auto *MemModelInst = new SPIRVInstruction(spv::OpMemoryModel, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003484 SPIRVInstList.insert(InsertPoint, MemModelInst);
3485
3486 //
3487 // Generate OpEntryPoint
3488 //
3489 for (auto EntryPoint : EntryPoints) {
3490 // Ops[0] = Execution Model
3491 // Ops[1] = EntryPoint ID
3492 // Ops[2] = Name (Literal String)
3493 // ...
3494 //
3495 // TODO: Do we need to consider Interface ID for forward references???
3496 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003497 const StringRef &name = EntryPoint.first->getName();
David Neto257c3892018-04-11 13:19:45 -04003498 Ops << MkNum(spv::ExecutionModelGLCompute) << MkId(EntryPoint.second)
3499 << MkString(name);
David Neto22f144c2017-06-12 14:26:21 -04003500
David Neto22f144c2017-06-12 14:26:21 -04003501 for (Value *Interface : EntryPointInterfaces) {
David Neto257c3892018-04-11 13:19:45 -04003502 Ops << MkId(VMap[Interface]);
David Neto22f144c2017-06-12 14:26:21 -04003503 }
3504
David Neto87846742018-04-11 17:36:22 -04003505 auto *EntryPointInst = new SPIRVInstruction(spv::OpEntryPoint, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003506 SPIRVInstList.insert(InsertPoint, EntryPointInst);
3507 }
3508
3509 for (auto EntryPoint : EntryPoints) {
3510 if (const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
3511 ->getMetadata("reqd_work_group_size")) {
3512
3513 if (!BuiltinDimVec.empty()) {
3514 llvm_unreachable(
3515 "Kernels should have consistent work group size definition");
3516 }
3517
3518 //
3519 // Generate OpExecutionMode
3520 //
3521
3522 // Ops[0] = Entry Point ID
3523 // Ops[1] = Execution Mode
3524 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
3525 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003526 Ops << MkId(EntryPoint.second) << MkNum(spv::ExecutionModeLocalSize);
David Neto22f144c2017-06-12 14:26:21 -04003527
3528 uint32_t XDim = static_cast<uint32_t>(
3529 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3530 uint32_t YDim = static_cast<uint32_t>(
3531 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3532 uint32_t ZDim = static_cast<uint32_t>(
3533 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3534
David Neto257c3892018-04-11 13:19:45 -04003535 Ops << MkNum(XDim) << MkNum(YDim) << MkNum(ZDim);
David Neto22f144c2017-06-12 14:26:21 -04003536
David Neto87846742018-04-11 17:36:22 -04003537 auto *ExecModeInst = new SPIRVInstruction(spv::OpExecutionMode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003538 SPIRVInstList.insert(InsertPoint, ExecModeInst);
3539 }
3540 }
3541
3542 //
3543 // Generate OpSource.
3544 //
3545 // Ops[0] = SourceLanguage ID
3546 // Ops[1] = Version (LiteralNum)
3547 //
3548 Ops.clear();
Kévin Petitf0515712020-01-07 18:29:20 +00003549 switch (clspv::Option::Language()) {
3550 case clspv::Option::SourceLanguage::OpenCL_C_10:
3551 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(100);
3552 break;
3553 case clspv::Option::SourceLanguage::OpenCL_C_11:
3554 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(110);
3555 break;
3556 case clspv::Option::SourceLanguage::OpenCL_C_12:
Kévin Petit0fc88042019-04-09 23:25:02 +01003557 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(120);
Kévin Petitf0515712020-01-07 18:29:20 +00003558 break;
3559 case clspv::Option::SourceLanguage::OpenCL_C_20:
3560 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(200);
3561 break;
3562 case clspv::Option::SourceLanguage::OpenCL_CPP:
3563 Ops << MkNum(spv::SourceLanguageOpenCL_CPP) << MkNum(100);
3564 break;
3565 default:
3566 Ops << MkNum(spv::SourceLanguageUnknown) << MkNum(0);
3567 break;
Kévin Petit0fc88042019-04-09 23:25:02 +01003568 }
David Neto22f144c2017-06-12 14:26:21 -04003569
David Neto87846742018-04-11 17:36:22 -04003570 auto *OpenSourceInst = new SPIRVInstruction(spv::OpSource, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003571 SPIRVInstList.insert(InsertPoint, OpenSourceInst);
3572
3573 if (!BuiltinDimVec.empty()) {
3574 //
3575 // Generate OpDecorates for x/y/z dimension.
3576 //
3577 // Ops[0] = Target ID
3578 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04003579 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04003580
3581 // X Dimension
3582 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003583 Ops << MkId(BuiltinDimVec[0]) << MkNum(spv::DecorationSpecId) << MkNum(0);
David Neto87846742018-04-11 17:36:22 -04003584 SPIRVInstList.insert(InsertPoint,
3585 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003586
3587 // Y Dimension
3588 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003589 Ops << MkId(BuiltinDimVec[1]) << MkNum(spv::DecorationSpecId) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04003590 SPIRVInstList.insert(InsertPoint,
3591 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003592
3593 // Z Dimension
3594 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003595 Ops << MkId(BuiltinDimVec[2]) << MkNum(spv::DecorationSpecId) << MkNum(2);
David Neto87846742018-04-11 17:36:22 -04003596 SPIRVInstList.insert(InsertPoint,
3597 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003598 }
3599}
3600
David Netob6e2e062018-04-25 10:32:06 -04003601void SPIRVProducerPass::GenerateEntryPointInitialStores() {
3602 // Work around a driver bug. Initializers on Private variables might not
3603 // work. So the start of the kernel should store the initializer value to the
3604 // variables. Yes, *every* entry point pays this cost if *any* entry point
3605 // uses this builtin. At this point I judge this to be an acceptable tradeoff
3606 // of complexity vs. runtime, for a broken driver.
alan-bakerb6b09dc2018-11-08 16:59:28 -05003607 // TODO(dneto): Remove this at some point once fixed drivers are widely
3608 // available.
David Netob6e2e062018-04-25 10:32:06 -04003609 if (WorkgroupSizeVarID) {
3610 assert(WorkgroupSizeValueID);
3611
3612 SPIRVOperandList Ops;
3613 Ops << MkId(WorkgroupSizeVarID) << MkId(WorkgroupSizeValueID);
3614
3615 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
3616 getSPIRVInstList().push_back(Inst);
3617 }
3618}
3619
David Neto22f144c2017-06-12 14:26:21 -04003620void SPIRVProducerPass::GenerateFuncBody(Function &F) {
3621 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3622 ValueMapType &VMap = getValueMap();
3623
David Netob6e2e062018-04-25 10:32:06 -04003624 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04003625
3626 for (BasicBlock &BB : F) {
3627 // Register BasicBlock to ValueMap.
3628 VMap[&BB] = nextID;
3629
3630 //
3631 // Generate OpLabel for Basic Block.
3632 //
3633 SPIRVOperandList Ops;
David Neto87846742018-04-11 17:36:22 -04003634 auto *Inst = new SPIRVInstruction(spv::OpLabel, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003635 SPIRVInstList.push_back(Inst);
3636
David Neto6dcd4712017-06-23 11:06:47 -04003637 // OpVariable instructions must come first.
3638 for (Instruction &I : BB) {
alan-baker5b86ed72019-02-15 08:26:50 -05003639 if (auto *alloca = dyn_cast<AllocaInst>(&I)) {
3640 // Allocating a pointer requires variable pointers.
3641 if (alloca->getAllocatedType()->isPointerTy()) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003642 setVariablePointersCapabilities(
3643 alloca->getAllocatedType()->getPointerAddressSpace());
alan-baker5b86ed72019-02-15 08:26:50 -05003644 }
David Neto6dcd4712017-06-23 11:06:47 -04003645 GenerateInstruction(I);
3646 }
3647 }
3648
David Neto22f144c2017-06-12 14:26:21 -04003649 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04003650 if (clspv::Option::HackInitializers()) {
3651 GenerateEntryPointInitialStores();
3652 }
David Neto22f144c2017-06-12 14:26:21 -04003653 }
3654
3655 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003656 if (!isa<AllocaInst>(I)) {
3657 GenerateInstruction(I);
3658 }
David Neto22f144c2017-06-12 14:26:21 -04003659 }
3660 }
3661}
3662
3663spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3664 const std::map<CmpInst::Predicate, spv::Op> Map = {
3665 {CmpInst::ICMP_EQ, spv::OpIEqual},
3666 {CmpInst::ICMP_NE, spv::OpINotEqual},
3667 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3668 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3669 {CmpInst::ICMP_ULT, spv::OpULessThan},
3670 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3671 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3672 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3673 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3674 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3675 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3676 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3677 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3678 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3679 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3680 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3681 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3682 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3683 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3684 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3685 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3686 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3687
3688 assert(0 != Map.count(I->getPredicate()));
3689
3690 return Map.at(I->getPredicate());
3691}
3692
3693spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3694 const std::map<unsigned, spv::Op> Map{
3695 {Instruction::Trunc, spv::OpUConvert},
3696 {Instruction::ZExt, spv::OpUConvert},
3697 {Instruction::SExt, spv::OpSConvert},
3698 {Instruction::FPToUI, spv::OpConvertFToU},
3699 {Instruction::FPToSI, spv::OpConvertFToS},
3700 {Instruction::UIToFP, spv::OpConvertUToF},
3701 {Instruction::SIToFP, spv::OpConvertSToF},
3702 {Instruction::FPTrunc, spv::OpFConvert},
3703 {Instruction::FPExt, spv::OpFConvert},
3704 {Instruction::BitCast, spv::OpBitcast}};
3705
3706 assert(0 != Map.count(I.getOpcode()));
3707
3708 return Map.at(I.getOpcode());
3709}
3710
3711spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
Kévin Petit24272b62018-10-18 19:16:12 +00003712 if (I.getType()->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003713 switch (I.getOpcode()) {
3714 default:
3715 break;
3716 case Instruction::Or:
3717 return spv::OpLogicalOr;
3718 case Instruction::And:
3719 return spv::OpLogicalAnd;
3720 case Instruction::Xor:
3721 return spv::OpLogicalNotEqual;
3722 }
3723 }
3724
alan-bakerb6b09dc2018-11-08 16:59:28 -05003725 const std::map<unsigned, spv::Op> Map{
David Neto22f144c2017-06-12 14:26:21 -04003726 {Instruction::Add, spv::OpIAdd},
3727 {Instruction::FAdd, spv::OpFAdd},
3728 {Instruction::Sub, spv::OpISub},
3729 {Instruction::FSub, spv::OpFSub},
3730 {Instruction::Mul, spv::OpIMul},
3731 {Instruction::FMul, spv::OpFMul},
3732 {Instruction::UDiv, spv::OpUDiv},
3733 {Instruction::SDiv, spv::OpSDiv},
3734 {Instruction::FDiv, spv::OpFDiv},
3735 {Instruction::URem, spv::OpUMod},
3736 {Instruction::SRem, spv::OpSRem},
3737 {Instruction::FRem, spv::OpFRem},
3738 {Instruction::Or, spv::OpBitwiseOr},
3739 {Instruction::Xor, spv::OpBitwiseXor},
3740 {Instruction::And, spv::OpBitwiseAnd},
3741 {Instruction::Shl, spv::OpShiftLeftLogical},
3742 {Instruction::LShr, spv::OpShiftRightLogical},
3743 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3744
3745 assert(0 != Map.count(I.getOpcode()));
3746
3747 return Map.at(I.getOpcode());
3748}
3749
3750void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
3751 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3752 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04003753 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
3754 LLVMContext &Context = I.getParent()->getParent()->getParent()->getContext();
3755
3756 // Register Instruction to ValueMap.
3757 if (0 == VMap[&I]) {
3758 VMap[&I] = nextID;
3759 }
3760
3761 switch (I.getOpcode()) {
3762 default: {
3763 if (Instruction::isCast(I.getOpcode())) {
3764 //
3765 // Generate SPIRV instructions for cast operators.
3766 //
3767
David Netod2de94a2017-08-28 17:27:47 -04003768 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003769 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003770 auto toI8 = Ty == Type::getInt8Ty(Context);
3771 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003772 // Handle zext, sext and uitofp with i1 type specially.
3773 if ((I.getOpcode() == Instruction::ZExt ||
3774 I.getOpcode() == Instruction::SExt ||
3775 I.getOpcode() == Instruction::UIToFP) &&
alan-bakerb6b09dc2018-11-08 16:59:28 -05003776 OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003777 //
3778 // Generate OpSelect.
3779 //
3780
3781 // Ops[0] = Result Type ID
3782 // Ops[1] = Condition ID
3783 // Ops[2] = True Constant ID
3784 // Ops[3] = False Constant ID
3785 SPIRVOperandList Ops;
3786
David Neto257c3892018-04-11 13:19:45 -04003787 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003788
David Neto22f144c2017-06-12 14:26:21 -04003789 uint32_t CondID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003790 Ops << MkId(CondID);
David Neto22f144c2017-06-12 14:26:21 -04003791
3792 uint32_t TrueID = 0;
3793 if (I.getOpcode() == Instruction::ZExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00003794 TrueID = VMap[ConstantInt::get(I.getType(), 1)];
David Neto22f144c2017-06-12 14:26:21 -04003795 } else if (I.getOpcode() == Instruction::SExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00003796 TrueID = VMap[ConstantInt::getSigned(I.getType(), -1)];
David Neto22f144c2017-06-12 14:26:21 -04003797 } else {
3798 TrueID = VMap[ConstantFP::get(Context, APFloat(1.0f))];
3799 }
David Neto257c3892018-04-11 13:19:45 -04003800 Ops << MkId(TrueID);
David Neto22f144c2017-06-12 14:26:21 -04003801
3802 uint32_t FalseID = 0;
3803 if (I.getOpcode() == Instruction::ZExt) {
3804 FalseID = VMap[Constant::getNullValue(I.getType())];
3805 } else if (I.getOpcode() == Instruction::SExt) {
3806 FalseID = VMap[Constant::getNullValue(I.getType())];
3807 } else {
3808 FalseID = VMap[ConstantFP::get(Context, APFloat(0.0f))];
3809 }
David Neto257c3892018-04-11 13:19:45 -04003810 Ops << MkId(FalseID);
David Neto22f144c2017-06-12 14:26:21 -04003811
David Neto87846742018-04-11 17:36:22 -04003812 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003813 SPIRVInstList.push_back(Inst);
alan-bakerb39c8262019-03-08 14:03:37 -05003814 } else if (!clspv::Option::Int8Support() &&
3815 I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
David Netod2de94a2017-08-28 17:27:47 -04003816 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3817 // 8 bits.
3818 // Before:
3819 // %result = trunc i32 %a to i8
3820 // After
3821 // %result = OpBitwiseAnd %uint %a %uint_255
3822
3823 SPIRVOperandList Ops;
3824
David Neto257c3892018-04-11 13:19:45 -04003825 Ops << MkId(lookupType(OpTy)) << MkId(VMap[I.getOperand(0)]);
David Netod2de94a2017-08-28 17:27:47 -04003826
3827 Type *UintTy = Type::getInt32Ty(Context);
3828 uint32_t MaskID = VMap[ConstantInt::get(UintTy, 255)];
David Neto257c3892018-04-11 13:19:45 -04003829 Ops << MkId(MaskID);
David Netod2de94a2017-08-28 17:27:47 -04003830
David Neto87846742018-04-11 17:36:22 -04003831 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Netod2de94a2017-08-28 17:27:47 -04003832 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003833 } else {
3834 // Ops[0] = Result Type ID
3835 // Ops[1] = Source Value ID
3836 SPIRVOperandList Ops;
3837
David Neto257c3892018-04-11 13:19:45 -04003838 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003839
David Neto87846742018-04-11 17:36:22 -04003840 auto *Inst = new SPIRVInstruction(GetSPIRVCastOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003841 SPIRVInstList.push_back(Inst);
3842 }
3843 } else if (isa<BinaryOperator>(I)) {
3844 //
3845 // Generate SPIRV instructions for binary operators.
3846 //
3847
3848 // Handle xor with i1 type specially.
3849 if (I.getOpcode() == Instruction::Xor &&
3850 I.getType() == Type::getInt1Ty(Context) &&
Kévin Petit24272b62018-10-18 19:16:12 +00003851 ((isa<ConstantInt>(I.getOperand(0)) &&
3852 !cast<ConstantInt>(I.getOperand(0))->isZero()) ||
3853 (isa<ConstantInt>(I.getOperand(1)) &&
3854 !cast<ConstantInt>(I.getOperand(1))->isZero()))) {
David Neto22f144c2017-06-12 14:26:21 -04003855 //
3856 // Generate OpLogicalNot.
3857 //
3858 // Ops[0] = Result Type ID
3859 // Ops[1] = Operand
3860 SPIRVOperandList Ops;
3861
David Neto257c3892018-04-11 13:19:45 -04003862 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003863
3864 Value *CondV = I.getOperand(0);
3865 if (isa<Constant>(I.getOperand(0))) {
3866 CondV = I.getOperand(1);
3867 }
David Neto257c3892018-04-11 13:19:45 -04003868 Ops << MkId(VMap[CondV]);
David Neto22f144c2017-06-12 14:26:21 -04003869
David Neto87846742018-04-11 17:36:22 -04003870 auto *Inst = new SPIRVInstruction(spv::OpLogicalNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003871 SPIRVInstList.push_back(Inst);
3872 } else {
3873 // Ops[0] = Result Type ID
3874 // Ops[1] = Operand 0
3875 // Ops[2] = Operand 1
3876 SPIRVOperandList Ops;
3877
David Neto257c3892018-04-11 13:19:45 -04003878 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
3879 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003880
David Neto87846742018-04-11 17:36:22 -04003881 auto *Inst =
3882 new SPIRVInstruction(GetSPIRVBinaryOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003883 SPIRVInstList.push_back(Inst);
3884 }
alan-bakerc9c55ae2019-12-02 16:01:27 -05003885 } else if (I.getOpcode() == Instruction::FNeg) {
3886 // The only unary operator.
3887 //
3888 // Ops[0] = Result Type ID
3889 // Ops[1] = Operand 0
3890 SPIRVOperandList ops;
3891
3892 ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
3893 auto *Inst = new SPIRVInstruction(spv::OpFNegate, nextID++, ops);
3894 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003895 } else {
3896 I.print(errs());
3897 llvm_unreachable("Unsupported instruction???");
3898 }
3899 break;
3900 }
3901 case Instruction::GetElementPtr: {
3902 auto &GlobalConstArgSet = getGlobalConstArgSet();
3903
3904 //
3905 // Generate OpAccessChain.
3906 //
3907 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
3908
3909 //
3910 // Generate OpAccessChain.
3911 //
3912
3913 // Ops[0] = Result Type ID
3914 // Ops[1] = Base ID
3915 // Ops[2] ... Ops[n] = Indexes ID
3916 SPIRVOperandList Ops;
3917
alan-bakerb6b09dc2018-11-08 16:59:28 -05003918 PointerType *ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04003919 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
3920 GlobalConstArgSet.count(GEP->getPointerOperand())) {
3921 // Use pointer type with private address space for global constant.
3922 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04003923 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04003924 }
David Neto257c3892018-04-11 13:19:45 -04003925
3926 Ops << MkId(lookupType(ResultType));
David Neto22f144c2017-06-12 14:26:21 -04003927
David Neto862b7d82018-06-14 18:48:37 -04003928 // Generate the base pointer.
3929 Ops << MkId(VMap[GEP->getPointerOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04003930
David Neto862b7d82018-06-14 18:48:37 -04003931 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04003932
3933 //
3934 // Follows below rules for gep.
3935 //
David Neto862b7d82018-06-14 18:48:37 -04003936 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
3937 // first index.
David Neto22f144c2017-06-12 14:26:21 -04003938 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
3939 // first index.
3940 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
3941 // use gep's first index.
3942 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
3943 // gep's first index.
3944 //
3945 spv::Op Opcode = spv::OpAccessChain;
3946 unsigned offset = 0;
3947 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04003948 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04003949 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04003950 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04003951 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04003952 }
David Neto862b7d82018-06-14 18:48:37 -04003953 } else {
David Neto22f144c2017-06-12 14:26:21 -04003954 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04003955 }
3956
3957 if (Opcode == spv::OpPtrAccessChain) {
David Neto1a1a0582017-07-07 12:01:44 -04003958 // Do we need to generate ArrayStride? Check against the GEP result type
3959 // rather than the pointer type of the base because when indexing into
3960 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
3961 // for something else in the SPIR-V.
3962 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
alan-baker5b86ed72019-02-15 08:26:50 -05003963 auto address_space = ResultType->getAddressSpace();
3964 setVariablePointersCapabilities(address_space);
3965 switch (GetStorageClass(address_space)) {
Alan Bakerfcda9482018-10-02 17:09:59 -04003966 case spv::StorageClassStorageBuffer:
3967 case spv::StorageClassUniform:
David Neto1a1a0582017-07-07 12:01:44 -04003968 // Save the need to generate an ArrayStride decoration. But defer
3969 // generation until later, so we only make one decoration.
David Neto85082642018-03-24 06:55:20 -07003970 getTypesNeedingArrayStride().insert(ResultType);
Alan Bakerfcda9482018-10-02 17:09:59 -04003971 break;
3972 default:
3973 break;
David Neto1a1a0582017-07-07 12:01:44 -04003974 }
David Neto22f144c2017-06-12 14:26:21 -04003975 }
3976
3977 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
David Neto257c3892018-04-11 13:19:45 -04003978 Ops << MkId(VMap[*II]);
David Neto22f144c2017-06-12 14:26:21 -04003979 }
3980
David Neto87846742018-04-11 17:36:22 -04003981 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003982 SPIRVInstList.push_back(Inst);
3983 break;
3984 }
3985 case Instruction::ExtractValue: {
3986 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3987 // Ops[0] = Result Type ID
3988 // Ops[1] = Composite ID
3989 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3990 SPIRVOperandList Ops;
3991
David Neto257c3892018-04-11 13:19:45 -04003992 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003993
3994 uint32_t CompositeID = VMap[EVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003995 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003996
3997 for (auto &Index : EVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003998 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003999 }
4000
David Neto87846742018-04-11 17:36:22 -04004001 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004002 SPIRVInstList.push_back(Inst);
4003 break;
4004 }
4005 case Instruction::InsertValue: {
4006 InsertValueInst *IVI = cast<InsertValueInst>(&I);
4007 // Ops[0] = Result Type ID
4008 // Ops[1] = Object ID
4009 // Ops[2] = Composite ID
4010 // Ops[3] ... Ops[n] = Indexes (Literal Number)
4011 SPIRVOperandList Ops;
4012
4013 uint32_t ResTyID = lookupType(I.getType());
David Neto257c3892018-04-11 13:19:45 -04004014 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04004015
4016 uint32_t ObjectID = VMap[IVI->getInsertedValueOperand()];
David Neto257c3892018-04-11 13:19:45 -04004017 Ops << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04004018
4019 uint32_t CompositeID = VMap[IVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04004020 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04004021
4022 for (auto &Index : IVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04004023 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04004024 }
4025
David Neto87846742018-04-11 17:36:22 -04004026 auto *Inst = new SPIRVInstruction(spv::OpCompositeInsert, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004027 SPIRVInstList.push_back(Inst);
4028 break;
4029 }
4030 case Instruction::Select: {
4031 //
4032 // Generate OpSelect.
4033 //
4034
4035 // Ops[0] = Result Type ID
4036 // Ops[1] = Condition ID
4037 // Ops[2] = True Constant ID
4038 // Ops[3] = False Constant ID
4039 SPIRVOperandList Ops;
4040
4041 // Find SPIRV instruction for parameter type.
4042 auto Ty = I.getType();
4043 if (Ty->isPointerTy()) {
4044 auto PointeeTy = Ty->getPointerElementType();
4045 if (PointeeTy->isStructTy() &&
4046 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
4047 Ty = PointeeTy;
alan-baker5b86ed72019-02-15 08:26:50 -05004048 } else {
4049 // Selecting between pointers requires variable pointers.
4050 setVariablePointersCapabilities(Ty->getPointerAddressSpace());
4051 if (!hasVariablePointers() && !selectFromSameObject(&I)) {
4052 setVariablePointers(true);
4053 }
David Neto22f144c2017-06-12 14:26:21 -04004054 }
4055 }
4056
David Neto257c3892018-04-11 13:19:45 -04004057 Ops << MkId(lookupType(Ty)) << MkId(VMap[I.getOperand(0)])
4058 << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004059
David Neto87846742018-04-11 17:36:22 -04004060 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004061 SPIRVInstList.push_back(Inst);
4062 break;
4063 }
4064 case Instruction::ExtractElement: {
4065 // Handle <4 x i8> type manually.
4066 Type *CompositeTy = I.getOperand(0)->getType();
4067 if (is4xi8vec(CompositeTy)) {
4068 //
4069 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
4070 // <4 x i8>.
4071 //
4072
4073 //
4074 // Generate OpShiftRightLogical
4075 //
4076 // Ops[0] = Result Type ID
4077 // Ops[1] = Operand 0
4078 // Ops[2] = Operand 1
4079 //
4080 SPIRVOperandList Ops;
4081
David Neto257c3892018-04-11 13:19:45 -04004082 Ops << MkId(lookupType(CompositeTy));
David Neto22f144c2017-06-12 14:26:21 -04004083
4084 uint32_t Op0ID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04004085 Ops << MkId(Op0ID);
David Neto22f144c2017-06-12 14:26:21 -04004086
4087 uint32_t Op1ID = 0;
4088 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
4089 // Handle constant index.
4090 uint64_t Idx = CI->getZExtValue();
4091 Value *ShiftAmount =
4092 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
4093 Op1ID = VMap[ShiftAmount];
4094 } else {
4095 // Handle variable index.
4096 SPIRVOperandList TmpOps;
4097
David Neto257c3892018-04-11 13:19:45 -04004098 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
4099 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004100
4101 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04004102 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04004103
4104 Op1ID = nextID;
4105
David Neto87846742018-04-11 17:36:22 -04004106 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004107 SPIRVInstList.push_back(TmpInst);
4108 }
David Neto257c3892018-04-11 13:19:45 -04004109 Ops << MkId(Op1ID);
David Neto22f144c2017-06-12 14:26:21 -04004110
4111 uint32_t ShiftID = nextID;
4112
David Neto87846742018-04-11 17:36:22 -04004113 auto *Inst =
4114 new SPIRVInstruction(spv::OpShiftRightLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004115 SPIRVInstList.push_back(Inst);
4116
4117 //
4118 // Generate OpBitwiseAnd
4119 //
4120 // Ops[0] = Result Type ID
4121 // Ops[1] = Operand 0
4122 // Ops[2] = Operand 1
4123 //
4124 Ops.clear();
4125
David Neto257c3892018-04-11 13:19:45 -04004126 Ops << MkId(lookupType(CompositeTy)) << MkId(ShiftID);
David Neto22f144c2017-06-12 14:26:21 -04004127
4128 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
David Neto257c3892018-04-11 13:19:45 -04004129 Ops << MkId(VMap[CstFF]);
David Neto22f144c2017-06-12 14:26:21 -04004130
David Neto9b2d6252017-09-06 15:47:37 -04004131 // Reset mapping for this value to the result of the bitwise and.
4132 VMap[&I] = nextID;
4133
David Neto87846742018-04-11 17:36:22 -04004134 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004135 SPIRVInstList.push_back(Inst);
4136 break;
4137 }
4138
4139 // Ops[0] = Result Type ID
4140 // Ops[1] = Composite ID
4141 // Ops[2] ... Ops[n] = Indexes (Literal Number)
4142 SPIRVOperandList Ops;
4143
David Neto257c3892018-04-11 13:19:45 -04004144 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004145
4146 spv::Op Opcode = spv::OpCompositeExtract;
4147 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
David Neto257c3892018-04-11 13:19:45 -04004148 Ops << MkNum(static_cast<uint32_t>(CI->getZExtValue()));
David Neto22f144c2017-06-12 14:26:21 -04004149 } else {
David Neto257c3892018-04-11 13:19:45 -04004150 Ops << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004151 Opcode = spv::OpVectorExtractDynamic;
4152 }
4153
David Neto87846742018-04-11 17:36:22 -04004154 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004155 SPIRVInstList.push_back(Inst);
4156 break;
4157 }
4158 case Instruction::InsertElement: {
4159 // Handle <4 x i8> type manually.
4160 Type *CompositeTy = I.getOperand(0)->getType();
4161 if (is4xi8vec(CompositeTy)) {
4162 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
4163 uint32_t CstFFID = VMap[CstFF];
4164
4165 uint32_t ShiftAmountID = 0;
4166 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
4167 // Handle constant index.
4168 uint64_t Idx = CI->getZExtValue();
4169 Value *ShiftAmount =
4170 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
4171 ShiftAmountID = VMap[ShiftAmount];
4172 } else {
4173 // Handle variable index.
4174 SPIRVOperandList TmpOps;
4175
David Neto257c3892018-04-11 13:19:45 -04004176 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
4177 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004178
4179 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04004180 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04004181
4182 ShiftAmountID = nextID;
4183
David Neto87846742018-04-11 17:36:22 -04004184 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004185 SPIRVInstList.push_back(TmpInst);
4186 }
4187
4188 //
4189 // Generate mask operations.
4190 //
4191
4192 // ShiftLeft mask according to index of insertelement.
4193 SPIRVOperandList Ops;
4194
David Neto257c3892018-04-11 13:19:45 -04004195 const uint32_t ResTyID = lookupType(CompositeTy);
4196 Ops << MkId(ResTyID) << MkId(CstFFID) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004197
4198 uint32_t MaskID = nextID;
4199
David Neto87846742018-04-11 17:36:22 -04004200 auto *Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004201 SPIRVInstList.push_back(Inst);
4202
4203 // Inverse mask.
4204 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004205 Ops << MkId(ResTyID) << MkId(MaskID);
David Neto22f144c2017-06-12 14:26:21 -04004206
4207 uint32_t InvMaskID = nextID;
4208
David Neto87846742018-04-11 17:36:22 -04004209 Inst = new SPIRVInstruction(spv::OpNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004210 SPIRVInstList.push_back(Inst);
4211
4212 // Apply mask.
4213 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004214 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(0)]) << MkId(InvMaskID);
David Neto22f144c2017-06-12 14:26:21 -04004215
4216 uint32_t OrgValID = nextID;
4217
David Neto87846742018-04-11 17:36:22 -04004218 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004219 SPIRVInstList.push_back(Inst);
4220
4221 // Create correct value according to index of insertelement.
4222 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05004223 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(1)])
4224 << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004225
4226 uint32_t InsertValID = nextID;
4227
David Neto87846742018-04-11 17:36:22 -04004228 Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004229 SPIRVInstList.push_back(Inst);
4230
4231 // Insert value to original value.
4232 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004233 Ops << MkId(ResTyID) << MkId(OrgValID) << MkId(InsertValID);
David Neto22f144c2017-06-12 14:26:21 -04004234
David Netoa394f392017-08-26 20:45:29 -04004235 VMap[&I] = nextID;
4236
David Neto87846742018-04-11 17:36:22 -04004237 Inst = new SPIRVInstruction(spv::OpBitwiseOr, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004238 SPIRVInstList.push_back(Inst);
4239
4240 break;
4241 }
4242
David Neto22f144c2017-06-12 14:26:21 -04004243 SPIRVOperandList Ops;
4244
James Priced26efea2018-06-09 23:28:32 +01004245 // Ops[0] = Result Type ID
4246 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004247
4248 spv::Op Opcode = spv::OpCompositeInsert;
4249 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04004250 const auto value = CI->getZExtValue();
4251 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01004252 // Ops[1] = Object ID
4253 // Ops[2] = Composite ID
4254 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004255 Ops << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(0)])
James Priced26efea2018-06-09 23:28:32 +01004256 << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004257 } else {
James Priced26efea2018-06-09 23:28:32 +01004258 // Ops[1] = Composite ID
4259 // Ops[2] = Object ID
4260 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004261 Ops << MkId(VMap[I.getOperand(0)]) << MkId(VMap[I.getOperand(1)])
James Priced26efea2018-06-09 23:28:32 +01004262 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004263 Opcode = spv::OpVectorInsertDynamic;
4264 }
4265
David Neto87846742018-04-11 17:36:22 -04004266 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004267 SPIRVInstList.push_back(Inst);
4268 break;
4269 }
4270 case Instruction::ShuffleVector: {
4271 // Ops[0] = Result Type ID
4272 // Ops[1] = Vector 1 ID
4273 // Ops[2] = Vector 2 ID
4274 // Ops[3] ... Ops[n] = Components (Literal Number)
4275 SPIRVOperandList Ops;
4276
David Neto257c3892018-04-11 13:19:45 -04004277 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4278 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004279
4280 uint64_t NumElements = 0;
4281 if (Constant *Cst = dyn_cast<Constant>(I.getOperand(2))) {
4282 NumElements = cast<VectorType>(Cst->getType())->getNumElements();
4283
4284 if (Cst->isNullValue()) {
4285 for (unsigned i = 0; i < NumElements; i++) {
David Neto257c3892018-04-11 13:19:45 -04004286 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04004287 }
4288 } else if (const ConstantDataSequential *CDS =
4289 dyn_cast<ConstantDataSequential>(Cst)) {
4290 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
4291 std::vector<uint32_t> LiteralNum;
David Neto257c3892018-04-11 13:19:45 -04004292 const auto value = CDS->getElementAsInteger(i);
4293 assert(value <= UINT32_MAX);
4294 Ops << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004295 }
4296 } else if (const ConstantVector *CV = dyn_cast<ConstantVector>(Cst)) {
4297 for (unsigned i = 0; i < CV->getNumOperands(); i++) {
4298 auto Op = CV->getOperand(i);
4299
4300 uint32_t literal = 0;
4301
4302 if (auto CI = dyn_cast<ConstantInt>(Op)) {
4303 literal = static_cast<uint32_t>(CI->getZExtValue());
4304 } else if (auto UI = dyn_cast<UndefValue>(Op)) {
4305 literal = 0xFFFFFFFFu;
4306 } else {
4307 Op->print(errs());
4308 llvm_unreachable("Unsupported element in ConstantVector!");
4309 }
4310
David Neto257c3892018-04-11 13:19:45 -04004311 Ops << MkNum(literal);
David Neto22f144c2017-06-12 14:26:21 -04004312 }
4313 } else {
4314 Cst->print(errs());
4315 llvm_unreachable("Unsupported constant mask in ShuffleVector!");
4316 }
4317 }
4318
David Neto87846742018-04-11 17:36:22 -04004319 auto *Inst = new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004320 SPIRVInstList.push_back(Inst);
4321 break;
4322 }
4323 case Instruction::ICmp:
4324 case Instruction::FCmp: {
4325 CmpInst *CmpI = cast<CmpInst>(&I);
4326
David Netod4ca2e62017-07-06 18:47:35 -04004327 // Pointer equality is invalid.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004328 Type *ArgTy = CmpI->getOperand(0)->getType();
David Netod4ca2e62017-07-06 18:47:35 -04004329 if (isa<PointerType>(ArgTy)) {
4330 CmpI->print(errs());
4331 std::string name = I.getParent()->getParent()->getName();
4332 errs()
4333 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4334 << "in function " << name << "\n";
4335 llvm_unreachable("Pointer equality check is invalid");
4336 break;
4337 }
4338
David Neto257c3892018-04-11 13:19:45 -04004339 // Ops[0] = Result Type ID
4340 // Ops[1] = Operand 1 ID
4341 // Ops[2] = Operand 2 ID
4342 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004343
David Neto257c3892018-04-11 13:19:45 -04004344 Ops << MkId(lookupType(CmpI->getType())) << MkId(VMap[CmpI->getOperand(0)])
4345 << MkId(VMap[CmpI->getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004346
4347 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
David Neto87846742018-04-11 17:36:22 -04004348 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004349 SPIRVInstList.push_back(Inst);
4350 break;
4351 }
4352 case Instruction::Br: {
4353 // Branch instrucion is deferred because it needs label's ID. Record slot's
4354 // location on SPIRVInstructionList.
4355 DeferredInsts.push_back(
4356 std::make_tuple(&I, --SPIRVInstList.end(), 0 /* No id */));
4357 break;
4358 }
4359 case Instruction::Switch: {
4360 I.print(errs());
4361 llvm_unreachable("Unsupported instruction???");
4362 break;
4363 }
4364 case Instruction::IndirectBr: {
4365 I.print(errs());
4366 llvm_unreachable("Unsupported instruction???");
4367 break;
4368 }
4369 case Instruction::PHI: {
4370 // Branch instrucion is deferred because it needs label's ID. Record slot's
4371 // location on SPIRVInstructionList.
4372 DeferredInsts.push_back(
4373 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4374 break;
4375 }
4376 case Instruction::Alloca: {
4377 //
4378 // Generate OpVariable.
4379 //
4380 // Ops[0] : Result Type ID
4381 // Ops[1] : Storage Class
4382 SPIRVOperandList Ops;
4383
David Neto257c3892018-04-11 13:19:45 -04004384 Ops << MkId(lookupType(I.getType())) << MkNum(spv::StorageClassFunction);
David Neto22f144c2017-06-12 14:26:21 -04004385
David Neto87846742018-04-11 17:36:22 -04004386 auto *Inst = new SPIRVInstruction(spv::OpVariable, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004387 SPIRVInstList.push_back(Inst);
4388 break;
4389 }
4390 case Instruction::Load: {
4391 LoadInst *LD = cast<LoadInst>(&I);
4392 //
4393 // Generate OpLoad.
4394 //
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04004395
alan-baker5b86ed72019-02-15 08:26:50 -05004396 if (LD->getType()->isPointerTy()) {
4397 // Loading a pointer requires variable pointers.
4398 setVariablePointersCapabilities(LD->getType()->getPointerAddressSpace());
4399 }
David Neto22f144c2017-06-12 14:26:21 -04004400
David Neto0a2f98d2017-09-15 19:38:40 -04004401 uint32_t ResTyID = lookupType(LD->getType());
David Netoa60b00b2017-09-15 16:34:09 -04004402 uint32_t PointerID = VMap[LD->getPointerOperand()];
4403
4404 // This is a hack to work around what looks like a driver bug.
4405 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004406 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4407 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004408 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004409 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004410 // Generate a bitwise-and of the original value with itself.
4411 // We should have been able to get away with just an OpCopyObject,
4412 // but we need something more complex to get past certain driver bugs.
4413 // This is ridiculous, but necessary.
4414 // TODO(dneto): Revisit this once drivers fix their bugs.
4415
4416 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004417 Ops << MkId(ResTyID) << MkId(WorkgroupSizeValueID)
4418 << MkId(WorkgroupSizeValueID);
David Neto0a2f98d2017-09-15 19:38:40 -04004419
David Neto87846742018-04-11 17:36:22 -04004420 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto0a2f98d2017-09-15 19:38:40 -04004421 SPIRVInstList.push_back(Inst);
David Netoa60b00b2017-09-15 16:34:09 -04004422 break;
4423 }
4424
4425 // This is the normal path. Generate a load.
4426
David Neto22f144c2017-06-12 14:26:21 -04004427 // Ops[0] = Result Type ID
4428 // Ops[1] = Pointer ID
4429 // Ops[2] ... Ops[n] = Optional Memory Access
4430 //
4431 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004432
David Neto22f144c2017-06-12 14:26:21 -04004433 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004434 Ops << MkId(ResTyID) << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04004435
David Neto87846742018-04-11 17:36:22 -04004436 auto *Inst = new SPIRVInstruction(spv::OpLoad, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004437 SPIRVInstList.push_back(Inst);
4438 break;
4439 }
4440 case Instruction::Store: {
4441 StoreInst *ST = cast<StoreInst>(&I);
4442 //
4443 // Generate OpStore.
4444 //
4445
alan-baker5b86ed72019-02-15 08:26:50 -05004446 if (ST->getValueOperand()->getType()->isPointerTy()) {
4447 // Storing a pointer requires variable pointers.
4448 setVariablePointersCapabilities(
4449 ST->getValueOperand()->getType()->getPointerAddressSpace());
4450 }
4451
David Neto22f144c2017-06-12 14:26:21 -04004452 // Ops[0] = Pointer ID
4453 // Ops[1] = Object ID
4454 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4455 //
4456 // TODO: Do we need to implement Optional Memory Access???
David Neto257c3892018-04-11 13:19:45 -04004457 SPIRVOperandList Ops;
4458 Ops << MkId(VMap[ST->getPointerOperand()])
4459 << MkId(VMap[ST->getValueOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004460
David Neto87846742018-04-11 17:36:22 -04004461 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004462 SPIRVInstList.push_back(Inst);
4463 break;
4464 }
4465 case Instruction::AtomicCmpXchg: {
4466 I.print(errs());
4467 llvm_unreachable("Unsupported instruction???");
4468 break;
4469 }
4470 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004471 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4472
4473 spv::Op opcode;
4474
4475 switch (AtomicRMW->getOperation()) {
4476 default:
4477 I.print(errs());
4478 llvm_unreachable("Unsupported instruction???");
4479 case llvm::AtomicRMWInst::Add:
4480 opcode = spv::OpAtomicIAdd;
4481 break;
4482 case llvm::AtomicRMWInst::Sub:
4483 opcode = spv::OpAtomicISub;
4484 break;
4485 case llvm::AtomicRMWInst::Xchg:
4486 opcode = spv::OpAtomicExchange;
4487 break;
4488 case llvm::AtomicRMWInst::Min:
4489 opcode = spv::OpAtomicSMin;
4490 break;
4491 case llvm::AtomicRMWInst::Max:
4492 opcode = spv::OpAtomicSMax;
4493 break;
4494 case llvm::AtomicRMWInst::UMin:
4495 opcode = spv::OpAtomicUMin;
4496 break;
4497 case llvm::AtomicRMWInst::UMax:
4498 opcode = spv::OpAtomicUMax;
4499 break;
4500 case llvm::AtomicRMWInst::And:
4501 opcode = spv::OpAtomicAnd;
4502 break;
4503 case llvm::AtomicRMWInst::Or:
4504 opcode = spv::OpAtomicOr;
4505 break;
4506 case llvm::AtomicRMWInst::Xor:
4507 opcode = spv::OpAtomicXor;
4508 break;
4509 }
4510
4511 //
4512 // Generate OpAtomic*.
4513 //
4514 SPIRVOperandList Ops;
4515
David Neto257c3892018-04-11 13:19:45 -04004516 Ops << MkId(lookupType(I.getType()))
4517 << MkId(VMap[AtomicRMW->getPointerOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004518
4519 auto IntTy = Type::getInt32Ty(I.getContext());
Neil Henning39672102017-09-29 14:33:13 +01004520 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
David Neto257c3892018-04-11 13:19:45 -04004521 Ops << MkId(VMap[ConstantScopeDevice]);
Neil Henning39672102017-09-29 14:33:13 +01004522
4523 const auto ConstantMemorySemantics = ConstantInt::get(
4524 IntTy, spv::MemorySemanticsUniformMemoryMask |
4525 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto257c3892018-04-11 13:19:45 -04004526 Ops << MkId(VMap[ConstantMemorySemantics]);
Neil Henning39672102017-09-29 14:33:13 +01004527
David Neto257c3892018-04-11 13:19:45 -04004528 Ops << MkId(VMap[AtomicRMW->getValOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004529
4530 VMap[&I] = nextID;
4531
David Neto87846742018-04-11 17:36:22 -04004532 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
Neil Henning39672102017-09-29 14:33:13 +01004533 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004534 break;
4535 }
4536 case Instruction::Fence: {
4537 I.print(errs());
4538 llvm_unreachable("Unsupported instruction???");
4539 break;
4540 }
4541 case Instruction::Call: {
4542 CallInst *Call = dyn_cast<CallInst>(&I);
4543 Function *Callee = Call->getCalledFunction();
4544
Alan Baker202c8c72018-08-13 13:47:44 -04004545 if (Callee->getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004546 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
4547 // Generate an OpLoad
4548 SPIRVOperandList Ops;
4549 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004550
David Neto862b7d82018-06-14 18:48:37 -04004551 Ops << MkId(lookupType(Call->getType()->getPointerElementType()))
4552 << MkId(ResourceVarDeferredLoadCalls[Call]);
4553
4554 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
4555 SPIRVInstList.push_back(Inst);
4556 VMap[Call] = load_id;
4557 break;
4558
4559 } else {
4560 // This maps to an OpVariable we've already generated.
4561 // No code is generated for the call.
4562 }
4563 break;
alan-bakerb6b09dc2018-11-08 16:59:28 -05004564 } else if (Callee->getName().startswith(
4565 clspv::WorkgroupAccessorFunction())) {
Alan Baker202c8c72018-08-13 13:47:44 -04004566 // Don't codegen an instruction here, but instead map this call directly
4567 // to the workgroup variable id.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004568 int spec_id = static_cast<int>(
4569 cast<ConstantInt>(Call->getOperand(0))->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04004570 const auto &info = LocalSpecIdInfoMap[spec_id];
4571 VMap[Call] = info.variable_id;
4572 break;
David Neto862b7d82018-06-14 18:48:37 -04004573 }
4574
4575 // Sampler initializers become a load of the corresponding sampler.
4576
Kévin Petitdf71de32019-04-09 14:09:50 +01004577 if (Callee->getName().equals(clspv::LiteralSamplerFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004578 // Map this to a load from the variable.
alan-baker09cb9802019-12-10 13:16:27 -05004579 const auto third_param = static_cast<unsigned>(
4580 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue());
4581 auto sampler_value = third_param;
4582 if (clspv::Option::UseSamplerMap()) {
4583 sampler_value = getSamplerMap()[third_param].first;
4584 }
David Neto862b7d82018-06-14 18:48:37 -04004585
4586 // Generate an OpLoad
David Neto22f144c2017-06-12 14:26:21 -04004587 SPIRVOperandList Ops;
David Neto862b7d82018-06-14 18:48:37 -04004588 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004589
David Neto257c3892018-04-11 13:19:45 -04004590 Ops << MkId(lookupType(SamplerTy->getPointerElementType()))
alan-baker09cb9802019-12-10 13:16:27 -05004591 << MkId(SamplerLiteralToIDMap[sampler_value]);
David Neto22f144c2017-06-12 14:26:21 -04004592
David Neto862b7d82018-06-14 18:48:37 -04004593 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004594 SPIRVInstList.push_back(Inst);
David Neto862b7d82018-06-14 18:48:37 -04004595 VMap[Call] = load_id;
David Neto22f144c2017-06-12 14:26:21 -04004596 break;
4597 }
4598
Kévin Petit349c9502019-03-28 17:24:14 +00004599 // Handle SPIR-V intrinsics
Kévin Petit9b340262019-06-19 18:31:11 +01004600 spv::Op opcode = StringSwitch<spv::Op>(Callee->getName())
4601 .Case("spirv.atomic_xor", spv::OpAtomicXor)
4602 .Default(spv::OpNop);
David Neto22f144c2017-06-12 14:26:21 -04004603
Kévin Petit617a76d2019-04-04 13:54:16 +01004604 // If the switch above didn't have an entry maybe the intrinsic
4605 // is using the name mangling logic.
4606 bool usesMangler = false;
4607 if (opcode == spv::OpNop) {
4608 if (Callee->getName().startswith(clspv::SPIRVOpIntrinsicFunction())) {
4609 auto OpCst = cast<ConstantInt>(Call->getOperand(0));
4610 opcode = static_cast<spv::Op>(OpCst->getZExtValue());
4611 usesMangler = true;
4612 }
4613 }
4614
Kévin Petit349c9502019-03-28 17:24:14 +00004615 if (opcode != spv::OpNop) {
4616
David Neto22f144c2017-06-12 14:26:21 -04004617 SPIRVOperandList Ops;
4618
Kévin Petit349c9502019-03-28 17:24:14 +00004619 if (!I.getType()->isVoidTy()) {
4620 Ops << MkId(lookupType(I.getType()));
4621 }
David Neto22f144c2017-06-12 14:26:21 -04004622
Kévin Petit617a76d2019-04-04 13:54:16 +01004623 unsigned firstOperand = usesMangler ? 1 : 0;
4624 for (unsigned i = firstOperand; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004625 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004626 }
4627
Kévin Petit349c9502019-03-28 17:24:14 +00004628 if (!I.getType()->isVoidTy()) {
4629 VMap[&I] = nextID;
Kévin Petit8a560882019-03-21 15:24:34 +00004630 }
4631
Kévin Petit349c9502019-03-28 17:24:14 +00004632 SPIRVInstruction *Inst;
4633 if (!I.getType()->isVoidTy()) {
4634 Inst = new SPIRVInstruction(opcode, nextID++, Ops);
4635 } else {
4636 Inst = new SPIRVInstruction(opcode, Ops);
4637 }
Kévin Petit8a560882019-03-21 15:24:34 +00004638 SPIRVInstList.push_back(Inst);
4639 break;
4640 }
4641
David Neto22f144c2017-06-12 14:26:21 -04004642 // spirv.copy_memory.* intrinsics become OpMemoryMemory's.
4643 if (Callee->getName().startswith("spirv.copy_memory")) {
4644 //
4645 // Generate OpCopyMemory.
4646 //
4647
4648 // Ops[0] = Dst ID
4649 // Ops[1] = Src ID
4650 // Ops[2] = Memory Access
4651 // Ops[3] = Alignment
4652
4653 auto IsVolatile =
4654 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
4655
4656 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
4657 : spv::MemoryAccessMaskNone;
4658
4659 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
4660
4661 auto Alignment =
4662 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4663
David Neto257c3892018-04-11 13:19:45 -04004664 SPIRVOperandList Ops;
4665 Ops << MkId(VMap[Call->getArgOperand(0)])
4666 << MkId(VMap[Call->getArgOperand(1)]) << MkNum(MemoryAccess)
4667 << MkNum(static_cast<uint32_t>(Alignment));
David Neto22f144c2017-06-12 14:26:21 -04004668
David Neto87846742018-04-11 17:36:22 -04004669 auto *Inst = new SPIRVInstruction(spv::OpCopyMemory, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004670
4671 SPIRVInstList.push_back(Inst);
4672
4673 break;
4674 }
4675
David Neto22f144c2017-06-12 14:26:21 -04004676 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
4677 // Additionally, OpTypeSampledImage is generated.
alan-bakerf67468c2019-11-25 15:51:49 -05004678 if (clspv::IsSampledImageRead(Callee)) {
David Neto22f144c2017-06-12 14:26:21 -04004679 //
4680 // Generate OpSampledImage.
4681 //
4682 // Ops[0] = Result Type ID
4683 // Ops[1] = Image ID
4684 // Ops[2] = Sampler ID
4685 //
4686 SPIRVOperandList Ops;
4687
4688 Value *Image = Call->getArgOperand(0);
4689 Value *Sampler = Call->getArgOperand(1);
4690 Value *Coordinate = Call->getArgOperand(2);
4691
4692 TypeMapType &OpImageTypeMap = getImageTypeMap();
4693 Type *ImageTy = Image->getType()->getPointerElementType();
4694 uint32_t ImageTyID = OpImageTypeMap[ImageTy];
David Neto22f144c2017-06-12 14:26:21 -04004695 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004696 uint32_t SamplerID = VMap[Sampler];
David Neto257c3892018-04-11 13:19:45 -04004697
4698 Ops << MkId(ImageTyID) << MkId(ImageID) << MkId(SamplerID);
David Neto22f144c2017-06-12 14:26:21 -04004699
4700 uint32_t SampledImageID = nextID;
4701
David Neto87846742018-04-11 17:36:22 -04004702 auto *Inst = new SPIRVInstruction(spv::OpSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004703 SPIRVInstList.push_back(Inst);
4704
4705 //
4706 // Generate OpImageSampleExplicitLod.
4707 //
4708 // Ops[0] = Result Type ID
4709 // Ops[1] = Sampled Image ID
4710 // Ops[2] = Coordinate ID
4711 // Ops[3] = Image Operands Type ID
4712 // Ops[4] ... Ops[n] = Operands ID
4713 //
4714 Ops.clear();
4715
alan-bakerf67468c2019-11-25 15:51:49 -05004716 const bool is_int_image = IsIntImageType(Image->getType());
4717 uint32_t result_type = 0;
4718 if (is_int_image) {
4719 result_type = v4int32ID;
4720 } else {
4721 result_type = lookupType(Call->getType());
4722 }
4723
4724 Ops << MkId(result_type) << MkId(SampledImageID) << MkId(VMap[Coordinate])
4725 << MkNum(spv::ImageOperandsLodMask);
David Neto22f144c2017-06-12 14:26:21 -04004726
4727 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
David Neto257c3892018-04-11 13:19:45 -04004728 Ops << MkId(VMap[CstFP0]);
David Neto22f144c2017-06-12 14:26:21 -04004729
alan-bakerf67468c2019-11-25 15:51:49 -05004730 uint32_t final_id = nextID++;
4731 VMap[&I] = final_id;
David Neto22f144c2017-06-12 14:26:21 -04004732
alan-bakerf67468c2019-11-25 15:51:49 -05004733 uint32_t image_id = final_id;
4734 if (is_int_image) {
4735 // Int image requires a bitcast from v4int to v4uint.
4736 image_id = nextID++;
4737 }
4738
4739 Inst = new SPIRVInstruction(spv::OpImageSampleExplicitLod, image_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004740 SPIRVInstList.push_back(Inst);
alan-bakerf67468c2019-11-25 15:51:49 -05004741
4742 if (is_int_image) {
4743 // Generate the bitcast.
4744 Ops.clear();
4745 Ops << MkId(lookupType(Call->getType())) << MkId(image_id);
4746 Inst = new SPIRVInstruction(spv::OpBitcast, final_id, Ops);
4747 SPIRVInstList.push_back(Inst);
4748 }
David Neto22f144c2017-06-12 14:26:21 -04004749 break;
4750 }
4751
alan-bakerf67468c2019-11-25 15:51:49 -05004752 // write_image is mapped to OpImageWrite.
4753 if (clspv::IsImageWrite(Callee)) {
David Neto22f144c2017-06-12 14:26:21 -04004754 //
4755 // Generate OpImageWrite.
4756 //
4757 // Ops[0] = Image ID
4758 // Ops[1] = Coordinate ID
4759 // Ops[2] = Texel ID
4760 // Ops[3] = (Optional) Image Operands Type (Literal Number)
4761 // Ops[4] ... Ops[n] = (Optional) Operands ID
4762 //
4763 SPIRVOperandList Ops;
4764
4765 Value *Image = Call->getArgOperand(0);
4766 Value *Coordinate = Call->getArgOperand(1);
4767 Value *Texel = Call->getArgOperand(2);
4768
4769 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004770 uint32_t CoordinateID = VMap[Coordinate];
David Neto22f144c2017-06-12 14:26:21 -04004771 uint32_t TexelID = VMap[Texel];
alan-bakerf67468c2019-11-25 15:51:49 -05004772
4773 const bool is_int_image = IsIntImageType(Image->getType());
4774 if (is_int_image) {
4775 // Generate a bitcast to v4int and use it as the texel value.
4776 uint32_t castID = nextID++;
4777 Ops << MkId(v4int32ID) << MkId(TexelID);
4778 auto cast = new SPIRVInstruction(spv::OpBitcast, castID, Ops);
4779 SPIRVInstList.push_back(cast);
4780 Ops.clear();
4781 TexelID = castID;
4782 }
David Neto257c3892018-04-11 13:19:45 -04004783 Ops << MkId(ImageID) << MkId(CoordinateID) << MkId(TexelID);
David Neto22f144c2017-06-12 14:26:21 -04004784
David Neto87846742018-04-11 17:36:22 -04004785 auto *Inst = new SPIRVInstruction(spv::OpImageWrite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004786 SPIRVInstList.push_back(Inst);
4787 break;
4788 }
4789
alan-bakerce179f12019-12-06 19:02:22 -05004790 // get_image_* is mapped to OpImageQuerySize or OpImageQuerySizeLod
4791 if (clspv::IsImageQuery(Callee)) {
David Neto5c22a252018-03-15 16:07:41 -04004792 //
alan-bakerce179f12019-12-06 19:02:22 -05004793 // Generate OpImageQuerySize[Lod]
David Neto5c22a252018-03-15 16:07:41 -04004794 //
4795 // Ops[0] = Image ID
4796 //
alan-bakerce179f12019-12-06 19:02:22 -05004797 // Result type has components equal to the dimensionality of the image,
4798 // plus 1 if the image is arrayed.
4799 //
alan-bakerf906d2b2019-12-10 11:26:23 -05004800 // %sizes = OpImageQuerySize[Lod] %uint[2|3|4] %im [%uint_0]
David Neto5c22a252018-03-15 16:07:41 -04004801 SPIRVOperandList Ops;
4802
4803 // Implement:
alan-bakerce179f12019-12-06 19:02:22 -05004804 // %sizes = OpImageQuerySize[Lod] %uint[2|3|4] %im [%uint_0]
4805 uint32_t SizesTypeID = 0;
4806
David Neto5c22a252018-03-15 16:07:41 -04004807 Value *Image = Call->getArgOperand(0);
alan-bakerce179f12019-12-06 19:02:22 -05004808 const uint32_t dim = ImageDimensionality(Image->getType());
alan-bakerf906d2b2019-12-10 11:26:23 -05004809 // TODO(alan-baker): fix component calculation when arrayed images are
4810 // supported.
alan-bakerce179f12019-12-06 19:02:22 -05004811 const uint32_t components = dim;
4812 if (components == 1) {
alan-bakerce179f12019-12-06 19:02:22 -05004813 SizesTypeID = TypeMap[Type::getInt32Ty(Context)];
4814 } else {
4815 SizesTypeID = TypeMap[VectorType::get(Type::getInt32Ty(Context), dim)];
4816 }
David Neto5c22a252018-03-15 16:07:41 -04004817 uint32_t ImageID = VMap[Image];
David Neto257c3892018-04-11 13:19:45 -04004818 Ops << MkId(SizesTypeID) << MkId(ImageID);
alan-bakerce179f12019-12-06 19:02:22 -05004819 spv::Op query_opcode = spv::OpImageQuerySize;
4820 if (clspv::IsSampledImageType(Image->getType())) {
4821 query_opcode = spv::OpImageQuerySizeLod;
4822 // Need explicit 0 for Lod operand.
4823 Constant *CstInt0 = ConstantInt::get(Context, APInt(32, 0));
4824 Ops << MkId(VMap[CstInt0]);
4825 }
David Neto5c22a252018-03-15 16:07:41 -04004826
4827 uint32_t SizesID = nextID++;
alan-bakerce179f12019-12-06 19:02:22 -05004828 auto *QueryInst = new SPIRVInstruction(query_opcode, SizesID, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004829 SPIRVInstList.push_back(QueryInst);
4830
alan-bakerce179f12019-12-06 19:02:22 -05004831 // May require an extra instruction to create the appropriate result of
4832 // the builtin function.
4833 if (clspv::IsGetImageDim(Callee)) {
4834 if (dim == 3) {
4835 // get_image_dim returns an int4 for 3D images.
4836 //
4837 // Reset value map entry since we generated an intermediate
4838 // instruction.
4839 VMap[&I] = nextID;
David Neto5c22a252018-03-15 16:07:41 -04004840
alan-bakerce179f12019-12-06 19:02:22 -05004841 // Implement:
4842 // %result = OpCompositeConstruct %uint4 %sizes %uint_0
4843 Ops.clear();
4844 Ops << MkId(lookupType(VectorType::get(Type::getInt32Ty(Context), 4)))
4845 << MkId(SizesID);
David Neto5c22a252018-03-15 16:07:41 -04004846
alan-bakerce179f12019-12-06 19:02:22 -05004847 Constant *CstInt0 = ConstantInt::get(Context, APInt(32, 0));
4848 Ops << MkId(VMap[CstInt0]);
David Neto5c22a252018-03-15 16:07:41 -04004849
alan-bakerce179f12019-12-06 19:02:22 -05004850 auto *Inst =
4851 new SPIRVInstruction(spv::OpCompositeConstruct, nextID++, Ops);
4852 SPIRVInstList.push_back(Inst);
4853 } else if (dim != components) {
4854 // get_image_dim return an int2 regardless of the arrayedness of the
4855 // image. If the image is arrayed an element must be dropped from the
4856 // query result.
4857 //
4858 // Reset value map entry since we generated an intermediate
4859 // instruction.
4860 VMap[&I] = nextID;
4861
4862 // Implement:
4863 // %result = OpVectorShuffle %uint2 %sizes %sizes 0 1
4864 Ops.clear();
4865 Ops << MkId(lookupType(VectorType::get(Type::getInt32Ty(Context), 2)))
4866 << MkId(SizesID) << MkId(SizesID) << MkNum(0) << MkNum(1);
4867
4868 auto *Inst =
4869 new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
4870 SPIRVInstList.push_back(Inst);
4871 }
4872 } else if (components > 1) {
4873 // Reset value map entry since we generated an intermediate instruction.
4874 VMap[&I] = nextID;
4875
4876 // Implement:
4877 // %result = OpCompositeExtract %uint %sizes <component number>
4878 Ops.clear();
4879 Ops << MkId(TypeMap[I.getType()]) << MkId(SizesID);
4880
4881 uint32_t component = 0;
4882 if (IsGetImageHeight(Callee))
4883 component = 1;
4884 else if (IsGetImageDepth(Callee))
4885 component = 2;
4886 Ops << MkNum(component);
4887
4888 auto *Inst =
4889 new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
4890 SPIRVInstList.push_back(Inst);
4891 }
David Neto5c22a252018-03-15 16:07:41 -04004892 break;
4893 }
4894
David Neto22f144c2017-06-12 14:26:21 -04004895 // Call instrucion is deferred because it needs function's ID. Record
4896 // slot's location on SPIRVInstructionList.
4897 DeferredInsts.push_back(
4898 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4899
David Neto3fbb4072017-10-16 11:28:14 -04004900 // Check whether the implementation of this call uses an extended
4901 // instruction plus one more value-producing instruction. If so, then
4902 // reserve the id for the extra value-producing slot.
4903 glsl::ExtInst EInst = getIndirectExtInstEnum(Callee->getName());
4904 if (EInst != kGlslExtInstBad) {
4905 // Reserve a spot for the extra value.
David Neto4d02a532017-09-17 12:57:44 -04004906 // Increase nextID.
David Neto22f144c2017-06-12 14:26:21 -04004907 VMap[&I] = nextID;
4908 nextID++;
4909 }
4910 break;
4911 }
4912 case Instruction::Ret: {
4913 unsigned NumOps = I.getNumOperands();
4914 if (NumOps == 0) {
4915 //
4916 // Generate OpReturn.
4917 //
David Netoef5ba2b2019-12-20 08:35:54 -05004918 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpReturn));
David Neto22f144c2017-06-12 14:26:21 -04004919 } else {
4920 //
4921 // Generate OpReturnValue.
4922 //
4923
4924 // Ops[0] = Return Value ID
4925 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004926
4927 Ops << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004928
David Neto87846742018-04-11 17:36:22 -04004929 auto *Inst = new SPIRVInstruction(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004930 SPIRVInstList.push_back(Inst);
4931 break;
4932 }
4933 break;
4934 }
4935 }
4936}
4937
4938void SPIRVProducerPass::GenerateFuncEpilogue() {
4939 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4940
4941 //
4942 // Generate OpFunctionEnd
4943 //
4944
David Netoef5ba2b2019-12-20 08:35:54 -05004945 auto *Inst = new SPIRVInstruction(spv::OpFunctionEnd);
David Neto22f144c2017-06-12 14:26:21 -04004946 SPIRVInstList.push_back(Inst);
4947}
4948
4949bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
alan-bakerb39c8262019-03-08 14:03:37 -05004950 // Don't specialize <4 x i8> if i8 is generally supported.
4951 if (clspv::Option::Int8Support())
4952 return false;
4953
David Neto22f144c2017-06-12 14:26:21 -04004954 LLVMContext &Context = Ty->getContext();
4955 if (Ty->isVectorTy()) {
4956 if (Ty->getVectorElementType() == Type::getInt8Ty(Context) &&
4957 Ty->getVectorNumElements() == 4) {
4958 return true;
4959 }
4960 }
4961
4962 return false;
4963}
4964
4965void SPIRVProducerPass::HandleDeferredInstruction() {
4966 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4967 ValueMapType &VMap = getValueMap();
4968 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4969
4970 for (auto DeferredInst = DeferredInsts.rbegin();
4971 DeferredInst != DeferredInsts.rend(); ++DeferredInst) {
4972 Value *Inst = std::get<0>(*DeferredInst);
4973 SPIRVInstructionList::iterator InsertPoint = ++std::get<1>(*DeferredInst);
4974 if (InsertPoint != SPIRVInstList.end()) {
4975 while ((*InsertPoint)->getOpcode() == spv::OpPhi) {
4976 ++InsertPoint;
4977 }
4978 }
4979
4980 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
alan-baker06cad652019-12-03 17:56:47 -05004981 // Check whether this branch needs to be preceeded by merge instruction.
David Neto22f144c2017-06-12 14:26:21 -04004982 BasicBlock *BrBB = Br->getParent();
alan-baker06cad652019-12-03 17:56:47 -05004983 if (ContinueBlocks.count(BrBB)) {
David Neto22f144c2017-06-12 14:26:21 -04004984 //
4985 // Generate OpLoopMerge.
4986 //
4987 // Ops[0] = Merge Block ID
4988 // Ops[1] = Continue Target ID
4989 // Ops[2] = Selection Control
4990 SPIRVOperandList Ops;
4991
alan-baker06cad652019-12-03 17:56:47 -05004992 auto MergeBB = MergeBlocks[BrBB];
4993 auto ContinueBB = ContinueBlocks[BrBB];
David Neto22f144c2017-06-12 14:26:21 -04004994 uint32_t MergeBBID = VMap[MergeBB];
David Neto22f144c2017-06-12 14:26:21 -04004995 uint32_t ContinueBBID = VMap[ContinueBB];
David Neto257c3892018-04-11 13:19:45 -04004996 Ops << MkId(MergeBBID) << MkId(ContinueBBID)
alan-baker06cad652019-12-03 17:56:47 -05004997 << MkNum(spv::LoopControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004998
David Neto87846742018-04-11 17:36:22 -04004999 auto *MergeInst = new SPIRVInstruction(spv::OpLoopMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005000 SPIRVInstList.insert(InsertPoint, MergeInst);
alan-baker06cad652019-12-03 17:56:47 -05005001 } else if (MergeBlocks.count(BrBB)) {
5002 //
5003 // Generate OpSelectionMerge.
5004 //
5005 // Ops[0] = Merge Block ID
5006 // Ops[1] = Selection Control
5007 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04005008
alan-baker06cad652019-12-03 17:56:47 -05005009 auto MergeBB = MergeBlocks[BrBB];
5010 uint32_t MergeBBID = VMap[MergeBB];
5011 Ops << MkId(MergeBBID) << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04005012
alan-baker06cad652019-12-03 17:56:47 -05005013 auto *MergeInst = new SPIRVInstruction(spv::OpSelectionMerge, Ops);
5014 SPIRVInstList.insert(InsertPoint, MergeInst);
David Neto22f144c2017-06-12 14:26:21 -04005015 }
5016
5017 if (Br->isConditional()) {
5018 //
5019 // Generate OpBranchConditional.
5020 //
5021 // Ops[0] = Condition ID
5022 // Ops[1] = True Label ID
5023 // Ops[2] = False Label ID
5024 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
5025 SPIRVOperandList Ops;
5026
5027 uint32_t CondID = VMap[Br->getCondition()];
David Neto22f144c2017-06-12 14:26:21 -04005028 uint32_t TrueBBID = VMap[Br->getSuccessor(0)];
David Neto22f144c2017-06-12 14:26:21 -04005029 uint32_t FalseBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04005030
5031 Ops << MkId(CondID) << MkId(TrueBBID) << MkId(FalseBBID);
David Neto22f144c2017-06-12 14:26:21 -04005032
David Neto87846742018-04-11 17:36:22 -04005033 auto *BrInst = new SPIRVInstruction(spv::OpBranchConditional, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005034 SPIRVInstList.insert(InsertPoint, BrInst);
5035 } else {
5036 //
5037 // Generate OpBranch.
5038 //
5039 // Ops[0] = Target Label ID
5040 SPIRVOperandList Ops;
5041
5042 uint32_t TargetID = VMap[Br->getSuccessor(0)];
David Neto257c3892018-04-11 13:19:45 -04005043 Ops << MkId(TargetID);
David Neto22f144c2017-06-12 14:26:21 -04005044
David Neto87846742018-04-11 17:36:22 -04005045 SPIRVInstList.insert(InsertPoint,
5046 new SPIRVInstruction(spv::OpBranch, Ops));
David Neto22f144c2017-06-12 14:26:21 -04005047 }
5048 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
alan-baker5b86ed72019-02-15 08:26:50 -05005049 if (PHI->getType()->isPointerTy()) {
5050 // OpPhi on pointers requires variable pointers.
5051 setVariablePointersCapabilities(
5052 PHI->getType()->getPointerAddressSpace());
5053 if (!hasVariablePointers() && !selectFromSameObject(PHI)) {
5054 setVariablePointers(true);
5055 }
5056 }
5057
David Neto22f144c2017-06-12 14:26:21 -04005058 //
5059 // Generate OpPhi.
5060 //
5061 // Ops[0] = Result Type ID
5062 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
5063 SPIRVOperandList Ops;
5064
David Neto257c3892018-04-11 13:19:45 -04005065 Ops << MkId(lookupType(PHI->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005066
David Neto22f144c2017-06-12 14:26:21 -04005067 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
5068 uint32_t VarID = VMap[PHI->getIncomingValue(i)];
David Neto22f144c2017-06-12 14:26:21 -04005069 uint32_t ParentID = VMap[PHI->getIncomingBlock(i)];
David Neto257c3892018-04-11 13:19:45 -04005070 Ops << MkId(VarID) << MkId(ParentID);
David Neto22f144c2017-06-12 14:26:21 -04005071 }
5072
5073 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005074 InsertPoint,
5075 new SPIRVInstruction(spv::OpPhi, std::get<2>(*DeferredInst), Ops));
David Neto22f144c2017-06-12 14:26:21 -04005076 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
5077 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04005078 auto callee_name = Callee->getName();
5079 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04005080
5081 if (EInst) {
5082 uint32_t &ExtInstImportID = getOpExtInstImportID();
5083
5084 //
5085 // Generate OpExtInst.
5086 //
5087
5088 // Ops[0] = Result Type ID
5089 // Ops[1] = Set ID (OpExtInstImport ID)
5090 // Ops[2] = Instruction Number (Literal Number)
5091 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5092 SPIRVOperandList Ops;
5093
David Neto862b7d82018-06-14 18:48:37 -04005094 Ops << MkId(lookupType(Call->getType())) << MkId(ExtInstImportID)
5095 << MkNum(EInst);
David Neto22f144c2017-06-12 14:26:21 -04005096
David Neto22f144c2017-06-12 14:26:21 -04005097 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5098 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04005099 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04005100 }
5101
David Neto87846742018-04-11 17:36:22 -04005102 auto *ExtInst = new SPIRVInstruction(spv::OpExtInst,
5103 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005104 SPIRVInstList.insert(InsertPoint, ExtInst);
5105
David Neto3fbb4072017-10-16 11:28:14 -04005106 const auto IndirectExtInst = getIndirectExtInstEnum(callee_name);
5107 if (IndirectExtInst != kGlslExtInstBad) {
5108 // Generate one more instruction that uses the result of the extended
5109 // instruction. Its result id is one more than the id of the
5110 // extended instruction.
David Neto22f144c2017-06-12 14:26:21 -04005111 LLVMContext &Context =
5112 Call->getParent()->getParent()->getParent()->getContext();
David Neto22f144c2017-06-12 14:26:21 -04005113
David Neto3fbb4072017-10-16 11:28:14 -04005114 auto generate_extra_inst = [this, &Context, &Call, &DeferredInst,
5115 &VMap, &SPIRVInstList, &InsertPoint](
5116 spv::Op opcode, Constant *constant) {
5117 //
5118 // Generate instruction like:
5119 // result = opcode constant <extinst-result>
5120 //
5121 // Ops[0] = Result Type ID
5122 // Ops[1] = Operand 0 ;; the constant, suitably splatted
5123 // Ops[2] = Operand 1 ;; the result of the extended instruction
5124 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04005125
David Neto3fbb4072017-10-16 11:28:14 -04005126 Type *resultTy = Call->getType();
David Neto257c3892018-04-11 13:19:45 -04005127 Ops << MkId(lookupType(resultTy));
David Neto3fbb4072017-10-16 11:28:14 -04005128
5129 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
5130 constant = ConstantVector::getSplat(
5131 static_cast<unsigned>(vectorTy->getNumElements()), constant);
5132 }
David Neto257c3892018-04-11 13:19:45 -04005133 Ops << MkId(VMap[constant]) << MkId(std::get<2>(*DeferredInst));
David Neto3fbb4072017-10-16 11:28:14 -04005134
5135 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005136 InsertPoint, new SPIRVInstruction(
5137 opcode, std::get<2>(*DeferredInst) + 1, Ops));
David Neto3fbb4072017-10-16 11:28:14 -04005138 };
5139
5140 switch (IndirectExtInst) {
5141 case glsl::ExtInstFindUMsb: // Implementing clz
5142 generate_extra_inst(
5143 spv::OpISub, ConstantInt::get(Type::getInt32Ty(Context), 31));
5144 break;
5145 case glsl::ExtInstAcos: // Implementing acospi
5146 case glsl::ExtInstAsin: // Implementing asinpi
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005147 case glsl::ExtInstAtan: // Implementing atanpi
David Neto3fbb4072017-10-16 11:28:14 -04005148 case glsl::ExtInstAtan2: // Implementing atan2pi
5149 generate_extra_inst(
5150 spv::OpFMul,
5151 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
5152 break;
5153
5154 default:
5155 assert(false && "internally inconsistent");
David Neto4d02a532017-09-17 12:57:44 -04005156 }
David Neto22f144c2017-06-12 14:26:21 -04005157 }
David Neto3fbb4072017-10-16 11:28:14 -04005158
alan-bakerb39c8262019-03-08 14:03:37 -05005159 } else if (callee_name.startswith("_Z8popcount")) {
David Neto22f144c2017-06-12 14:26:21 -04005160 //
5161 // Generate OpBitCount
5162 //
5163 // Ops[0] = Result Type ID
5164 // Ops[1] = Base ID
David Neto257c3892018-04-11 13:19:45 -04005165 SPIRVOperandList Ops;
5166 Ops << MkId(lookupType(Call->getType()))
5167 << MkId(VMap[Call->getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04005168
5169 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005170 InsertPoint, new SPIRVInstruction(spv::OpBitCount,
David Neto22f144c2017-06-12 14:26:21 -04005171 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005172
David Neto862b7d82018-06-14 18:48:37 -04005173 } else if (callee_name.startswith(kCompositeConstructFunctionPrefix)) {
David Netoab03f432017-11-03 17:00:44 -04005174
5175 // Generate an OpCompositeConstruct
5176 SPIRVOperandList Ops;
5177
5178 // The result type.
David Neto257c3892018-04-11 13:19:45 -04005179 Ops << MkId(lookupType(Call->getType()));
David Netoab03f432017-11-03 17:00:44 -04005180
5181 for (Use &use : Call->arg_operands()) {
David Neto257c3892018-04-11 13:19:45 -04005182 Ops << MkId(VMap[use.get()]);
David Netoab03f432017-11-03 17:00:44 -04005183 }
5184
5185 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005186 InsertPoint, new SPIRVInstruction(spv::OpCompositeConstruct,
5187 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005188
Alan Baker202c8c72018-08-13 13:47:44 -04005189 } else if (callee_name.startswith(clspv::ResourceAccessorFunction())) {
5190
5191 // We have already mapped the call's result value to an ID.
5192 // Don't generate any code now.
5193
5194 } else if (callee_name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04005195
5196 // We have already mapped the call's result value to an ID.
5197 // Don't generate any code now.
5198
David Neto22f144c2017-06-12 14:26:21 -04005199 } else {
alan-baker5b86ed72019-02-15 08:26:50 -05005200 if (Call->getType()->isPointerTy()) {
5201 // Functions returning pointers require variable pointers.
5202 setVariablePointersCapabilities(
5203 Call->getType()->getPointerAddressSpace());
5204 }
5205
David Neto22f144c2017-06-12 14:26:21 -04005206 //
5207 // Generate OpFunctionCall.
5208 //
5209
5210 // Ops[0] = Result Type ID
5211 // Ops[1] = Callee Function ID
5212 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
5213 SPIRVOperandList Ops;
5214
David Neto862b7d82018-06-14 18:48:37 -04005215 Ops << MkId(lookupType(Call->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005216
5217 uint32_t CalleeID = VMap[Callee];
David Neto43568eb2017-10-13 18:25:25 -04005218 if (CalleeID == 0) {
5219 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04005220 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04005221 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
5222 // causes an infinite loop. Instead, go ahead and generate
5223 // the bad function call. A validator will catch the 0-Id.
5224 // llvm_unreachable("Can't translate function call");
5225 }
David Neto22f144c2017-06-12 14:26:21 -04005226
David Neto257c3892018-04-11 13:19:45 -04005227 Ops << MkId(CalleeID);
David Neto22f144c2017-06-12 14:26:21 -04005228
David Neto22f144c2017-06-12 14:26:21 -04005229 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5230 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
alan-baker5b86ed72019-02-15 08:26:50 -05005231 auto *operand = Call->getOperand(i);
alan-bakerd4d50652019-12-03 17:17:15 -05005232 auto *operand_type = operand->getType();
5233 // Images and samplers can be passed as function parameters without
5234 // variable pointers.
5235 if (operand_type->isPointerTy() && !IsImageType(operand_type) &&
5236 !IsSamplerType(operand_type)) {
alan-baker5b86ed72019-02-15 08:26:50 -05005237 auto sc =
5238 GetStorageClass(operand->getType()->getPointerAddressSpace());
5239 if (sc == spv::StorageClassStorageBuffer) {
5240 // Passing SSBO by reference requires variable pointers storage
5241 // buffer.
5242 setVariablePointersStorageBuffer(true);
5243 } else if (sc == spv::StorageClassWorkgroup) {
5244 // Workgroup references require variable pointers if they are not
5245 // memory object declarations.
5246 if (auto *operand_call = dyn_cast<CallInst>(operand)) {
5247 // Workgroup accessor represents a variable reference.
5248 if (!operand_call->getCalledFunction()->getName().startswith(
5249 clspv::WorkgroupAccessorFunction()))
5250 setVariablePointers(true);
5251 } else {
5252 // Arguments are function parameters.
5253 if (!isa<Argument>(operand))
5254 setVariablePointers(true);
5255 }
5256 }
5257 }
5258 Ops << MkId(VMap[operand]);
David Neto22f144c2017-06-12 14:26:21 -04005259 }
5260
David Neto87846742018-04-11 17:36:22 -04005261 auto *CallInst = new SPIRVInstruction(spv::OpFunctionCall,
5262 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005263 SPIRVInstList.insert(InsertPoint, CallInst);
5264 }
5265 }
5266 }
5267}
5268
David Neto1a1a0582017-07-07 12:01:44 -04005269void SPIRVProducerPass::HandleDeferredDecorations(const DataLayout &DL) {
Alan Baker202c8c72018-08-13 13:47:44 -04005270 if (getTypesNeedingArrayStride().empty() && LocalArgSpecIds.empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04005271 return;
David Netoc6f3ab22018-04-06 18:02:31 -04005272 }
David Neto1a1a0582017-07-07 12:01:44 -04005273
5274 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto1a1a0582017-07-07 12:01:44 -04005275
5276 // Find an iterator pointing just past the last decoration.
5277 bool seen_decorations = false;
5278 auto DecoInsertPoint =
5279 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
5280 [&seen_decorations](SPIRVInstruction *Inst) -> bool {
5281 const bool is_decoration =
5282 Inst->getOpcode() == spv::OpDecorate ||
5283 Inst->getOpcode() == spv::OpMemberDecorate;
5284 if (is_decoration) {
5285 seen_decorations = true;
5286 return false;
5287 } else {
5288 return seen_decorations;
5289 }
5290 });
5291
David Netoc6f3ab22018-04-06 18:02:31 -04005292 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
5293 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07005294 for (auto *type : getTypesNeedingArrayStride()) {
5295 Type *elemTy = nullptr;
5296 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
5297 elemTy = ptrTy->getElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005298 } else if (auto *arrayTy = dyn_cast<ArrayType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005299 elemTy = arrayTy->getArrayElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005300 } else if (auto *seqTy = dyn_cast<SequentialType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005301 elemTy = seqTy->getSequentialElementType();
5302 } else {
5303 errs() << "Unhandled strided type " << *type << "\n";
5304 llvm_unreachable("Unhandled strided type");
5305 }
David Neto1a1a0582017-07-07 12:01:44 -04005306
5307 // Ops[0] = Target ID
5308 // Ops[1] = Decoration (ArrayStride)
5309 // Ops[2] = Stride number (Literal Number)
5310 SPIRVOperandList Ops;
5311
David Neto85082642018-03-24 06:55:20 -07005312 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Alan Bakerfcda9482018-10-02 17:09:59 -04005313 const uint32_t stride = static_cast<uint32_t>(GetTypeAllocSize(elemTy, DL));
David Neto257c3892018-04-11 13:19:45 -04005314
5315 Ops << MkId(lookupType(type)) << MkNum(spv::DecorationArrayStride)
5316 << MkNum(stride);
David Neto1a1a0582017-07-07 12:01:44 -04005317
David Neto87846742018-04-11 17:36:22 -04005318 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto1a1a0582017-07-07 12:01:44 -04005319 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
5320 }
David Netoc6f3ab22018-04-06 18:02:31 -04005321
5322 // Emit SpecId decorations targeting the array size value.
Alan Baker202c8c72018-08-13 13:47:44 -04005323 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
5324 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005325 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04005326 SPIRVOperandList Ops;
5327 Ops << MkId(arg_info.array_size_id) << MkNum(spv::DecorationSpecId)
5328 << MkNum(arg_info.spec_id);
5329 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04005330 new SPIRVInstruction(spv::OpDecorate, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04005331 }
David Neto1a1a0582017-07-07 12:01:44 -04005332}
5333
David Neto22f144c2017-06-12 14:26:21 -04005334glsl::ExtInst SPIRVProducerPass::getExtInstEnum(StringRef Name) {
5335 return StringSwitch<glsl::ExtInst>(Name)
alan-bakerb39c8262019-03-08 14:03:37 -05005336 .Case("_Z3absc", glsl::ExtInst::ExtInstSAbs)
5337 .Case("_Z3absDv2_c", glsl::ExtInst::ExtInstSAbs)
5338 .Case("_Z3absDv3_c", glsl::ExtInst::ExtInstSAbs)
5339 .Case("_Z3absDv4_c", glsl::ExtInst::ExtInstSAbs)
Kévin Petit2444e9b2018-11-09 14:14:37 +00005340 .Case("_Z3abss", glsl::ExtInst::ExtInstSAbs)
5341 .Case("_Z3absDv2_s", glsl::ExtInst::ExtInstSAbs)
5342 .Case("_Z3absDv3_s", glsl::ExtInst::ExtInstSAbs)
5343 .Case("_Z3absDv4_s", glsl::ExtInst::ExtInstSAbs)
David Neto22f144c2017-06-12 14:26:21 -04005344 .Case("_Z3absi", glsl::ExtInst::ExtInstSAbs)
5345 .Case("_Z3absDv2_i", glsl::ExtInst::ExtInstSAbs)
5346 .Case("_Z3absDv3_i", glsl::ExtInst::ExtInstSAbs)
5347 .Case("_Z3absDv4_i", glsl::ExtInst::ExtInstSAbs)
Kévin Petit2444e9b2018-11-09 14:14:37 +00005348 .Case("_Z3absl", glsl::ExtInst::ExtInstSAbs)
5349 .Case("_Z3absDv2_l", glsl::ExtInst::ExtInstSAbs)
5350 .Case("_Z3absDv3_l", glsl::ExtInst::ExtInstSAbs)
5351 .Case("_Z3absDv4_l", glsl::ExtInst::ExtInstSAbs)
alan-bakerb39c8262019-03-08 14:03:37 -05005352 .Case("_Z5clampccc", glsl::ExtInst::ExtInstSClamp)
5353 .Case("_Z5clampDv2_cS_S_", glsl::ExtInst::ExtInstSClamp)
5354 .Case("_Z5clampDv3_cS_S_", glsl::ExtInst::ExtInstSClamp)
5355 .Case("_Z5clampDv4_cS_S_", glsl::ExtInst::ExtInstSClamp)
5356 .Case("_Z5clamphhh", glsl::ExtInst::ExtInstUClamp)
5357 .Case("_Z5clampDv2_hS_S_", glsl::ExtInst::ExtInstUClamp)
5358 .Case("_Z5clampDv3_hS_S_", glsl::ExtInst::ExtInstUClamp)
5359 .Case("_Z5clampDv4_hS_S_", glsl::ExtInst::ExtInstUClamp)
Kévin Petit495255d2019-03-06 13:56:48 +00005360 .Case("_Z5clampsss", glsl::ExtInst::ExtInstSClamp)
5361 .Case("_Z5clampDv2_sS_S_", glsl::ExtInst::ExtInstSClamp)
5362 .Case("_Z5clampDv3_sS_S_", glsl::ExtInst::ExtInstSClamp)
5363 .Case("_Z5clampDv4_sS_S_", glsl::ExtInst::ExtInstSClamp)
5364 .Case("_Z5clampttt", glsl::ExtInst::ExtInstUClamp)
5365 .Case("_Z5clampDv2_tS_S_", glsl::ExtInst::ExtInstUClamp)
5366 .Case("_Z5clampDv3_tS_S_", glsl::ExtInst::ExtInstUClamp)
5367 .Case("_Z5clampDv4_tS_S_", glsl::ExtInst::ExtInstUClamp)
David Neto22f144c2017-06-12 14:26:21 -04005368 .Case("_Z5clampiii", glsl::ExtInst::ExtInstSClamp)
5369 .Case("_Z5clampDv2_iS_S_", glsl::ExtInst::ExtInstSClamp)
5370 .Case("_Z5clampDv3_iS_S_", glsl::ExtInst::ExtInstSClamp)
5371 .Case("_Z5clampDv4_iS_S_", glsl::ExtInst::ExtInstSClamp)
5372 .Case("_Z5clampjjj", glsl::ExtInst::ExtInstUClamp)
5373 .Case("_Z5clampDv2_jS_S_", glsl::ExtInst::ExtInstUClamp)
5374 .Case("_Z5clampDv3_jS_S_", glsl::ExtInst::ExtInstUClamp)
5375 .Case("_Z5clampDv4_jS_S_", glsl::ExtInst::ExtInstUClamp)
Kévin Petit495255d2019-03-06 13:56:48 +00005376 .Case("_Z5clamplll", glsl::ExtInst::ExtInstSClamp)
5377 .Case("_Z5clampDv2_lS_S_", glsl::ExtInst::ExtInstSClamp)
5378 .Case("_Z5clampDv3_lS_S_", glsl::ExtInst::ExtInstSClamp)
5379 .Case("_Z5clampDv4_lS_S_", glsl::ExtInst::ExtInstSClamp)
5380 .Case("_Z5clampmmm", glsl::ExtInst::ExtInstUClamp)
5381 .Case("_Z5clampDv2_mS_S_", glsl::ExtInst::ExtInstUClamp)
5382 .Case("_Z5clampDv3_mS_S_", glsl::ExtInst::ExtInstUClamp)
5383 .Case("_Z5clampDv4_mS_S_", glsl::ExtInst::ExtInstUClamp)
David Neto22f144c2017-06-12 14:26:21 -04005384 .Case("_Z5clampfff", glsl::ExtInst::ExtInstFClamp)
5385 .Case("_Z5clampDv2_fS_S_", glsl::ExtInst::ExtInstFClamp)
5386 .Case("_Z5clampDv3_fS_S_", glsl::ExtInst::ExtInstFClamp)
5387 .Case("_Z5clampDv4_fS_S_", glsl::ExtInst::ExtInstFClamp)
alan-bakerb39c8262019-03-08 14:03:37 -05005388 .Case("_Z3maxcc", glsl::ExtInst::ExtInstSMax)
5389 .Case("_Z3maxDv2_cS_", glsl::ExtInst::ExtInstSMax)
5390 .Case("_Z3maxDv3_cS_", glsl::ExtInst::ExtInstSMax)
5391 .Case("_Z3maxDv4_cS_", glsl::ExtInst::ExtInstSMax)
5392 .Case("_Z3maxhh", glsl::ExtInst::ExtInstUMax)
5393 .Case("_Z3maxDv2_hS_", glsl::ExtInst::ExtInstUMax)
5394 .Case("_Z3maxDv3_hS_", glsl::ExtInst::ExtInstUMax)
5395 .Case("_Z3maxDv4_hS_", glsl::ExtInst::ExtInstUMax)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005396 .Case("_Z3maxss", glsl::ExtInst::ExtInstSMax)
5397 .Case("_Z3maxDv2_sS_", glsl::ExtInst::ExtInstSMax)
5398 .Case("_Z3maxDv3_sS_", glsl::ExtInst::ExtInstSMax)
5399 .Case("_Z3maxDv4_sS_", glsl::ExtInst::ExtInstSMax)
5400 .Case("_Z3maxtt", glsl::ExtInst::ExtInstUMax)
5401 .Case("_Z3maxDv2_tS_", glsl::ExtInst::ExtInstUMax)
5402 .Case("_Z3maxDv3_tS_", glsl::ExtInst::ExtInstUMax)
5403 .Case("_Z3maxDv4_tS_", glsl::ExtInst::ExtInstUMax)
David Neto22f144c2017-06-12 14:26:21 -04005404 .Case("_Z3maxii", glsl::ExtInst::ExtInstSMax)
5405 .Case("_Z3maxDv2_iS_", glsl::ExtInst::ExtInstSMax)
5406 .Case("_Z3maxDv3_iS_", glsl::ExtInst::ExtInstSMax)
5407 .Case("_Z3maxDv4_iS_", glsl::ExtInst::ExtInstSMax)
5408 .Case("_Z3maxjj", glsl::ExtInst::ExtInstUMax)
5409 .Case("_Z3maxDv2_jS_", glsl::ExtInst::ExtInstUMax)
5410 .Case("_Z3maxDv3_jS_", glsl::ExtInst::ExtInstUMax)
5411 .Case("_Z3maxDv4_jS_", glsl::ExtInst::ExtInstUMax)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005412 .Case("_Z3maxll", glsl::ExtInst::ExtInstSMax)
5413 .Case("_Z3maxDv2_lS_", glsl::ExtInst::ExtInstSMax)
5414 .Case("_Z3maxDv3_lS_", glsl::ExtInst::ExtInstSMax)
5415 .Case("_Z3maxDv4_lS_", glsl::ExtInst::ExtInstSMax)
5416 .Case("_Z3maxmm", glsl::ExtInst::ExtInstUMax)
5417 .Case("_Z3maxDv2_mS_", glsl::ExtInst::ExtInstUMax)
5418 .Case("_Z3maxDv3_mS_", glsl::ExtInst::ExtInstUMax)
5419 .Case("_Z3maxDv4_mS_", glsl::ExtInst::ExtInstUMax)
David Neto22f144c2017-06-12 14:26:21 -04005420 .Case("_Z3maxff", glsl::ExtInst::ExtInstFMax)
5421 .Case("_Z3maxDv2_fS_", glsl::ExtInst::ExtInstFMax)
5422 .Case("_Z3maxDv3_fS_", glsl::ExtInst::ExtInstFMax)
5423 .Case("_Z3maxDv4_fS_", glsl::ExtInst::ExtInstFMax)
5424 .StartsWith("_Z4fmax", glsl::ExtInst::ExtInstFMax)
alan-bakerb39c8262019-03-08 14:03:37 -05005425 .Case("_Z3mincc", glsl::ExtInst::ExtInstSMin)
5426 .Case("_Z3minDv2_cS_", glsl::ExtInst::ExtInstSMin)
5427 .Case("_Z3minDv3_cS_", glsl::ExtInst::ExtInstSMin)
5428 .Case("_Z3minDv4_cS_", glsl::ExtInst::ExtInstSMin)
5429 .Case("_Z3minhh", glsl::ExtInst::ExtInstUMin)
5430 .Case("_Z3minDv2_hS_", glsl::ExtInst::ExtInstUMin)
5431 .Case("_Z3minDv3_hS_", glsl::ExtInst::ExtInstUMin)
5432 .Case("_Z3minDv4_hS_", glsl::ExtInst::ExtInstUMin)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005433 .Case("_Z3minss", glsl::ExtInst::ExtInstSMin)
5434 .Case("_Z3minDv2_sS_", glsl::ExtInst::ExtInstSMin)
5435 .Case("_Z3minDv3_sS_", glsl::ExtInst::ExtInstSMin)
5436 .Case("_Z3minDv4_sS_", glsl::ExtInst::ExtInstSMin)
5437 .Case("_Z3mintt", glsl::ExtInst::ExtInstUMin)
5438 .Case("_Z3minDv2_tS_", glsl::ExtInst::ExtInstUMin)
5439 .Case("_Z3minDv3_tS_", glsl::ExtInst::ExtInstUMin)
5440 .Case("_Z3minDv4_tS_", glsl::ExtInst::ExtInstUMin)
David Neto22f144c2017-06-12 14:26:21 -04005441 .Case("_Z3minii", glsl::ExtInst::ExtInstSMin)
5442 .Case("_Z3minDv2_iS_", glsl::ExtInst::ExtInstSMin)
5443 .Case("_Z3minDv3_iS_", glsl::ExtInst::ExtInstSMin)
5444 .Case("_Z3minDv4_iS_", glsl::ExtInst::ExtInstSMin)
5445 .Case("_Z3minjj", glsl::ExtInst::ExtInstUMin)
5446 .Case("_Z3minDv2_jS_", glsl::ExtInst::ExtInstUMin)
5447 .Case("_Z3minDv3_jS_", glsl::ExtInst::ExtInstUMin)
5448 .Case("_Z3minDv4_jS_", glsl::ExtInst::ExtInstUMin)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005449 .Case("_Z3minll", glsl::ExtInst::ExtInstSMin)
5450 .Case("_Z3minDv2_lS_", glsl::ExtInst::ExtInstSMin)
5451 .Case("_Z3minDv3_lS_", glsl::ExtInst::ExtInstSMin)
5452 .Case("_Z3minDv4_lS_", glsl::ExtInst::ExtInstSMin)
5453 .Case("_Z3minmm", glsl::ExtInst::ExtInstUMin)
5454 .Case("_Z3minDv2_mS_", glsl::ExtInst::ExtInstUMin)
5455 .Case("_Z3minDv3_mS_", glsl::ExtInst::ExtInstUMin)
5456 .Case("_Z3minDv4_mS_", glsl::ExtInst::ExtInstUMin)
David Neto22f144c2017-06-12 14:26:21 -04005457 .Case("_Z3minff", glsl::ExtInst::ExtInstFMin)
5458 .Case("_Z3minDv2_fS_", glsl::ExtInst::ExtInstFMin)
5459 .Case("_Z3minDv3_fS_", glsl::ExtInst::ExtInstFMin)
5460 .Case("_Z3minDv4_fS_", glsl::ExtInst::ExtInstFMin)
5461 .StartsWith("_Z4fmin", glsl::ExtInst::ExtInstFMin)
5462 .StartsWith("_Z7degrees", glsl::ExtInst::ExtInstDegrees)
5463 .StartsWith("_Z7radians", glsl::ExtInst::ExtInstRadians)
5464 .StartsWith("_Z3mix", glsl::ExtInst::ExtInstFMix)
5465 .StartsWith("_Z4acos", glsl::ExtInst::ExtInstAcos)
5466 .StartsWith("_Z5acosh", glsl::ExtInst::ExtInstAcosh)
5467 .StartsWith("_Z4asin", glsl::ExtInst::ExtInstAsin)
5468 .StartsWith("_Z5asinh", glsl::ExtInst::ExtInstAsinh)
5469 .StartsWith("_Z4atan", glsl::ExtInst::ExtInstAtan)
5470 .StartsWith("_Z5atan2", glsl::ExtInst::ExtInstAtan2)
5471 .StartsWith("_Z5atanh", glsl::ExtInst::ExtInstAtanh)
5472 .StartsWith("_Z4ceil", glsl::ExtInst::ExtInstCeil)
5473 .StartsWith("_Z3sin", glsl::ExtInst::ExtInstSin)
5474 .StartsWith("_Z4sinh", glsl::ExtInst::ExtInstSinh)
5475 .StartsWith("_Z8half_sin", glsl::ExtInst::ExtInstSin)
5476 .StartsWith("_Z10native_sin", glsl::ExtInst::ExtInstSin)
5477 .StartsWith("_Z3cos", glsl::ExtInst::ExtInstCos)
5478 .StartsWith("_Z4cosh", glsl::ExtInst::ExtInstCosh)
5479 .StartsWith("_Z8half_cos", glsl::ExtInst::ExtInstCos)
5480 .StartsWith("_Z10native_cos", glsl::ExtInst::ExtInstCos)
5481 .StartsWith("_Z3tan", glsl::ExtInst::ExtInstTan)
5482 .StartsWith("_Z4tanh", glsl::ExtInst::ExtInstTanh)
5483 .StartsWith("_Z8half_tan", glsl::ExtInst::ExtInstTan)
5484 .StartsWith("_Z10native_tan", glsl::ExtInst::ExtInstTan)
5485 .StartsWith("_Z3exp", glsl::ExtInst::ExtInstExp)
5486 .StartsWith("_Z8half_exp", glsl::ExtInst::ExtInstExp)
5487 .StartsWith("_Z10native_exp", glsl::ExtInst::ExtInstExp)
5488 .StartsWith("_Z4exp2", glsl::ExtInst::ExtInstExp2)
5489 .StartsWith("_Z9half_exp2", glsl::ExtInst::ExtInstExp2)
5490 .StartsWith("_Z11native_exp2", glsl::ExtInst::ExtInstExp2)
5491 .StartsWith("_Z3log", glsl::ExtInst::ExtInstLog)
5492 .StartsWith("_Z8half_log", glsl::ExtInst::ExtInstLog)
5493 .StartsWith("_Z10native_log", glsl::ExtInst::ExtInstLog)
5494 .StartsWith("_Z4log2", glsl::ExtInst::ExtInstLog2)
5495 .StartsWith("_Z9half_log2", glsl::ExtInst::ExtInstLog2)
5496 .StartsWith("_Z11native_log2", glsl::ExtInst::ExtInstLog2)
5497 .StartsWith("_Z4fabs", glsl::ExtInst::ExtInstFAbs)
kpet3458e942018-10-03 14:35:21 +01005498 .StartsWith("_Z3fma", glsl::ExtInst::ExtInstFma)
David Neto22f144c2017-06-12 14:26:21 -04005499 .StartsWith("_Z5floor", glsl::ExtInst::ExtInstFloor)
5500 .StartsWith("_Z5ldexp", glsl::ExtInst::ExtInstLdexp)
5501 .StartsWith("_Z3pow", glsl::ExtInst::ExtInstPow)
5502 .StartsWith("_Z4powr", glsl::ExtInst::ExtInstPow)
5503 .StartsWith("_Z9half_powr", glsl::ExtInst::ExtInstPow)
5504 .StartsWith("_Z11native_powr", glsl::ExtInst::ExtInstPow)
5505 .StartsWith("_Z5round", glsl::ExtInst::ExtInstRound)
5506 .StartsWith("_Z4sqrt", glsl::ExtInst::ExtInstSqrt)
5507 .StartsWith("_Z9half_sqrt", glsl::ExtInst::ExtInstSqrt)
5508 .StartsWith("_Z11native_sqrt", glsl::ExtInst::ExtInstSqrt)
5509 .StartsWith("_Z5rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5510 .StartsWith("_Z10half_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5511 .StartsWith("_Z12native_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5512 .StartsWith("_Z5trunc", glsl::ExtInst::ExtInstTrunc)
5513 .StartsWith("_Z5frexp", glsl::ExtInst::ExtInstFrexp)
5514 .StartsWith("_Z4sign", glsl::ExtInst::ExtInstFSign)
5515 .StartsWith("_Z6length", glsl::ExtInst::ExtInstLength)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005516 .StartsWith("_Z11fast_length", glsl::ExtInst::ExtInstLength)
David Neto22f144c2017-06-12 14:26:21 -04005517 .StartsWith("_Z8distance", glsl::ExtInst::ExtInstDistance)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005518 .StartsWith("_Z13fast_distance", glsl::ExtInst::ExtInstDistance)
David Netoe9a03512017-10-16 10:08:27 -04005519 .StartsWith("_Z4step", glsl::ExtInst::ExtInstStep)
kpet6fd2a262018-10-03 14:48:01 +01005520 .StartsWith("_Z10smoothstep", glsl::ExtInst::ExtInstSmoothStep)
David Neto22f144c2017-06-12 14:26:21 -04005521 .Case("_Z5crossDv3_fS_", glsl::ExtInst::ExtInstCross)
5522 .StartsWith("_Z9normalize", glsl::ExtInst::ExtInstNormalize)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005523 .StartsWith("_Z14fast_normalize", glsl::ExtInst::ExtInstNormalize)
David Neto22f144c2017-06-12 14:26:21 -04005524 .StartsWith("llvm.fmuladd.", glsl::ExtInst::ExtInstFma)
5525 .Case("spirv.unpack.v2f16", glsl::ExtInst::ExtInstUnpackHalf2x16)
5526 .Case("spirv.pack.v2f16", glsl::ExtInst::ExtInstPackHalf2x16)
David Neto62653202017-10-16 19:05:18 -04005527 .Case("clspv.fract.f", glsl::ExtInst::ExtInstFract)
5528 .Case("clspv.fract.v2f", glsl::ExtInst::ExtInstFract)
5529 .Case("clspv.fract.v3f", glsl::ExtInst::ExtInstFract)
5530 .Case("clspv.fract.v4f", glsl::ExtInst::ExtInstFract)
David Neto3fbb4072017-10-16 11:28:14 -04005531 .Default(kGlslExtInstBad);
5532}
5533
5534glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(StringRef Name) {
5535 // Check indirect cases.
5536 return StringSwitch<glsl::ExtInst>(Name)
5537 .StartsWith("_Z3clz", glsl::ExtInst::ExtInstFindUMsb)
5538 // Use exact match on float arg because these need a multiply
5539 // of a constant of the right floating point type.
5540 .Case("_Z6acospif", glsl::ExtInst::ExtInstAcos)
5541 .Case("_Z6acospiDv2_f", glsl::ExtInst::ExtInstAcos)
5542 .Case("_Z6acospiDv3_f", glsl::ExtInst::ExtInstAcos)
5543 .Case("_Z6acospiDv4_f", glsl::ExtInst::ExtInstAcos)
5544 .Case("_Z6asinpif", glsl::ExtInst::ExtInstAsin)
5545 .Case("_Z6asinpiDv2_f", glsl::ExtInst::ExtInstAsin)
5546 .Case("_Z6asinpiDv3_f", glsl::ExtInst::ExtInstAsin)
5547 .Case("_Z6asinpiDv4_f", glsl::ExtInst::ExtInstAsin)
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005548 .Case("_Z6atanpif", glsl::ExtInst::ExtInstAtan)
5549 .Case("_Z6atanpiDv2_f", glsl::ExtInst::ExtInstAtan)
5550 .Case("_Z6atanpiDv3_f", glsl::ExtInst::ExtInstAtan)
5551 .Case("_Z6atanpiDv4_f", glsl::ExtInst::ExtInstAtan)
David Neto3fbb4072017-10-16 11:28:14 -04005552 .Case("_Z7atan2piff", glsl::ExtInst::ExtInstAtan2)
5553 .Case("_Z7atan2piDv2_fS_", glsl::ExtInst::ExtInstAtan2)
5554 .Case("_Z7atan2piDv3_fS_", glsl::ExtInst::ExtInstAtan2)
5555 .Case("_Z7atan2piDv4_fS_", glsl::ExtInst::ExtInstAtan2)
5556 .Default(kGlslExtInstBad);
5557}
5558
alan-bakerb6b09dc2018-11-08 16:59:28 -05005559glsl::ExtInst
5560SPIRVProducerPass::getDirectOrIndirectExtInstEnum(StringRef Name) {
David Neto3fbb4072017-10-16 11:28:14 -04005561 auto direct = getExtInstEnum(Name);
5562 if (direct != kGlslExtInstBad)
5563 return direct;
5564 return getIndirectExtInstEnum(Name);
David Neto22f144c2017-06-12 14:26:21 -04005565}
5566
David Neto22f144c2017-06-12 14:26:21 -04005567void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04005568 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04005569}
5570
5571void SPIRVProducerPass::WriteResultID(SPIRVInstruction *Inst) {
5572 WriteOneWord(Inst->getResultID());
5573}
5574
5575void SPIRVProducerPass::WriteWordCountAndOpcode(SPIRVInstruction *Inst) {
5576 // High 16 bit : Word Count
5577 // Low 16 bit : Opcode
5578 uint32_t Word = Inst->getOpcode();
David Netoee2660d2018-06-28 16:31:29 -04005579 const uint32_t count = Inst->getWordCount();
5580 if (count > 65535) {
5581 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
5582 llvm_unreachable("Word count too high");
5583 }
David Neto22f144c2017-06-12 14:26:21 -04005584 Word |= Inst->getWordCount() << 16;
5585 WriteOneWord(Word);
5586}
5587
David Netoef5ba2b2019-12-20 08:35:54 -05005588void SPIRVProducerPass::WriteOperand(const std::unique_ptr<SPIRVOperand> &Op) {
David Neto22f144c2017-06-12 14:26:21 -04005589 SPIRVOperandType OpTy = Op->getType();
5590 switch (OpTy) {
5591 default: {
5592 llvm_unreachable("Unsupported SPIRV Operand Type???");
5593 break;
5594 }
5595 case SPIRVOperandType::NUMBERID: {
5596 WriteOneWord(Op->getNumID());
5597 break;
5598 }
5599 case SPIRVOperandType::LITERAL_STRING: {
5600 std::string Str = Op->getLiteralStr();
5601 const char *Data = Str.c_str();
5602 size_t WordSize = Str.size() / 4;
5603 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
5604 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
5605 }
5606
5607 uint32_t Remainder = Str.size() % 4;
5608 uint32_t LastWord = 0;
5609 if (Remainder) {
5610 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
5611 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
5612 }
5613 }
5614
5615 WriteOneWord(LastWord);
5616 break;
5617 }
5618 case SPIRVOperandType::LITERAL_INTEGER:
5619 case SPIRVOperandType::LITERAL_FLOAT: {
5620 auto LiteralNum = Op->getLiteralNum();
5621 // TODO: Handle LiteranNum carefully.
5622 for (auto Word : LiteralNum) {
5623 WriteOneWord(Word);
5624 }
5625 break;
5626 }
5627 }
5628}
5629
5630void SPIRVProducerPass::WriteSPIRVBinary() {
5631 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5632
5633 for (auto Inst : SPIRVInstList) {
David Netoef5ba2b2019-12-20 08:35:54 -05005634 const auto &Ops = Inst->getOperands();
David Neto22f144c2017-06-12 14:26:21 -04005635 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5636
5637 switch (Opcode) {
5638 default: {
David Neto5c22a252018-03-15 16:07:41 -04005639 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04005640 llvm_unreachable("Unsupported SPIRV instruction");
5641 break;
5642 }
5643 case spv::OpCapability:
5644 case spv::OpExtension:
5645 case spv::OpMemoryModel:
5646 case spv::OpEntryPoint:
5647 case spv::OpExecutionMode:
5648 case spv::OpSource:
5649 case spv::OpDecorate:
5650 case spv::OpMemberDecorate:
5651 case spv::OpBranch:
5652 case spv::OpBranchConditional:
5653 case spv::OpSelectionMerge:
5654 case spv::OpLoopMerge:
5655 case spv::OpStore:
5656 case spv::OpImageWrite:
5657 case spv::OpReturnValue:
5658 case spv::OpControlBarrier:
5659 case spv::OpMemoryBarrier:
5660 case spv::OpReturn:
5661 case spv::OpFunctionEnd:
5662 case spv::OpCopyMemory: {
5663 WriteWordCountAndOpcode(Inst);
5664 for (uint32_t i = 0; i < Ops.size(); i++) {
5665 WriteOperand(Ops[i]);
5666 }
5667 break;
5668 }
5669 case spv::OpTypeBool:
5670 case spv::OpTypeVoid:
5671 case spv::OpTypeSampler:
5672 case spv::OpLabel:
5673 case spv::OpExtInstImport:
5674 case spv::OpTypePointer:
5675 case spv::OpTypeRuntimeArray:
5676 case spv::OpTypeStruct:
5677 case spv::OpTypeImage:
5678 case spv::OpTypeSampledImage:
5679 case spv::OpTypeInt:
5680 case spv::OpTypeFloat:
5681 case spv::OpTypeArray:
5682 case spv::OpTypeVector:
5683 case spv::OpTypeFunction: {
5684 WriteWordCountAndOpcode(Inst);
5685 WriteResultID(Inst);
5686 for (uint32_t i = 0; i < Ops.size(); i++) {
5687 WriteOperand(Ops[i]);
5688 }
5689 break;
5690 }
5691 case spv::OpFunction:
5692 case spv::OpFunctionParameter:
5693 case spv::OpAccessChain:
5694 case spv::OpPtrAccessChain:
5695 case spv::OpInBoundsAccessChain:
5696 case spv::OpUConvert:
5697 case spv::OpSConvert:
5698 case spv::OpConvertFToU:
5699 case spv::OpConvertFToS:
5700 case spv::OpConvertUToF:
5701 case spv::OpConvertSToF:
5702 case spv::OpFConvert:
5703 case spv::OpConvertPtrToU:
5704 case spv::OpConvertUToPtr:
5705 case spv::OpBitcast:
alan-bakerc9c55ae2019-12-02 16:01:27 -05005706 case spv::OpFNegate:
David Neto22f144c2017-06-12 14:26:21 -04005707 case spv::OpIAdd:
5708 case spv::OpFAdd:
5709 case spv::OpISub:
5710 case spv::OpFSub:
5711 case spv::OpIMul:
5712 case spv::OpFMul:
5713 case spv::OpUDiv:
5714 case spv::OpSDiv:
5715 case spv::OpFDiv:
5716 case spv::OpUMod:
5717 case spv::OpSRem:
5718 case spv::OpFRem:
Kévin Petit8a560882019-03-21 15:24:34 +00005719 case spv::OpUMulExtended:
5720 case spv::OpSMulExtended:
David Neto22f144c2017-06-12 14:26:21 -04005721 case spv::OpBitwiseOr:
5722 case spv::OpBitwiseXor:
5723 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005724 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005725 case spv::OpShiftLeftLogical:
5726 case spv::OpShiftRightLogical:
5727 case spv::OpShiftRightArithmetic:
5728 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04005729 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04005730 case spv::OpCompositeExtract:
5731 case spv::OpVectorExtractDynamic:
5732 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04005733 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04005734 case spv::OpVectorInsertDynamic:
5735 case spv::OpVectorShuffle:
5736 case spv::OpIEqual:
5737 case spv::OpINotEqual:
5738 case spv::OpUGreaterThan:
5739 case spv::OpUGreaterThanEqual:
5740 case spv::OpULessThan:
5741 case spv::OpULessThanEqual:
5742 case spv::OpSGreaterThan:
5743 case spv::OpSGreaterThanEqual:
5744 case spv::OpSLessThan:
5745 case spv::OpSLessThanEqual:
5746 case spv::OpFOrdEqual:
5747 case spv::OpFOrdGreaterThan:
5748 case spv::OpFOrdGreaterThanEqual:
5749 case spv::OpFOrdLessThan:
5750 case spv::OpFOrdLessThanEqual:
5751 case spv::OpFOrdNotEqual:
5752 case spv::OpFUnordEqual:
5753 case spv::OpFUnordGreaterThan:
5754 case spv::OpFUnordGreaterThanEqual:
5755 case spv::OpFUnordLessThan:
5756 case spv::OpFUnordLessThanEqual:
5757 case spv::OpFUnordNotEqual:
5758 case spv::OpExtInst:
5759 case spv::OpIsInf:
5760 case spv::OpIsNan:
5761 case spv::OpAny:
5762 case spv::OpAll:
5763 case spv::OpUndef:
5764 case spv::OpConstantNull:
5765 case spv::OpLogicalOr:
5766 case spv::OpLogicalAnd:
5767 case spv::OpLogicalNot:
5768 case spv::OpLogicalNotEqual:
5769 case spv::OpConstantComposite:
5770 case spv::OpSpecConstantComposite:
5771 case spv::OpConstantTrue:
5772 case spv::OpConstantFalse:
5773 case spv::OpConstant:
5774 case spv::OpSpecConstant:
5775 case spv::OpVariable:
5776 case spv::OpFunctionCall:
5777 case spv::OpSampledImage:
5778 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04005779 case spv::OpImageQuerySize:
alan-bakerce179f12019-12-06 19:02:22 -05005780 case spv::OpImageQuerySizeLod:
David Neto22f144c2017-06-12 14:26:21 -04005781 case spv::OpSelect:
5782 case spv::OpPhi:
5783 case spv::OpLoad:
5784 case spv::OpAtomicIAdd:
5785 case spv::OpAtomicISub:
5786 case spv::OpAtomicExchange:
5787 case spv::OpAtomicIIncrement:
5788 case spv::OpAtomicIDecrement:
5789 case spv::OpAtomicCompareExchange:
5790 case spv::OpAtomicUMin:
5791 case spv::OpAtomicSMin:
5792 case spv::OpAtomicUMax:
5793 case spv::OpAtomicSMax:
5794 case spv::OpAtomicAnd:
5795 case spv::OpAtomicOr:
5796 case spv::OpAtomicXor:
5797 case spv::OpDot: {
5798 WriteWordCountAndOpcode(Inst);
5799 WriteOperand(Ops[0]);
5800 WriteResultID(Inst);
5801 for (uint32_t i = 1; i < Ops.size(); i++) {
5802 WriteOperand(Ops[i]);
5803 }
5804 break;
5805 }
5806 }
5807 }
5808}
Alan Baker9bf93fb2018-08-28 16:59:26 -04005809
alan-bakerb6b09dc2018-11-08 16:59:28 -05005810bool SPIRVProducerPass::IsTypeNullable(const Type *type) const {
Alan Baker9bf93fb2018-08-28 16:59:26 -04005811 switch (type->getTypeID()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005812 case Type::HalfTyID:
5813 case Type::FloatTyID:
5814 case Type::DoubleTyID:
5815 case Type::IntegerTyID:
5816 case Type::VectorTyID:
5817 return true;
5818 case Type::PointerTyID: {
5819 const PointerType *pointer_type = cast<PointerType>(type);
5820 if (pointer_type->getPointerAddressSpace() !=
5821 AddressSpace::UniformConstant) {
5822 auto pointee_type = pointer_type->getPointerElementType();
5823 if (pointee_type->isStructTy() &&
5824 cast<StructType>(pointee_type)->isOpaque()) {
5825 // Images and samplers are not nullable.
5826 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04005827 }
Alan Baker9bf93fb2018-08-28 16:59:26 -04005828 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05005829 return true;
5830 }
5831 case Type::ArrayTyID:
5832 return IsTypeNullable(cast<CompositeType>(type)->getTypeAtIndex(0u));
5833 case Type::StructTyID: {
5834 const StructType *struct_type = cast<StructType>(type);
5835 // Images and samplers are not nullable.
5836 if (struct_type->isOpaque())
Alan Baker9bf93fb2018-08-28 16:59:26 -04005837 return false;
alan-bakerb6b09dc2018-11-08 16:59:28 -05005838 for (const auto element : struct_type->elements()) {
5839 if (!IsTypeNullable(element))
5840 return false;
5841 }
5842 return true;
5843 }
5844 default:
5845 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04005846 }
5847}
Alan Bakerfcda9482018-10-02 17:09:59 -04005848
5849void SPIRVProducerPass::PopulateUBOTypeMaps(Module &module) {
5850 if (auto *offsets_md =
5851 module.getNamedMetadata(clspv::RemappedTypeOffsetMetadataName())) {
5852 // Metdata is stored as key-value pair operands. The first element of each
5853 // operand is the type and the second is a vector of offsets.
5854 for (const auto *operand : offsets_md->operands()) {
5855 const auto *pair = cast<MDTuple>(operand);
5856 auto *type =
5857 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
5858 const auto *offset_vector = cast<MDTuple>(pair->getOperand(1));
5859 std::vector<uint32_t> offsets;
5860 for (const Metadata *offset_md : offset_vector->operands()) {
5861 const auto *constant_md = cast<ConstantAsMetadata>(offset_md);
alan-bakerb6b09dc2018-11-08 16:59:28 -05005862 offsets.push_back(static_cast<uint32_t>(
5863 cast<ConstantInt>(constant_md->getValue())->getZExtValue()));
Alan Bakerfcda9482018-10-02 17:09:59 -04005864 }
5865 RemappedUBOTypeOffsets.insert(std::make_pair(type, offsets));
5866 }
5867 }
5868
5869 if (auto *sizes_md =
5870 module.getNamedMetadata(clspv::RemappedTypeSizesMetadataName())) {
5871 // Metadata is stored as key-value pair operands. The first element of each
5872 // operand is the type and the second is a triple of sizes: type size in
5873 // bits, store size and alloc size.
5874 for (const auto *operand : sizes_md->operands()) {
5875 const auto *pair = cast<MDTuple>(operand);
5876 auto *type =
5877 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
5878 const auto *size_triple = cast<MDTuple>(pair->getOperand(1));
5879 uint64_t type_size_in_bits =
5880 cast<ConstantInt>(
5881 cast<ConstantAsMetadata>(size_triple->getOperand(0))->getValue())
5882 ->getZExtValue();
5883 uint64_t type_store_size =
5884 cast<ConstantInt>(
5885 cast<ConstantAsMetadata>(size_triple->getOperand(1))->getValue())
5886 ->getZExtValue();
5887 uint64_t type_alloc_size =
5888 cast<ConstantInt>(
5889 cast<ConstantAsMetadata>(size_triple->getOperand(2))->getValue())
5890 ->getZExtValue();
5891 RemappedUBOTypeSizes.insert(std::make_pair(
5892 type, std::make_tuple(type_size_in_bits, type_store_size,
5893 type_alloc_size)));
5894 }
5895 }
5896}
5897
5898uint64_t SPIRVProducerPass::GetTypeSizeInBits(Type *type,
5899 const DataLayout &DL) {
5900 auto iter = RemappedUBOTypeSizes.find(type);
5901 if (iter != RemappedUBOTypeSizes.end()) {
5902 return std::get<0>(iter->second);
5903 }
5904
5905 return DL.getTypeSizeInBits(type);
5906}
5907
5908uint64_t SPIRVProducerPass::GetTypeStoreSize(Type *type, const DataLayout &DL) {
5909 auto iter = RemappedUBOTypeSizes.find(type);
5910 if (iter != RemappedUBOTypeSizes.end()) {
5911 return std::get<1>(iter->second);
5912 }
5913
5914 return DL.getTypeStoreSize(type);
5915}
5916
5917uint64_t SPIRVProducerPass::GetTypeAllocSize(Type *type, const DataLayout &DL) {
5918 auto iter = RemappedUBOTypeSizes.find(type);
5919 if (iter != RemappedUBOTypeSizes.end()) {
5920 return std::get<2>(iter->second);
5921 }
5922
5923 return DL.getTypeAllocSize(type);
5924}
alan-baker5b86ed72019-02-15 08:26:50 -05005925
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04005926void SPIRVProducerPass::setVariablePointersCapabilities(
5927 unsigned address_space) {
alan-baker5b86ed72019-02-15 08:26:50 -05005928 if (GetStorageClass(address_space) == spv::StorageClassStorageBuffer) {
5929 setVariablePointersStorageBuffer(true);
5930 } else {
5931 setVariablePointers(true);
5932 }
5933}
5934
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04005935Value *SPIRVProducerPass::GetBasePointer(Value *v) {
alan-baker5b86ed72019-02-15 08:26:50 -05005936 if (auto *gep = dyn_cast<GetElementPtrInst>(v)) {
5937 return GetBasePointer(gep->getPointerOperand());
5938 }
5939
5940 // Conservatively return |v|.
5941 return v;
5942}
5943
5944bool SPIRVProducerPass::sameResource(Value *lhs, Value *rhs) const {
5945 if (auto *lhs_call = dyn_cast<CallInst>(lhs)) {
5946 if (auto *rhs_call = dyn_cast<CallInst>(rhs)) {
5947 if (lhs_call->getCalledFunction()->getName().startswith(
5948 clspv::ResourceAccessorFunction()) &&
5949 rhs_call->getCalledFunction()->getName().startswith(
5950 clspv::ResourceAccessorFunction())) {
5951 // For resource accessors, match descriptor set and binding.
5952 if (lhs_call->getOperand(0) == rhs_call->getOperand(0) &&
5953 lhs_call->getOperand(1) == rhs_call->getOperand(1))
5954 return true;
5955 } else if (lhs_call->getCalledFunction()->getName().startswith(
5956 clspv::WorkgroupAccessorFunction()) &&
5957 rhs_call->getCalledFunction()->getName().startswith(
5958 clspv::WorkgroupAccessorFunction())) {
5959 // For workgroup resources, match spec id.
5960 if (lhs_call->getOperand(0) == rhs_call->getOperand(0))
5961 return true;
5962 }
5963 }
5964 }
5965
5966 return false;
5967}
5968
5969bool SPIRVProducerPass::selectFromSameObject(Instruction *inst) {
5970 assert(inst->getType()->isPointerTy());
5971 assert(GetStorageClass(inst->getType()->getPointerAddressSpace()) ==
5972 spv::StorageClassStorageBuffer);
5973 const bool hack_undef = clspv::Option::HackUndef();
5974 if (auto *select = dyn_cast<SelectInst>(inst)) {
5975 auto *true_base = GetBasePointer(select->getTrueValue());
5976 auto *false_base = GetBasePointer(select->getFalseValue());
5977
5978 if (true_base == false_base)
5979 return true;
5980
5981 // If either the true or false operand is a null, then we satisfy the same
5982 // object constraint.
5983 if (auto *true_cst = dyn_cast<Constant>(true_base)) {
5984 if (true_cst->isNullValue() || (hack_undef && isa<UndefValue>(true_base)))
5985 return true;
5986 }
5987
5988 if (auto *false_cst = dyn_cast<Constant>(false_base)) {
5989 if (false_cst->isNullValue() ||
5990 (hack_undef && isa<UndefValue>(false_base)))
5991 return true;
5992 }
5993
5994 if (sameResource(true_base, false_base))
5995 return true;
5996 } else if (auto *phi = dyn_cast<PHINode>(inst)) {
5997 Value *value = nullptr;
5998 bool ok = true;
5999 for (unsigned i = 0; ok && i != phi->getNumIncomingValues(); ++i) {
6000 auto *base = GetBasePointer(phi->getIncomingValue(i));
6001 // Null values satisfy the constraint of selecting of selecting from the
6002 // same object.
6003 if (!value) {
6004 if (auto *cst = dyn_cast<Constant>(base)) {
6005 if (!cst->isNullValue() && !(hack_undef && isa<UndefValue>(base)))
6006 value = base;
6007 } else {
6008 value = base;
6009 }
6010 } else if (base != value) {
6011 if (auto *base_cst = dyn_cast<Constant>(base)) {
6012 if (base_cst->isNullValue() || (hack_undef && isa<UndefValue>(base)))
6013 continue;
6014 }
6015
6016 if (sameResource(value, base))
6017 continue;
6018
6019 // Values don't represent the same base.
6020 ok = false;
6021 }
6022 }
6023
6024 return ok;
6025 }
6026
6027 // Conservatively return false.
6028 return false;
6029}
alan-bakere9308012019-03-15 10:25:13 -04006030
6031bool SPIRVProducerPass::CalledWithCoherentResource(Argument &Arg) {
6032 if (!Arg.getType()->isPointerTy() ||
6033 Arg.getType()->getPointerAddressSpace() != clspv::AddressSpace::Global) {
6034 // Only SSBOs need to be annotated as coherent.
6035 return false;
6036 }
6037
6038 DenseSet<Value *> visited;
6039 std::vector<Value *> stack;
6040 for (auto *U : Arg.getParent()->users()) {
6041 if (auto *call = dyn_cast<CallInst>(U)) {
6042 stack.push_back(call->getOperand(Arg.getArgNo()));
6043 }
6044 }
6045
6046 while (!stack.empty()) {
6047 Value *v = stack.back();
6048 stack.pop_back();
6049
6050 if (!visited.insert(v).second)
6051 continue;
6052
6053 auto *resource_call = dyn_cast<CallInst>(v);
6054 if (resource_call &&
6055 resource_call->getCalledFunction()->getName().startswith(
6056 clspv::ResourceAccessorFunction())) {
6057 // If this is a resource accessor function, check if the coherent operand
6058 // is set.
6059 const auto coherent =
6060 unsigned(dyn_cast<ConstantInt>(resource_call->getArgOperand(5))
6061 ->getZExtValue());
6062 if (coherent == 1)
6063 return true;
6064 } else if (auto *arg = dyn_cast<Argument>(v)) {
6065 // If this is a function argument, trace through its callers.
alan-bakere98f3f92019-04-08 15:06:36 -04006066 for (auto U : arg->getParent()->users()) {
alan-bakere9308012019-03-15 10:25:13 -04006067 if (auto *call = dyn_cast<CallInst>(U)) {
6068 stack.push_back(call->getOperand(arg->getArgNo()));
6069 }
6070 }
6071 } else if (auto *user = dyn_cast<User>(v)) {
6072 // If this is a user, traverse all operands that could lead to resource
6073 // variables.
6074 for (unsigned i = 0; i != user->getNumOperands(); ++i) {
6075 Value *operand = user->getOperand(i);
6076 if (operand->getType()->isPointerTy() &&
6077 operand->getType()->getPointerAddressSpace() ==
6078 clspv::AddressSpace::Global) {
6079 stack.push_back(operand);
6080 }
6081 }
6082 }
6083 }
6084
6085 // No coherent resource variables encountered.
6086 return false;
6087}
alan-baker06cad652019-12-03 17:56:47 -05006088
6089void SPIRVProducerPass::PopulateStructuredCFGMaps(Module &module) {
6090 // First, track loop merges and continues.
6091 DenseSet<BasicBlock *> LoopMergesAndContinues;
6092 for (auto &F : module) {
6093 if (F.isDeclaration())
6094 continue;
6095
6096 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
6097 const LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>(F).getLoopInfo();
6098 std::deque<BasicBlock *> order;
6099 DenseSet<BasicBlock *> visited;
6100 clspv::ComputeStructuredOrder(&*F.begin(), &DT, LI, &order, &visited);
6101
6102 for (auto BB : order) {
6103 auto terminator = BB->getTerminator();
6104 auto branch = dyn_cast<BranchInst>(terminator);
6105 if (LI.isLoopHeader(BB)) {
6106 auto L = LI.getLoopFor(BB);
6107 BasicBlock *ContinueBB = nullptr;
6108 BasicBlock *MergeBB = nullptr;
6109
6110 MergeBB = L->getExitBlock();
6111 if (!MergeBB) {
6112 // StructurizeCFG pass converts CFG into triangle shape and the cfg
6113 // has regions with single entry/exit. As a result, loop should not
6114 // have multiple exits.
6115 llvm_unreachable("Loop has multiple exits???");
6116 }
6117
6118 if (L->isLoopLatch(BB)) {
6119 ContinueBB = BB;
6120 } else {
6121 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
6122 // block.
6123 BasicBlock *Header = L->getHeader();
6124 BasicBlock *Latch = L->getLoopLatch();
6125 for (auto *loop_block : L->blocks()) {
6126 if (loop_block == Header) {
6127 continue;
6128 }
6129
6130 // Check whether block dominates block with back-edge.
6131 // The loop latch is the single block with a back-edge. If it was
6132 // possible, StructurizeCFG made the loop conform to this
6133 // requirement, otherwise |Latch| is a nullptr.
6134 if (DT.dominates(loop_block, Latch)) {
6135 ContinueBB = loop_block;
6136 }
6137 }
6138
6139 if (!ContinueBB) {
6140 llvm_unreachable("Wrong continue block from loop");
6141 }
6142 }
6143
6144 // Record the continue and merge blocks.
6145 MergeBlocks[BB] = MergeBB;
6146 ContinueBlocks[BB] = ContinueBB;
6147 LoopMergesAndContinues.insert(MergeBB);
6148 LoopMergesAndContinues.insert(ContinueBB);
6149 } else if (branch && branch->isConditional()) {
6150 auto L = LI.getLoopFor(BB);
6151 bool HasBackedge = false;
6152 while (L && !HasBackedge) {
6153 if (L->isLoopLatch(BB)) {
6154 HasBackedge = true;
6155 }
6156 L = L->getParentLoop();
6157 }
6158
6159 if (!HasBackedge) {
6160 // Only need a merge if the branch doesn't include a loop break or
6161 // continue.
6162 auto true_bb = branch->getSuccessor(0);
6163 auto false_bb = branch->getSuccessor(1);
6164 if (!LoopMergesAndContinues.count(true_bb) &&
6165 !LoopMergesAndContinues.count(false_bb)) {
6166 // StructurizeCFG pass already manipulated CFG. Just use false block
6167 // of branch instruction as merge block.
6168 MergeBlocks[BB] = false_bb;
6169 }
6170 }
6171 }
6172 }
6173 }
6174}