blob: 135140f683581c67c089156eeda50a3608f16046 [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"
39#include "llvm/Pass.h"
40#include "llvm/Support/CommandLine.h"
41#include "llvm/Support/raw_ostream.h"
42#include "llvm/Transforms/Utils/Cloning.h"
David Neto22f144c2017-06-12 14:26:21 -040043
David Neto85082642018-03-24 06:55:20 -070044#include "spirv/1.0/spirv.hpp"
David Neto118188e2018-08-24 11:27:54 -040045
David Neto85082642018-03-24 06:55:20 -070046#include "clspv/AddressSpace.h"
alan-bakerf5e5f692018-11-27 08:33:24 -050047#include "clspv/DescriptorMap.h"
David Neto118188e2018-08-24 11:27:54 -040048#include "clspv/Option.h"
49#include "clspv/Passes.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"
David Neto85082642018-03-24 06:55:20 -070054#include "ConstantEmitter.h"
Alan Baker202c8c72018-08-13 13:47:44 -040055#include "Constants.h"
David Neto78383442018-06-15 20:31:56 -040056#include "DescriptorCounter.h"
David Neto48f56a42017-10-06 16:44:25 -040057
David Neto22f144c2017-06-12 14:26:21 -040058#if defined(_MSC_VER)
59#pragma warning(pop)
60#endif
61
62using namespace llvm;
63using namespace clspv;
David Neto156783e2017-07-05 15:39:41 -040064using namespace mdconst;
David Neto22f144c2017-06-12 14:26:21 -040065
66namespace {
David Netocd8ca5f2017-10-02 23:34:11 -040067
David Neto862b7d82018-06-14 18:48:37 -040068cl::opt<bool> ShowResourceVars("show-rv", cl::init(false), cl::Hidden,
69 cl::desc("Show resource variable creation"));
70
71// These hacks exist to help transition code generation algorithms
72// without making huge noise in detailed test output.
73const bool Hack_generate_runtime_array_stride_early = true;
74
David Neto3fbb4072017-10-16 11:28:14 -040075// The value of 1/pi. This value is from MSDN
76// https://msdn.microsoft.com/en-us/library/4hwaceh6.aspx
77const double kOneOverPi = 0.318309886183790671538;
78const glsl::ExtInst kGlslExtInstBad = static_cast<glsl::ExtInst>(0);
79
alan-bakerb6b09dc2018-11-08 16:59:28 -050080const char *kCompositeConstructFunctionPrefix = "clspv.composite_construct.";
David Netoab03f432017-11-03 17:00:44 -040081
David Neto22f144c2017-06-12 14:26:21 -040082enum SPIRVOperandType {
83 NUMBERID,
84 LITERAL_INTEGER,
85 LITERAL_STRING,
86 LITERAL_FLOAT
87};
88
89struct SPIRVOperand {
90 explicit SPIRVOperand(SPIRVOperandType Ty, uint32_t Num)
91 : Type(Ty), LiteralNum(1, Num) {}
92 explicit SPIRVOperand(SPIRVOperandType Ty, const char *Str)
93 : Type(Ty), LiteralStr(Str) {}
94 explicit SPIRVOperand(SPIRVOperandType Ty, StringRef Str)
95 : Type(Ty), LiteralStr(Str) {}
96 explicit SPIRVOperand(SPIRVOperandType Ty, ArrayRef<uint32_t> NumVec)
97 : Type(Ty), LiteralNum(NumVec.begin(), NumVec.end()) {}
98
99 SPIRVOperandType getType() { return Type; };
100 uint32_t getNumID() { return LiteralNum[0]; };
101 std::string getLiteralStr() { return LiteralStr; };
102 ArrayRef<uint32_t> getLiteralNum() { return LiteralNum; };
103
David Neto87846742018-04-11 17:36:22 -0400104 uint32_t GetNumWords() const {
105 switch (Type) {
106 case NUMBERID:
107 return 1;
108 case LITERAL_INTEGER:
109 case LITERAL_FLOAT:
David Netoee2660d2018-06-28 16:31:29 -0400110 return uint32_t(LiteralNum.size());
David Neto87846742018-04-11 17:36:22 -0400111 case LITERAL_STRING:
112 // Account for the terminating null character.
David Netoee2660d2018-06-28 16:31:29 -0400113 return uint32_t((LiteralStr.size() + 4) / 4);
David Neto87846742018-04-11 17:36:22 -0400114 }
115 llvm_unreachable("Unhandled case in SPIRVOperand::GetNumWords()");
116 }
117
David Neto22f144c2017-06-12 14:26:21 -0400118private:
119 SPIRVOperandType Type;
120 std::string LiteralStr;
121 SmallVector<uint32_t, 4> LiteralNum;
122};
123
David Netoc6f3ab22018-04-06 18:02:31 -0400124class SPIRVOperandList {
125public:
126 SPIRVOperandList() {}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500127 SPIRVOperandList(const SPIRVOperandList &other) = delete;
128 SPIRVOperandList(SPIRVOperandList &&other) {
David Netoc6f3ab22018-04-06 18:02:31 -0400129 contents_ = std::move(other.contents_);
130 other.contents_.clear();
131 }
132 SPIRVOperandList(ArrayRef<SPIRVOperand *> init)
133 : contents_(init.begin(), init.end()) {}
134 operator ArrayRef<SPIRVOperand *>() { return contents_; }
135 void push_back(SPIRVOperand *op) { contents_.push_back(op); }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500136 void clear() { contents_.clear(); }
David Netoc6f3ab22018-04-06 18:02:31 -0400137 size_t size() const { return contents_.size(); }
138 SPIRVOperand *&operator[](size_t i) { return contents_[i]; }
139
David Neto87846742018-04-11 17:36:22 -0400140 const SmallVector<SPIRVOperand *, 8> &getOperands() const {
141 return contents_;
142 }
143
David Netoc6f3ab22018-04-06 18:02:31 -0400144private:
alan-bakerb6b09dc2018-11-08 16:59:28 -0500145 SmallVector<SPIRVOperand *, 8> contents_;
David Netoc6f3ab22018-04-06 18:02:31 -0400146};
147
148SPIRVOperandList &operator<<(SPIRVOperandList &list, SPIRVOperand *elem) {
149 list.push_back(elem);
150 return list;
151}
152
alan-bakerb6b09dc2018-11-08 16:59:28 -0500153SPIRVOperand *MkNum(uint32_t num) {
David Netoc6f3ab22018-04-06 18:02:31 -0400154 return new SPIRVOperand(LITERAL_INTEGER, num);
155}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500156SPIRVOperand *MkInteger(ArrayRef<uint32_t> num_vec) {
David Neto257c3892018-04-11 13:19:45 -0400157 return new SPIRVOperand(LITERAL_INTEGER, num_vec);
158}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500159SPIRVOperand *MkFloat(ArrayRef<uint32_t> num_vec) {
David Neto257c3892018-04-11 13:19:45 -0400160 return new SPIRVOperand(LITERAL_FLOAT, num_vec);
161}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500162SPIRVOperand *MkId(uint32_t id) { return new SPIRVOperand(NUMBERID, id); }
163SPIRVOperand *MkString(StringRef str) {
David Neto257c3892018-04-11 13:19:45 -0400164 return new SPIRVOperand(LITERAL_STRING, str);
165}
David Netoc6f3ab22018-04-06 18:02:31 -0400166
David Neto22f144c2017-06-12 14:26:21 -0400167struct SPIRVInstruction {
David Neto87846742018-04-11 17:36:22 -0400168 // Create an instruction with an opcode and no result ID, and with the given
169 // operands. This computes its own word count.
170 explicit SPIRVInstruction(spv::Op Opc, ArrayRef<SPIRVOperand *> Ops)
171 : WordCount(1), Opcode(static_cast<uint16_t>(Opc)), ResultID(0),
172 Operands(Ops.begin(), Ops.end()) {
173 for (auto *operand : Ops) {
David Netoee2660d2018-06-28 16:31:29 -0400174 WordCount += uint16_t(operand->GetNumWords());
David Neto87846742018-04-11 17:36:22 -0400175 }
176 }
177 // Create an instruction with an opcode and a no-zero result ID, and
178 // with the given operands. This computes its own word count.
179 explicit SPIRVInstruction(spv::Op Opc, uint32_t ResID,
David Neto22f144c2017-06-12 14:26:21 -0400180 ArrayRef<SPIRVOperand *> Ops)
David Neto87846742018-04-11 17:36:22 -0400181 : WordCount(2), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID),
182 Operands(Ops.begin(), Ops.end()) {
183 if (ResID == 0) {
184 llvm_unreachable("Result ID of 0 was provided");
185 }
186 for (auto *operand : Ops) {
187 WordCount += operand->GetNumWords();
188 }
189 }
David Neto22f144c2017-06-12 14:26:21 -0400190
David Netoee2660d2018-06-28 16:31:29 -0400191 uint32_t getWordCount() const { return WordCount; }
David Neto22f144c2017-06-12 14:26:21 -0400192 uint16_t getOpcode() const { return Opcode; }
193 uint32_t getResultID() const { return ResultID; }
194 ArrayRef<SPIRVOperand *> getOperands() const { return Operands; }
195
196private:
David Netoee2660d2018-06-28 16:31:29 -0400197 uint32_t WordCount; // Check the 16-bit bound at code generation time.
David Neto22f144c2017-06-12 14:26:21 -0400198 uint16_t Opcode;
199 uint32_t ResultID;
200 SmallVector<SPIRVOperand *, 4> Operands;
201};
202
203struct SPIRVProducerPass final : public ModulePass {
David Neto22f144c2017-06-12 14:26:21 -0400204 typedef DenseMap<Type *, uint32_t> TypeMapType;
205 typedef UniqueVector<Type *> TypeList;
206 typedef DenseMap<Value *, uint32_t> ValueMapType;
David Netofb9a7972017-08-25 17:08:24 -0400207 typedef UniqueVector<Value *> ValueList;
David Neto22f144c2017-06-12 14:26:21 -0400208 typedef std::vector<std::pair<Value *, uint32_t>> EntryPointVecType;
209 typedef std::list<SPIRVInstruction *> SPIRVInstructionList;
David Neto87846742018-04-11 17:36:22 -0400210 // A vector of tuples, each of which is:
211 // - the LLVM instruction that we will later generate SPIR-V code for
212 // - where the SPIR-V instruction should be inserted
213 // - the result ID of the SPIR-V instruction
David Neto22f144c2017-06-12 14:26:21 -0400214 typedef std::vector<
215 std::tuple<Value *, SPIRVInstructionList::iterator, uint32_t>>
216 DeferredInstVecType;
217 typedef DenseMap<FunctionType *, std::pair<FunctionType *, uint32_t>>
218 GlobalConstFuncMapType;
219
David Neto44795152017-07-13 15:45:28 -0400220 explicit SPIRVProducerPass(
alan-bakerf5e5f692018-11-27 08:33:24 -0500221 raw_pwrite_stream &out,
222 std::vector<clspv::version0::DescriptorMapEntry> *descriptor_map_entries,
David Neto44795152017-07-13 15:45:28 -0400223 ArrayRef<std::pair<unsigned, std::string>> samplerMap, bool outputAsm,
224 bool outputCInitList)
David Netoc2c368d2017-06-30 16:50:17 -0400225 : ModulePass(ID), samplerMap(samplerMap), out(out),
David Neto0676e6f2017-07-11 18:47:44 -0400226 binaryTempOut(binaryTempUnderlyingVector), binaryOut(&out),
alan-bakerf5e5f692018-11-27 08:33:24 -0500227 descriptorMapEntries(descriptor_map_entries), outputAsm(outputAsm),
David Neto0676e6f2017-07-11 18:47:44 -0400228 outputCInitList(outputCInitList), patchBoundOffset(0), nextID(1),
alan-baker5b86ed72019-02-15 08:26:50 -0500229 OpExtInstImportID(0), HasVariablePointersStorageBuffer(false),
230 HasVariablePointers(false), SamplerTy(nullptr), WorkgroupSizeValueID(0),
231 WorkgroupSizeVarID(0), max_local_spec_id_(0), constant_i32_zero_id_(0) {
232 }
David Neto22f144c2017-06-12 14:26:21 -0400233
234 void getAnalysisUsage(AnalysisUsage &AU) const override {
235 AU.addRequired<DominatorTreeWrapperPass>();
236 AU.addRequired<LoopInfoWrapperPass>();
237 }
238
239 virtual bool runOnModule(Module &module) override;
240
241 // output the SPIR-V header block
242 void outputHeader();
243
244 // patch the SPIR-V header block
245 void patchHeader();
246
247 uint32_t lookupType(Type *Ty) {
248 if (Ty->isPointerTy() &&
249 (Ty->getPointerAddressSpace() != AddressSpace::UniformConstant)) {
250 auto PointeeTy = Ty->getPointerElementType();
251 if (PointeeTy->isStructTy() &&
252 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
253 Ty = PointeeTy;
254 }
255 }
256
David Neto862b7d82018-06-14 18:48:37 -0400257 auto where = TypeMap.find(Ty);
258 if (where == TypeMap.end()) {
259 if (Ty) {
260 errs() << "Unhandled type " << *Ty << "\n";
261 } else {
262 errs() << "Unhandled type (null)\n";
263 }
David Netoe439d702018-03-23 13:14:08 -0700264 llvm_unreachable("\nUnhandled type!");
David Neto22f144c2017-06-12 14:26:21 -0400265 }
266
David Neto862b7d82018-06-14 18:48:37 -0400267 return where->second;
David Neto22f144c2017-06-12 14:26:21 -0400268 }
269 TypeMapType &getImageTypeMap() { return ImageTypeMap; }
270 TypeList &getTypeList() { return Types; };
271 ValueList &getConstantList() { return Constants; };
272 ValueMapType &getValueMap() { return ValueMap; }
273 ValueMapType &getAllocatedValueMap() { return AllocatedValueMap; }
274 SPIRVInstructionList &getSPIRVInstList() { return SPIRVInsts; };
David Neto22f144c2017-06-12 14:26:21 -0400275 EntryPointVecType &getEntryPointVec() { return EntryPointVec; };
276 DeferredInstVecType &getDeferredInstVec() { return DeferredInstVec; };
277 ValueList &getEntryPointInterfacesVec() { return EntryPointInterfacesVec; };
278 uint32_t &getOpExtInstImportID() { return OpExtInstImportID; };
279 std::vector<uint32_t> &getBuiltinDimVec() { return BuiltinDimensionVec; };
alan-baker5b86ed72019-02-15 08:26:50 -0500280 bool hasVariablePointersStorageBuffer() {
281 return HasVariablePointersStorageBuffer;
282 }
283 void setVariablePointersStorageBuffer(bool Val) {
284 HasVariablePointersStorageBuffer = Val;
285 }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500286 bool hasVariablePointers() {
alan-baker5b86ed72019-02-15 08:26:50 -0500287 return HasVariablePointers;
alan-bakerb6b09dc2018-11-08 16:59:28 -0500288 };
David Neto22f144c2017-06-12 14:26:21 -0400289 void setVariablePointers(bool Val) { HasVariablePointers = Val; };
alan-bakerb6b09dc2018-11-08 16:59:28 -0500290 ArrayRef<std::pair<unsigned, std::string>> &getSamplerMap() {
291 return samplerMap;
292 }
David Neto22f144c2017-06-12 14:26:21 -0400293 GlobalConstFuncMapType &getGlobalConstFuncTypeMap() {
294 return GlobalConstFuncTypeMap;
295 }
296 SmallPtrSet<Value *, 16> &getGlobalConstArgSet() {
297 return GlobalConstArgumentSet;
298 }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500299 TypeList &getTypesNeedingArrayStride() { return TypesNeedingArrayStride; }
David Neto22f144c2017-06-12 14:26:21 -0400300
David Netoc6f3ab22018-04-06 18:02:31 -0400301 void GenerateLLVMIRInfo(Module &M, const DataLayout &DL);
alan-bakerb6b09dc2018-11-08 16:59:28 -0500302 // Populate GlobalConstFuncTypeMap. Also, if module-scope __constant will
303 // *not* be converted to a storage buffer, replace each such global variable
304 // with one in the storage class expecgted by SPIR-V.
David Neto862b7d82018-06-14 18:48:37 -0400305 void FindGlobalConstVars(Module &M, const DataLayout &DL);
306 // Populate ResourceVarInfoList, FunctionToResourceVarsMap, and
307 // ModuleOrderedResourceVars.
308 void FindResourceVars(Module &M, const DataLayout &DL);
Alan Baker202c8c72018-08-13 13:47:44 -0400309 void FindWorkgroupVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400310 bool FindExtInst(Module &M);
311 void FindTypePerGlobalVar(GlobalVariable &GV);
312 void FindTypePerFunc(Function &F);
David Neto862b7d82018-06-14 18:48:37 -0400313 void FindTypesForSamplerMap(Module &M);
314 void FindTypesForResourceVars(Module &M);
alan-bakerb6b09dc2018-11-08 16:59:28 -0500315 // Inserts |Ty| and relevant sub-types into the |Types| member, indicating
316 // that |Ty| and its subtypes will need a corresponding SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400317 void FindType(Type *Ty);
318 void FindConstantPerGlobalVar(GlobalVariable &GV);
319 void FindConstantPerFunc(Function &F);
320 void FindConstant(Value *V);
321 void GenerateExtInstImport();
David Neto19a1bad2017-08-25 15:01:41 -0400322 // Generates instructions for SPIR-V types corresponding to the LLVM types
323 // saved in the |Types| member. A type follows its subtypes. IDs are
324 // allocated sequentially starting with the current value of nextID, and
325 // with a type following its subtypes. Also updates nextID to just beyond
326 // the last generated ID.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500327 void GenerateSPIRVTypes(LLVMContext &context, Module &module);
David Neto22f144c2017-06-12 14:26:21 -0400328 void GenerateSPIRVConstants();
David Neto5c22a252018-03-15 16:07:41 -0400329 void GenerateModuleInfo(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400330 void GenerateGlobalVar(GlobalVariable &GV);
David Netoc6f3ab22018-04-06 18:02:31 -0400331 void GenerateWorkgroupVars();
David Neto862b7d82018-06-14 18:48:37 -0400332 // Generate descriptor map entries for resource variables associated with
333 // arguments to F.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500334 void GenerateDescriptorMapInfo(const DataLayout &DL, Function &F);
David Neto22f144c2017-06-12 14:26:21 -0400335 void GenerateSamplers(Module &M);
David Neto862b7d82018-06-14 18:48:37 -0400336 // Generate OpVariables for %clspv.resource.var.* calls.
337 void GenerateResourceVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400338 void GenerateFuncPrologue(Function &F);
339 void GenerateFuncBody(Function &F);
David Netob6e2e062018-04-25 10:32:06 -0400340 void GenerateEntryPointInitialStores();
David Neto22f144c2017-06-12 14:26:21 -0400341 spv::Op GetSPIRVCmpOpcode(CmpInst *CmpI);
342 spv::Op GetSPIRVCastOpcode(Instruction &I);
343 spv::Op GetSPIRVBinaryOpcode(Instruction &I);
344 void GenerateInstruction(Instruction &I);
345 void GenerateFuncEpilogue();
346 void HandleDeferredInstruction();
alan-bakerb6b09dc2018-11-08 16:59:28 -0500347 void HandleDeferredDecorations(const DataLayout &DL);
David Neto22f144c2017-06-12 14:26:21 -0400348 bool is4xi8vec(Type *Ty) const;
David Neto257c3892018-04-11 13:19:45 -0400349 // Return the SPIR-V Id for 32-bit constant zero. The constant must already
350 // have been created.
351 uint32_t GetI32Zero();
David Neto22f144c2017-06-12 14:26:21 -0400352 spv::StorageClass GetStorageClass(unsigned AddrSpace) const;
David Neto862b7d82018-06-14 18:48:37 -0400353 spv::StorageClass GetStorageClassForArgKind(clspv::ArgKind arg_kind) const;
David Neto22f144c2017-06-12 14:26:21 -0400354 spv::BuiltIn GetBuiltin(StringRef globalVarName) const;
David Neto3fbb4072017-10-16 11:28:14 -0400355 // Returns the GLSL extended instruction enum that the given function
356 // call maps to. If none, then returns the 0 value, i.e. GLSLstd4580Bad.
David Neto22f144c2017-06-12 14:26:21 -0400357 glsl::ExtInst getExtInstEnum(StringRef Name);
David Neto3fbb4072017-10-16 11:28:14 -0400358 // Returns the GLSL extended instruction enum indirectly used by the given
359 // function. That is, to implement the given function, we use an extended
360 // instruction plus one more instruction. If none, then returns the 0 value,
361 // i.e. GLSLstd4580Bad.
362 glsl::ExtInst getIndirectExtInstEnum(StringRef Name);
363 // Returns the single GLSL extended instruction used directly or
364 // indirectly by the given function call.
365 glsl::ExtInst getDirectOrIndirectExtInstEnum(StringRef Name);
David Neto22f144c2017-06-12 14:26:21 -0400366 void PrintResID(SPIRVInstruction *Inst);
367 void PrintOpcode(SPIRVInstruction *Inst);
368 void PrintOperand(SPIRVOperand *Op);
369 void PrintCapability(SPIRVOperand *Op);
370 void PrintExtInst(SPIRVOperand *Op);
371 void PrintAddrModel(SPIRVOperand *Op);
372 void PrintMemModel(SPIRVOperand *Op);
373 void PrintExecModel(SPIRVOperand *Op);
374 void PrintExecMode(SPIRVOperand *Op);
375 void PrintSourceLanguage(SPIRVOperand *Op);
376 void PrintFuncCtrl(SPIRVOperand *Op);
377 void PrintStorageClass(SPIRVOperand *Op);
378 void PrintDecoration(SPIRVOperand *Op);
379 void PrintBuiltIn(SPIRVOperand *Op);
380 void PrintSelectionControl(SPIRVOperand *Op);
381 void PrintLoopControl(SPIRVOperand *Op);
382 void PrintDimensionality(SPIRVOperand *Op);
383 void PrintImageFormat(SPIRVOperand *Op);
384 void PrintMemoryAccess(SPIRVOperand *Op);
385 void PrintImageOperandsType(SPIRVOperand *Op);
386 void WriteSPIRVAssembly();
387 void WriteOneWord(uint32_t Word);
388 void WriteResultID(SPIRVInstruction *Inst);
389 void WriteWordCountAndOpcode(SPIRVInstruction *Inst);
390 void WriteOperand(SPIRVOperand *Op);
391 void WriteSPIRVBinary();
392
Alan Baker9bf93fb2018-08-28 16:59:26 -0400393 // Returns true if |type| is compatible with OpConstantNull.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500394 bool IsTypeNullable(const Type *type) const;
Alan Baker9bf93fb2018-08-28 16:59:26 -0400395
Alan Bakerfcda9482018-10-02 17:09:59 -0400396 // Populate UBO remapped type maps.
397 void PopulateUBOTypeMaps(Module &module);
398
399 // Wrapped methods of DataLayout accessors. If |type| was remapped for UBOs,
400 // uses the internal map, otherwise it falls back on the data layout.
401 uint64_t GetTypeSizeInBits(Type *type, const DataLayout &DL);
402 uint64_t GetTypeStoreSize(Type *type, const DataLayout &DL);
403 uint64_t GetTypeAllocSize(Type *type, const DataLayout &DL);
404
alan-baker5b86ed72019-02-15 08:26:50 -0500405 // Returns the base pointer of |v|.
406 Value *GetBasePointer(Value *v);
407
408 // Sets |HasVariablePointersStorageBuffer| or |HasVariablePointers| base on
409 // |address_space|.
410 void setVariablePointersCapabilities(unsigned address_space);
411
412 // Returns true if |lhs| and |rhs| represent the same resource or workgroup
413 // variable.
414 bool sameResource(Value *lhs, Value *rhs) const;
415
416 // Returns true if |inst| is phi or select that selects from the same
417 // structure (or null).
418 bool selectFromSameObject(Instruction *inst);
419
alan-bakere9308012019-03-15 10:25:13 -0400420 // Returns true if |Arg| is called with a coherent resource.
421 bool CalledWithCoherentResource(Argument &Arg);
422
David Neto22f144c2017-06-12 14:26:21 -0400423private:
424 static char ID;
David Neto44795152017-07-13 15:45:28 -0400425 ArrayRef<std::pair<unsigned, std::string>> samplerMap;
David Neto22f144c2017-06-12 14:26:21 -0400426 raw_pwrite_stream &out;
David Neto0676e6f2017-07-11 18:47:44 -0400427
428 // TODO(dneto): Wouldn't it be better to always just emit a binary, and then
429 // convert to other formats on demand?
430
431 // When emitting a C initialization list, the WriteSPIRVBinary method
432 // will actually write its words to this vector via binaryTempOut.
433 SmallVector<char, 100> binaryTempUnderlyingVector;
434 raw_svector_ostream binaryTempOut;
435
436 // Binary output writes to this stream, which might be |out| or
437 // |binaryTempOut|. It's the latter when we really want to write a C
438 // initializer list.
alan-bakerf5e5f692018-11-27 08:33:24 -0500439 raw_pwrite_stream* binaryOut;
440 std::vector<version0::DescriptorMapEntry> *descriptorMapEntries;
David Neto22f144c2017-06-12 14:26:21 -0400441 const bool outputAsm;
David Neto0676e6f2017-07-11 18:47:44 -0400442 const bool outputCInitList; // If true, output look like {0x7023, ... , 5}
David Neto22f144c2017-06-12 14:26:21 -0400443 uint64_t patchBoundOffset;
444 uint32_t nextID;
445
David Neto19a1bad2017-08-25 15:01:41 -0400446 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400447 TypeMapType TypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400448 // Maps an LLVM image type to its SPIR-V ID.
David Neto22f144c2017-06-12 14:26:21 -0400449 TypeMapType ImageTypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400450 // A unique-vector of LLVM types that map to a SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400451 TypeList Types;
452 ValueList Constants;
David Neto19a1bad2017-08-25 15:01:41 -0400453 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400454 ValueMapType ValueMap;
455 ValueMapType AllocatedValueMap;
456 SPIRVInstructionList SPIRVInsts;
David Neto862b7d82018-06-14 18:48:37 -0400457
David Neto22f144c2017-06-12 14:26:21 -0400458 EntryPointVecType EntryPointVec;
459 DeferredInstVecType DeferredInstVec;
460 ValueList EntryPointInterfacesVec;
461 uint32_t OpExtInstImportID;
462 std::vector<uint32_t> BuiltinDimensionVec;
alan-baker5b86ed72019-02-15 08:26:50 -0500463 bool HasVariablePointersStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -0400464 bool HasVariablePointers;
465 Type *SamplerTy;
alan-bakerb6b09dc2018-11-08 16:59:28 -0500466 DenseMap<unsigned, uint32_t> SamplerMapIndexToIDMap;
David Netoc77d9e22018-03-24 06:30:28 -0700467
468 // If a function F has a pointer-to-__constant parameter, then this variable
David Neto9ed8e2f2018-03-24 06:47:24 -0700469 // will map F's type to (G, index of the parameter), where in a first phase
470 // G is F's type. During FindTypePerFunc, G will be changed to F's type
471 // but replacing the pointer-to-constant parameter with
472 // pointer-to-ModuleScopePrivate.
David Netoc77d9e22018-03-24 06:30:28 -0700473 // TODO(dneto): This doesn't seem general enough? A function might have
474 // more than one such parameter.
David Neto22f144c2017-06-12 14:26:21 -0400475 GlobalConstFuncMapType GlobalConstFuncTypeMap;
476 SmallPtrSet<Value *, 16> GlobalConstArgumentSet;
David Neto1a1a0582017-07-07 12:01:44 -0400477 // An ordered set of pointer types of Base arguments to OpPtrAccessChain,
David Neto85082642018-03-24 06:55:20 -0700478 // or array types, and which point into transparent memory (StorageBuffer
479 // storage class). These will require an ArrayStride decoration.
David Neto1a1a0582017-07-07 12:01:44 -0400480 // See SPV_KHR_variable_pointers rev 13.
David Neto85082642018-03-24 06:55:20 -0700481 TypeList TypesNeedingArrayStride;
David Netoa60b00b2017-09-15 16:34:09 -0400482
483 // This is truly ugly, but works around what look like driver bugs.
484 // For get_local_size, an earlier part of the flow has created a module-scope
485 // variable in Private address space to hold the value for the workgroup
486 // size. Its intializer is a uint3 value marked as builtin WorkgroupSize.
487 // When this is present, save the IDs of the initializer value and variable
488 // in these two variables. We only ever do a vector load from it, and
489 // when we see one of those, substitute just the value of the intializer.
490 // This mimics what Glslang does, and that's what drivers are used to.
David Neto66cfe642018-03-24 06:13:56 -0700491 // TODO(dneto): Remove this once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -0400492 uint32_t WorkgroupSizeValueID;
493 uint32_t WorkgroupSizeVarID;
David Neto26aaf622017-10-23 18:11:53 -0400494
David Neto862b7d82018-06-14 18:48:37 -0400495 // Bookkeeping for mapping kernel arguments to resource variables.
496 struct ResourceVarInfo {
497 ResourceVarInfo(int index_arg, unsigned set_arg, unsigned binding_arg,
alan-bakere9308012019-03-15 10:25:13 -0400498 Function *fn, clspv::ArgKind arg_kind_arg, int coherent_arg)
David Neto862b7d82018-06-14 18:48:37 -0400499 : index(index_arg), descriptor_set(set_arg), binding(binding_arg),
alan-bakere9308012019-03-15 10:25:13 -0400500 var_fn(fn), arg_kind(arg_kind_arg), coherent(coherent_arg),
David Neto862b7d82018-06-14 18:48:37 -0400501 addr_space(fn->getReturnType()->getPointerAddressSpace()) {}
502 const int index; // Index into ResourceVarInfoList
503 const unsigned descriptor_set;
504 const unsigned binding;
505 Function *const var_fn; // The @clspv.resource.var.* function.
506 const clspv::ArgKind arg_kind;
alan-bakere9308012019-03-15 10:25:13 -0400507 const int coherent;
David Neto862b7d82018-06-14 18:48:37 -0400508 const unsigned addr_space; // The LLVM address space
509 // The SPIR-V ID of the OpVariable. Not populated at construction time.
510 uint32_t var_id = 0;
511 };
512 // A list of resource var info. Each one correponds to a module-scope
513 // resource variable we will have to create. Resource var indices are
514 // indices into this vector.
515 SmallVector<std::unique_ptr<ResourceVarInfo>, 8> ResourceVarInfoList;
516 // This is a vector of pointers of all the resource vars, but ordered by
517 // kernel function, and then by argument.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500518 UniqueVector<ResourceVarInfo *> ModuleOrderedResourceVars;
David Neto862b7d82018-06-14 18:48:37 -0400519 // Map a function to the ordered list of resource variables it uses, one for
520 // each argument. If an argument does not use a resource variable, it
521 // will have a null pointer entry.
522 using FunctionToResourceVarsMapType =
523 DenseMap<Function *, SmallVector<ResourceVarInfo *, 8>>;
524 FunctionToResourceVarsMapType FunctionToResourceVarsMap;
525
526 // What LLVM types map to SPIR-V types needing layout? These are the
527 // arrays and structures supporting storage buffers and uniform buffers.
528 TypeList TypesNeedingLayout;
529 // What LLVM struct types map to a SPIR-V struct type with Block decoration?
530 UniqueVector<StructType *> StructTypesNeedingBlock;
531 // For a call that represents a load from an opaque type (samplers, images),
532 // map it to the variable id it should load from.
533 DenseMap<CallInst *, uint32_t> ResourceVarDeferredLoadCalls;
David Neto85082642018-03-24 06:55:20 -0700534
Alan Baker202c8c72018-08-13 13:47:44 -0400535 // One larger than the maximum used SpecId for pointer-to-local arguments.
536 int max_local_spec_id_;
David Netoc6f3ab22018-04-06 18:02:31 -0400537 // An ordered list of the kernel arguments of type pointer-to-local.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500538 using LocalArgList = SmallVector<Argument *, 8>;
David Netoc6f3ab22018-04-06 18:02:31 -0400539 LocalArgList LocalArgs;
540 // Information about a pointer-to-local argument.
541 struct LocalArgInfo {
542 // The SPIR-V ID of the array variable.
543 uint32_t variable_id;
544 // The element type of the
alan-bakerb6b09dc2018-11-08 16:59:28 -0500545 Type *elem_type;
David Netoc6f3ab22018-04-06 18:02:31 -0400546 // The ID of the array type.
547 uint32_t array_size_id;
548 // The ID of the array type.
549 uint32_t array_type_id;
550 // The ID of the pointer to the array type.
551 uint32_t ptr_array_type_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400552 // The specialization constant ID of the array size.
553 int spec_id;
554 };
Alan Baker202c8c72018-08-13 13:47:44 -0400555 // A mapping from Argument to its assigned SpecId.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500556 DenseMap<const Argument *, int> LocalArgSpecIds;
Alan Baker202c8c72018-08-13 13:47:44 -0400557 // A mapping from SpecId to its LocalArgInfo.
558 DenseMap<int, LocalArgInfo> LocalSpecIdInfoMap;
Alan Bakerfcda9482018-10-02 17:09:59 -0400559 // A mapping from a remapped type to its real offsets.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500560 DenseMap<Type *, std::vector<uint32_t>> RemappedUBOTypeOffsets;
Alan Bakerfcda9482018-10-02 17:09:59 -0400561 // A mapping from a remapped type to its real sizes.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500562 DenseMap<Type *, std::tuple<uint64_t, uint64_t, uint64_t>>
563 RemappedUBOTypeSizes;
David Neto257c3892018-04-11 13:19:45 -0400564
565 // The ID of 32-bit integer zero constant. This is only valid after
566 // GenerateSPIRVConstants has run.
567 uint32_t constant_i32_zero_id_;
David Neto22f144c2017-06-12 14:26:21 -0400568};
569
570char SPIRVProducerPass::ID;
David Netoc6f3ab22018-04-06 18:02:31 -0400571
alan-bakerb6b09dc2018-11-08 16:59:28 -0500572} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400573
574namespace clspv {
alan-bakerf5e5f692018-11-27 08:33:24 -0500575ModulePass *createSPIRVProducerPass(
576 raw_pwrite_stream &out,
577 std::vector<version0::DescriptorMapEntry> *descriptor_map_entries,
578 ArrayRef<std::pair<unsigned, std::string>> samplerMap, bool outputAsm,
579 bool outputCInitList) {
580 return new SPIRVProducerPass(out, descriptor_map_entries, samplerMap,
581 outputAsm, outputCInitList);
David Neto22f144c2017-06-12 14:26:21 -0400582}
David Netoc2c368d2017-06-30 16:50:17 -0400583} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400584
585bool SPIRVProducerPass::runOnModule(Module &module) {
David Neto0676e6f2017-07-11 18:47:44 -0400586 binaryOut = outputCInitList ? &binaryTempOut : &out;
587
David Neto257c3892018-04-11 13:19:45 -0400588 constant_i32_zero_id_ = 0; // Reset, for the benefit of validity checks.
589
Alan Bakerfcda9482018-10-02 17:09:59 -0400590 PopulateUBOTypeMaps(module);
591
David Neto22f144c2017-06-12 14:26:21 -0400592 // SPIR-V always begins with its header information
593 outputHeader();
594
David Netoc6f3ab22018-04-06 18:02:31 -0400595 const DataLayout &DL = module.getDataLayout();
596
David Neto22f144c2017-06-12 14:26:21 -0400597 // Gather information from the LLVM IR that we require.
David Netoc6f3ab22018-04-06 18:02:31 -0400598 GenerateLLVMIRInfo(module, DL);
David Neto22f144c2017-06-12 14:26:21 -0400599
David Neto22f144c2017-06-12 14:26:21 -0400600 // Collect information on global variables too.
601 for (GlobalVariable &GV : module.globals()) {
602 // If the GV is one of our special __spirv_* variables, remove the
603 // initializer as it was only placed there to force LLVM to not throw the
604 // value away.
605 if (GV.getName().startswith("__spirv_")) {
606 GV.setInitializer(nullptr);
607 }
608
609 // Collect types' information from global variable.
610 FindTypePerGlobalVar(GV);
611
612 // Collect constant information from global variable.
613 FindConstantPerGlobalVar(GV);
614
615 // If the variable is an input, entry points need to know about it.
616 if (AddressSpace::Input == GV.getType()->getPointerAddressSpace()) {
David Netofb9a7972017-08-25 17:08:24 -0400617 getEntryPointInterfacesVec().insert(&GV);
David Neto22f144c2017-06-12 14:26:21 -0400618 }
619 }
620
621 // If there are extended instructions, generate OpExtInstImport.
622 if (FindExtInst(module)) {
623 GenerateExtInstImport();
624 }
625
626 // Generate SPIRV instructions for types.
Alan Bakerfcda9482018-10-02 17:09:59 -0400627 GenerateSPIRVTypes(module.getContext(), module);
David Neto22f144c2017-06-12 14:26:21 -0400628
629 // Generate SPIRV constants.
630 GenerateSPIRVConstants();
631
632 // If we have a sampler map, we might have literal samplers to generate.
633 if (0 < getSamplerMap().size()) {
634 GenerateSamplers(module);
635 }
636
637 // Generate SPIRV variables.
638 for (GlobalVariable &GV : module.globals()) {
639 GenerateGlobalVar(GV);
640 }
David Neto862b7d82018-06-14 18:48:37 -0400641 GenerateResourceVars(module);
David Netoc6f3ab22018-04-06 18:02:31 -0400642 GenerateWorkgroupVars();
David Neto22f144c2017-06-12 14:26:21 -0400643
644 // Generate SPIRV instructions for each function.
645 for (Function &F : module) {
646 if (F.isDeclaration()) {
647 continue;
648 }
649
David Neto862b7d82018-06-14 18:48:37 -0400650 GenerateDescriptorMapInfo(DL, F);
651
David Neto22f144c2017-06-12 14:26:21 -0400652 // Generate Function Prologue.
653 GenerateFuncPrologue(F);
654
655 // Generate SPIRV instructions for function body.
656 GenerateFuncBody(F);
657
658 // Generate Function Epilogue.
659 GenerateFuncEpilogue();
660 }
661
662 HandleDeferredInstruction();
David Neto1a1a0582017-07-07 12:01:44 -0400663 HandleDeferredDecorations(DL);
David Neto22f144c2017-06-12 14:26:21 -0400664
665 // Generate SPIRV module information.
David Neto5c22a252018-03-15 16:07:41 -0400666 GenerateModuleInfo(module);
David Neto22f144c2017-06-12 14:26:21 -0400667
668 if (outputAsm) {
669 WriteSPIRVAssembly();
670 } else {
671 WriteSPIRVBinary();
672 }
673
674 // We need to patch the SPIR-V header to set bound correctly.
675 patchHeader();
David Neto0676e6f2017-07-11 18:47:44 -0400676
677 if (outputCInitList) {
678 bool first = true;
David Neto0676e6f2017-07-11 18:47:44 -0400679 std::ostringstream os;
680
David Neto57fb0b92017-08-04 15:35:09 -0400681 auto emit_word = [&os, &first](uint32_t word) {
David Neto0676e6f2017-07-11 18:47:44 -0400682 if (!first)
David Neto57fb0b92017-08-04 15:35:09 -0400683 os << ",\n";
684 os << word;
David Neto0676e6f2017-07-11 18:47:44 -0400685 first = false;
686 };
687
688 os << "{";
David Neto57fb0b92017-08-04 15:35:09 -0400689 const std::string str(binaryTempOut.str());
690 for (unsigned i = 0; i < str.size(); i += 4) {
691 const uint32_t a = static_cast<unsigned char>(str[i]);
692 const uint32_t b = static_cast<unsigned char>(str[i + 1]);
693 const uint32_t c = static_cast<unsigned char>(str[i + 2]);
694 const uint32_t d = static_cast<unsigned char>(str[i + 3]);
695 emit_word(a | (b << 8) | (c << 16) | (d << 24));
David Neto0676e6f2017-07-11 18:47:44 -0400696 }
697 os << "}\n";
698 out << os.str();
699 }
700
David Neto22f144c2017-06-12 14:26:21 -0400701 return false;
702}
703
704void SPIRVProducerPass::outputHeader() {
705 if (outputAsm) {
706 // for ASM output the header goes into 5 comments at the beginning of the
707 // file
708 out << "; SPIR-V\n";
709
710 // the major version number is in the 2nd highest byte
711 const uint32_t major = (spv::Version >> 16) & 0xFF;
712
713 // the minor version number is in the 2nd lowest byte
714 const uint32_t minor = (spv::Version >> 8) & 0xFF;
715 out << "; Version: " << major << "." << minor << "\n";
716
717 // use Codeplay's vendor ID
718 out << "; Generator: Codeplay; 0\n";
719
720 out << "; Bound: ";
721
722 // we record where we need to come back to and patch in the bound value
723 patchBoundOffset = out.tell();
724
725 // output one space per digit for the max size of a 32 bit unsigned integer
726 // (which is the maximum ID we could possibly be using)
727 for (uint32_t i = std::numeric_limits<uint32_t>::max(); 0 != i; i /= 10) {
728 out << " ";
729 }
730
731 out << "\n";
732
733 out << "; Schema: 0\n";
734 } else {
David Neto0676e6f2017-07-11 18:47:44 -0400735 binaryOut->write(reinterpret_cast<const char *>(&spv::MagicNumber),
alan-bakerb6b09dc2018-11-08 16:59:28 -0500736 sizeof(spv::MagicNumber));
David Neto0676e6f2017-07-11 18:47:44 -0400737 binaryOut->write(reinterpret_cast<const char *>(&spv::Version),
alan-bakerb6b09dc2018-11-08 16:59:28 -0500738 sizeof(spv::Version));
David Neto22f144c2017-06-12 14:26:21 -0400739
740 // use Codeplay's vendor ID
741 const uint32_t vendor = 3 << 16;
David Neto0676e6f2017-07-11 18:47:44 -0400742 binaryOut->write(reinterpret_cast<const char *>(&vendor), sizeof(vendor));
David Neto22f144c2017-06-12 14:26:21 -0400743
744 // we record where we need to come back to and patch in the bound value
David Neto0676e6f2017-07-11 18:47:44 -0400745 patchBoundOffset = binaryOut->tell();
David Neto22f144c2017-06-12 14:26:21 -0400746
747 // output a bad bound for now
David Neto0676e6f2017-07-11 18:47:44 -0400748 binaryOut->write(reinterpret_cast<const char *>(&nextID), sizeof(nextID));
David Neto22f144c2017-06-12 14:26:21 -0400749
750 // output the schema (reserved for use and must be 0)
751 const uint32_t schema = 0;
David Neto0676e6f2017-07-11 18:47:44 -0400752 binaryOut->write(reinterpret_cast<const char *>(&schema), sizeof(schema));
David Neto22f144c2017-06-12 14:26:21 -0400753 }
754}
755
756void SPIRVProducerPass::patchHeader() {
757 if (outputAsm) {
758 // get the string representation of the max bound used (nextID will be the
759 // max ID used)
760 auto asString = std::to_string(nextID);
761 out.pwrite(asString.c_str(), asString.size(), patchBoundOffset);
762 } else {
763 // for a binary we just write the value of nextID over bound
David Neto0676e6f2017-07-11 18:47:44 -0400764 binaryOut->pwrite(reinterpret_cast<char *>(&nextID), sizeof(nextID),
765 patchBoundOffset);
David Neto22f144c2017-06-12 14:26:21 -0400766 }
767}
768
David Netoc6f3ab22018-04-06 18:02:31 -0400769void SPIRVProducerPass::GenerateLLVMIRInfo(Module &M, const DataLayout &DL) {
David Neto22f144c2017-06-12 14:26:21 -0400770 // This function generates LLVM IR for function such as global variable for
771 // argument, constant and pointer type for argument access. These information
772 // is artificial one because we need Vulkan SPIR-V output. This function is
773 // executed ahead of FindType and FindConstant.
David Neto22f144c2017-06-12 14:26:21 -0400774 LLVMContext &Context = M.getContext();
775
David Neto862b7d82018-06-14 18:48:37 -0400776 FindGlobalConstVars(M, DL);
David Neto5c22a252018-03-15 16:07:41 -0400777
David Neto862b7d82018-06-14 18:48:37 -0400778 FindResourceVars(M, DL);
David Neto22f144c2017-06-12 14:26:21 -0400779
780 bool HasWorkGroupBuiltin = false;
781 for (GlobalVariable &GV : M.globals()) {
782 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
783 if (spv::BuiltInWorkgroupSize == BuiltinType) {
784 HasWorkGroupBuiltin = true;
785 }
786 }
787
David Neto862b7d82018-06-14 18:48:37 -0400788 FindTypesForSamplerMap(M);
789 FindTypesForResourceVars(M);
Alan Baker202c8c72018-08-13 13:47:44 -0400790 FindWorkgroupVars(M);
David Neto22f144c2017-06-12 14:26:21 -0400791
David Neto862b7d82018-06-14 18:48:37 -0400792 // These function calls need a <2 x i32> as an intermediate result but not
793 // the final result.
794 std::unordered_set<std::string> NeedsIVec2{
795 "_Z15get_image_width14ocl_image2d_ro",
796 "_Z15get_image_width14ocl_image2d_wo",
797 "_Z16get_image_height14ocl_image2d_ro",
798 "_Z16get_image_height14ocl_image2d_wo",
799 };
800
David Neto22f144c2017-06-12 14:26:21 -0400801 for (Function &F : M) {
Kévin Petitabef4522019-03-27 13:08:01 +0000802 if (F.isDeclaration()) {
David Neto22f144c2017-06-12 14:26:21 -0400803 continue;
804 }
805
806 for (BasicBlock &BB : F) {
807 for (Instruction &I : BB) {
808 if (I.getOpcode() == Instruction::ZExt ||
809 I.getOpcode() == Instruction::SExt ||
810 I.getOpcode() == Instruction::UIToFP) {
811 // If there is zext with i1 type, it will be changed to OpSelect. The
812 // OpSelect needs constant 0 and 1 so the constants are added here.
813
814 auto OpTy = I.getOperand(0)->getType();
815
Kévin Petit24272b62018-10-18 19:16:12 +0000816 if (OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -0400817 if (I.getOpcode() == Instruction::ZExt) {
David Neto22f144c2017-06-12 14:26:21 -0400818 FindConstant(Constant::getNullValue(I.getType()));
Kévin Petit7bfb8992019-02-26 13:45:08 +0000819 FindConstant(ConstantInt::get(I.getType(), 1));
David Neto22f144c2017-06-12 14:26:21 -0400820 } else if (I.getOpcode() == Instruction::SExt) {
David Neto22f144c2017-06-12 14:26:21 -0400821 FindConstant(Constant::getNullValue(I.getType()));
Kévin Petit7bfb8992019-02-26 13:45:08 +0000822 FindConstant(ConstantInt::getSigned(I.getType(), -1));
David Neto22f144c2017-06-12 14:26:21 -0400823 } else {
824 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
825 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
826 }
827 }
828 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
David Neto862b7d82018-06-14 18:48:37 -0400829 StringRef callee_name = Call->getCalledFunction()->getName();
David Neto22f144c2017-06-12 14:26:21 -0400830
831 // Handle image type specially.
David Neto862b7d82018-06-14 18:48:37 -0400832 if (callee_name.equals(
David Neto22f144c2017-06-12 14:26:21 -0400833 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
David Neto862b7d82018-06-14 18:48:37 -0400834 callee_name.equals(
David Neto22f144c2017-06-12 14:26:21 -0400835 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
836 TypeMapType &OpImageTypeMap = getImageTypeMap();
837 Type *ImageTy =
838 Call->getArgOperand(0)->getType()->getPointerElementType();
839 OpImageTypeMap[ImageTy] = 0;
840
841 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
842 }
David Neto5c22a252018-03-15 16:07:41 -0400843
David Neto862b7d82018-06-14 18:48:37 -0400844 if (NeedsIVec2.find(callee_name) != NeedsIVec2.end()) {
David Neto5c22a252018-03-15 16:07:41 -0400845 FindType(VectorType::get(Type::getInt32Ty(Context), 2));
846 }
David Neto22f144c2017-06-12 14:26:21 -0400847 }
848 }
849 }
850
Kévin Petitabef4522019-03-27 13:08:01 +0000851 // More things to do on kernel functions
852 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
853 if (const MDNode *MD =
854 dyn_cast<Function>(&F)->getMetadata("reqd_work_group_size")) {
855 // We generate constants if the WorkgroupSize builtin is being used.
856 if (HasWorkGroupBuiltin) {
857 // Collect constant information for work group size.
858 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(0)));
859 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(1)));
860 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(2)));
David Neto22f144c2017-06-12 14:26:21 -0400861 }
862 }
863 }
864
865 if (M.getTypeByName("opencl.image2d_ro_t") ||
866 M.getTypeByName("opencl.image2d_wo_t") ||
867 M.getTypeByName("opencl.image3d_ro_t") ||
868 M.getTypeByName("opencl.image3d_wo_t")) {
869 // Assume Image type's sampled type is float type.
870 FindType(Type::getFloatTy(Context));
871 }
872
873 // Collect types' information from function.
874 FindTypePerFunc(F);
875
876 // Collect constant information from function.
877 FindConstantPerFunc(F);
878 }
879}
880
David Neto862b7d82018-06-14 18:48:37 -0400881void SPIRVProducerPass::FindGlobalConstVars(Module &M, const DataLayout &DL) {
882 SmallVector<GlobalVariable *, 8> GVList;
883 SmallVector<GlobalVariable *, 8> DeadGVList;
884 for (GlobalVariable &GV : M.globals()) {
885 if (GV.getType()->getAddressSpace() == AddressSpace::Constant) {
886 if (GV.use_empty()) {
887 DeadGVList.push_back(&GV);
888 } else {
889 GVList.push_back(&GV);
890 }
891 }
892 }
893
894 // Remove dead global __constant variables.
895 for (auto GV : DeadGVList) {
896 GV->eraseFromParent();
897 }
898 DeadGVList.clear();
899
900 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
901 // For now, we only support a single storage buffer.
902 if (GVList.size() > 0) {
903 assert(GVList.size() == 1);
904 const auto *GV = GVList[0];
905 const auto constants_byte_size =
Alan Bakerfcda9482018-10-02 17:09:59 -0400906 (GetTypeSizeInBits(GV->getInitializer()->getType(), DL)) / 8;
David Neto862b7d82018-06-14 18:48:37 -0400907 const size_t kConstantMaxSize = 65536;
908 if (constants_byte_size > kConstantMaxSize) {
909 outs() << "Max __constant capacity of " << kConstantMaxSize
910 << " bytes exceeded: " << constants_byte_size << " bytes used\n";
911 llvm_unreachable("Max __constant capacity exceeded");
912 }
913 }
914 } else {
915 // Change global constant variable's address space to ModuleScopePrivate.
916 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
917 for (auto GV : GVList) {
918 // Create new gv with ModuleScopePrivate address space.
919 Type *NewGVTy = GV->getType()->getPointerElementType();
920 GlobalVariable *NewGV = new GlobalVariable(
921 M, NewGVTy, false, GV->getLinkage(), GV->getInitializer(), "",
922 nullptr, GV->getThreadLocalMode(), AddressSpace::ModuleScopePrivate);
923 NewGV->takeName(GV);
924
925 const SmallVector<User *, 8> GVUsers(GV->user_begin(), GV->user_end());
926 SmallVector<User *, 8> CandidateUsers;
927
928 auto record_called_function_type_as_user =
929 [&GlobalConstFuncTyMap](Value *gv, CallInst *call) {
930 // Find argument index.
931 unsigned index = 0;
932 for (unsigned i = 0; i < call->getNumArgOperands(); i++) {
933 if (gv == call->getOperand(i)) {
934 // TODO(dneto): Should we break here?
935 index = i;
936 }
937 }
938
939 // Record function type with global constant.
940 GlobalConstFuncTyMap[call->getFunctionType()] =
941 std::make_pair(call->getFunctionType(), index);
942 };
943
944 for (User *GVU : GVUsers) {
945 if (CallInst *Call = dyn_cast<CallInst>(GVU)) {
946 record_called_function_type_as_user(GV, Call);
947 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(GVU)) {
948 // Check GEP users.
949 for (User *GEPU : GEP->users()) {
950 if (CallInst *GEPCall = dyn_cast<CallInst>(GEPU)) {
951 record_called_function_type_as_user(GEP, GEPCall);
952 }
953 }
954 }
955
956 CandidateUsers.push_back(GVU);
957 }
958
959 for (User *U : CandidateUsers) {
960 // Update users of gv with new gv.
alan-bakered80f572019-02-11 17:28:26 -0500961 if (!isa<Constant>(U)) {
962 // #254: Can't change operands of a constant, but this shouldn't be
963 // something that sticks around in the module.
964 U->replaceUsesOfWith(GV, NewGV);
965 }
David Neto862b7d82018-06-14 18:48:37 -0400966 }
967
968 // Delete original gv.
969 GV->eraseFromParent();
970 }
971 }
972}
973
Radek Szymanskibe4b0c42018-10-04 22:20:53 +0100974void SPIRVProducerPass::FindResourceVars(Module &M, const DataLayout &) {
David Neto862b7d82018-06-14 18:48:37 -0400975 ResourceVarInfoList.clear();
976 FunctionToResourceVarsMap.clear();
977 ModuleOrderedResourceVars.reset();
978 // Normally, there is one resource variable per clspv.resource.var.*
979 // function, since that is unique'd by arg type and index. By design,
980 // we can share these resource variables across kernels because all
981 // kernels use the same descriptor set.
982 //
983 // But if the user requested distinct descriptor sets per kernel, then
984 // the descriptor allocator has made different (set,binding) pairs for
985 // the same (type,arg_index) pair. Since we can decorate a resource
986 // variable with only exactly one DescriptorSet and Binding, we are
987 // forced in this case to make distinct resource variables whenever
988 // the same clspv.reource.var.X function is seen with disintct
989 // (set,binding) values.
990 const bool always_distinct_sets =
991 clspv::Option::DistinctKernelDescriptorSets();
992 for (Function &F : M) {
993 // Rely on the fact the resource var functions have a stable ordering
994 // in the module.
Alan Baker202c8c72018-08-13 13:47:44 -0400995 if (F.getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -0400996 // Find all calls to this function with distinct set and binding pairs.
997 // Save them in ResourceVarInfoList.
998
999 // Determine uniqueness of the (set,binding) pairs only withing this
1000 // one resource-var builtin function.
1001 using SetAndBinding = std::pair<unsigned, unsigned>;
1002 // Maps set and binding to the resource var info.
1003 DenseMap<SetAndBinding, ResourceVarInfo *> set_and_binding_map;
1004 bool first_use = true;
1005 for (auto &U : F.uses()) {
1006 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
1007 const auto set = unsigned(
1008 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
1009 const auto binding = unsigned(
1010 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
1011 const auto arg_kind = clspv::ArgKind(
1012 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
1013 const auto arg_index = unsigned(
1014 dyn_cast<ConstantInt>(call->getArgOperand(3))->getZExtValue());
alan-bakere9308012019-03-15 10:25:13 -04001015 const auto coherent = unsigned(
1016 dyn_cast<ConstantInt>(call->getArgOperand(5))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04001017
1018 // Find or make the resource var info for this combination.
1019 ResourceVarInfo *rv = nullptr;
1020 if (always_distinct_sets) {
1021 // Make a new resource var any time we see a different
1022 // (set,binding) pair.
1023 SetAndBinding key{set, binding};
1024 auto where = set_and_binding_map.find(key);
1025 if (where == set_and_binding_map.end()) {
1026 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
alan-bakere9308012019-03-15 10:25:13 -04001027 binding, &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001028 ResourceVarInfoList.emplace_back(rv);
1029 set_and_binding_map[key] = rv;
1030 } else {
1031 rv = where->second;
1032 }
1033 } else {
1034 // The default is to make exactly one resource for each
1035 // clspv.resource.var.* function.
1036 if (first_use) {
1037 first_use = false;
1038 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
alan-bakere9308012019-03-15 10:25:13 -04001039 binding, &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001040 ResourceVarInfoList.emplace_back(rv);
1041 } else {
1042 rv = ResourceVarInfoList.back().get();
1043 }
1044 }
1045
1046 // Now populate FunctionToResourceVarsMap.
1047 auto &mapping =
1048 FunctionToResourceVarsMap[call->getParent()->getParent()];
1049 while (mapping.size() <= arg_index) {
1050 mapping.push_back(nullptr);
1051 }
1052 mapping[arg_index] = rv;
1053 }
1054 }
1055 }
1056 }
1057
1058 // Populate ModuleOrderedResourceVars.
1059 for (Function &F : M) {
1060 auto where = FunctionToResourceVarsMap.find(&F);
1061 if (where != FunctionToResourceVarsMap.end()) {
1062 for (auto &rv : where->second) {
1063 if (rv != nullptr) {
1064 ModuleOrderedResourceVars.insert(rv);
1065 }
1066 }
1067 }
1068 }
1069 if (ShowResourceVars) {
1070 for (auto *info : ModuleOrderedResourceVars) {
1071 outs() << "MORV index " << info->index << " (" << info->descriptor_set
1072 << "," << info->binding << ") " << *(info->var_fn->getReturnType())
1073 << "\n";
1074 }
1075 }
1076}
1077
David Neto22f144c2017-06-12 14:26:21 -04001078bool SPIRVProducerPass::FindExtInst(Module &M) {
1079 LLVMContext &Context = M.getContext();
1080 bool HasExtInst = false;
1081
1082 for (Function &F : M) {
1083 for (BasicBlock &BB : F) {
1084 for (Instruction &I : BB) {
1085 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1086 Function *Callee = Call->getCalledFunction();
1087 // Check whether this call is for extend instructions.
David Neto3fbb4072017-10-16 11:28:14 -04001088 auto callee_name = Callee->getName();
1089 const glsl::ExtInst EInst = getExtInstEnum(callee_name);
1090 const glsl::ExtInst IndirectEInst =
1091 getIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04001092
David Neto3fbb4072017-10-16 11:28:14 -04001093 HasExtInst |=
1094 (EInst != kGlslExtInstBad) || (IndirectEInst != kGlslExtInstBad);
1095
1096 if (IndirectEInst) {
1097 // Register extra constants if needed.
1098
1099 // Registers a type and constant for computing the result of the
1100 // given instruction. If the result of the instruction is a vector,
1101 // then make a splat vector constant with the same number of
1102 // elements.
1103 auto register_constant = [this, &I](Constant *constant) {
1104 FindType(constant->getType());
1105 FindConstant(constant);
1106 if (auto *vectorTy = dyn_cast<VectorType>(I.getType())) {
1107 // Register the splat vector of the value with the same
1108 // width as the result of the instruction.
1109 auto *vec_constant = ConstantVector::getSplat(
1110 static_cast<unsigned>(vectorTy->getNumElements()),
1111 constant);
1112 FindConstant(vec_constant);
1113 FindType(vec_constant->getType());
1114 }
1115 };
1116 switch (IndirectEInst) {
1117 case glsl::ExtInstFindUMsb:
1118 // clz needs OpExtInst and OpISub with constant 31, or splat
1119 // vector of 31. Add it to the constant list here.
1120 register_constant(
1121 ConstantInt::get(Type::getInt32Ty(Context), 31));
1122 break;
1123 case glsl::ExtInstAcos:
1124 case glsl::ExtInstAsin:
Kévin Petiteb9f90a2018-09-29 12:29:34 +01001125 case glsl::ExtInstAtan:
David Neto3fbb4072017-10-16 11:28:14 -04001126 case glsl::ExtInstAtan2:
1127 // We need 1/pi for acospi, asinpi, atan2pi.
1128 register_constant(
1129 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
1130 break;
1131 default:
1132 assert(false && "internally inconsistent");
1133 }
David Neto22f144c2017-06-12 14:26:21 -04001134 }
1135 }
1136 }
1137 }
1138 }
1139
1140 return HasExtInst;
1141}
1142
1143void SPIRVProducerPass::FindTypePerGlobalVar(GlobalVariable &GV) {
1144 // Investigate global variable's type.
1145 FindType(GV.getType());
1146}
1147
1148void SPIRVProducerPass::FindTypePerFunc(Function &F) {
1149 // Investigate function's type.
1150 FunctionType *FTy = F.getFunctionType();
1151
1152 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
1153 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
David Neto9ed8e2f2018-03-24 06:47:24 -07001154 // Handle a regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04001155 if (GlobalConstFuncTyMap.count(FTy)) {
1156 uint32_t GVCstArgIdx = GlobalConstFuncTypeMap[FTy].second;
1157 SmallVector<Type *, 4> NewFuncParamTys;
1158 for (unsigned i = 0; i < FTy->getNumParams(); i++) {
1159 Type *ParamTy = FTy->getParamType(i);
1160 if (i == GVCstArgIdx) {
1161 Type *EleTy = ParamTy->getPointerElementType();
1162 ParamTy = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1163 }
1164
1165 NewFuncParamTys.push_back(ParamTy);
1166 }
1167
1168 FunctionType *NewFTy =
1169 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1170 GlobalConstFuncTyMap[FTy] = std::make_pair(NewFTy, GVCstArgIdx);
1171 FTy = NewFTy;
1172 }
1173
1174 FindType(FTy);
1175 } else {
1176 // As kernel functions do not have parameters, create new function type and
1177 // add it to type map.
1178 SmallVector<Type *, 4> NewFuncParamTys;
1179 FunctionType *NewFTy =
1180 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1181 FindType(NewFTy);
1182 }
1183
1184 // Investigate instructions' type in function body.
1185 for (BasicBlock &BB : F) {
1186 for (Instruction &I : BB) {
1187 if (isa<ShuffleVectorInst>(I)) {
1188 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1189 // Ignore type for mask of shuffle vector instruction.
1190 if (i == 2) {
1191 continue;
1192 }
1193
1194 Value *Op = I.getOperand(i);
1195 if (!isa<MetadataAsValue>(Op)) {
1196 FindType(Op->getType());
1197 }
1198 }
1199
1200 FindType(I.getType());
1201 continue;
1202 }
1203
David Neto862b7d82018-06-14 18:48:37 -04001204 CallInst *Call = dyn_cast<CallInst>(&I);
1205
1206 if (Call && Call->getCalledFunction()->getName().startswith(
Alan Baker202c8c72018-08-13 13:47:44 -04001207 clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001208 // This is a fake call representing access to a resource variable.
1209 // We handle that elsewhere.
1210 continue;
1211 }
1212
Alan Baker202c8c72018-08-13 13:47:44 -04001213 if (Call && Call->getCalledFunction()->getName().startswith(
1214 clspv::WorkgroupAccessorFunction())) {
1215 // This is a fake call representing access to a workgroup variable.
1216 // We handle that elsewhere.
1217 continue;
1218 }
1219
David Neto22f144c2017-06-12 14:26:21 -04001220 // Work through the operands of the instruction.
1221 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1222 Value *const Op = I.getOperand(i);
1223 // If any of the operands is a constant, find the type!
1224 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1225 FindType(Op->getType());
1226 }
1227 }
1228
1229 for (Use &Op : I.operands()) {
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001230 if (isa<CallInst>(&I)) {
David Neto22f144c2017-06-12 14:26:21 -04001231 // Avoid to check call instruction's type.
1232 break;
1233 }
Alan Baker202c8c72018-08-13 13:47:44 -04001234 if (CallInst *OpCall = dyn_cast<CallInst>(Op)) {
1235 if (OpCall && OpCall->getCalledFunction()->getName().startswith(
1236 clspv::WorkgroupAccessorFunction())) {
1237 // This is a fake call representing access to a workgroup variable.
1238 // We handle that elsewhere.
1239 continue;
1240 }
1241 }
David Neto22f144c2017-06-12 14:26:21 -04001242 if (!isa<MetadataAsValue>(&Op)) {
1243 FindType(Op->getType());
1244 continue;
1245 }
1246 }
1247
David Neto22f144c2017-06-12 14:26:21 -04001248 // We don't want to track the type of this call as we are going to replace
1249 // it.
David Neto862b7d82018-06-14 18:48:37 -04001250 if (Call && ("clspv.sampler.var.literal" ==
David Neto22f144c2017-06-12 14:26:21 -04001251 Call->getCalledFunction()->getName())) {
1252 continue;
1253 }
1254
1255 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1256 // If gep's base operand has ModuleScopePrivate address space, make gep
1257 // return ModuleScopePrivate address space.
1258 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate) {
1259 // Add pointer type with private address space for global constant to
1260 // type list.
1261 Type *EleTy = I.getType()->getPointerElementType();
1262 Type *NewPTy =
1263 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1264
1265 FindType(NewPTy);
1266 continue;
1267 }
1268 }
1269
1270 FindType(I.getType());
1271 }
1272 }
1273}
1274
David Neto862b7d82018-06-14 18:48:37 -04001275void SPIRVProducerPass::FindTypesForSamplerMap(Module &M) {
1276 // If we are using a sampler map, find the type of the sampler.
1277 if (M.getFunction("clspv.sampler.var.literal") ||
1278 0 < getSamplerMap().size()) {
1279 auto SamplerStructTy = M.getTypeByName("opencl.sampler_t");
1280 if (!SamplerStructTy) {
1281 SamplerStructTy = StructType::create(M.getContext(), "opencl.sampler_t");
1282 }
1283
1284 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
1285
1286 FindType(SamplerTy);
1287 }
1288}
1289
1290void SPIRVProducerPass::FindTypesForResourceVars(Module &M) {
1291 // Record types so they are generated.
1292 TypesNeedingLayout.reset();
1293 StructTypesNeedingBlock.reset();
1294
1295 // To match older clspv codegen, generate the float type first if required
1296 // for images.
1297 for (const auto *info : ModuleOrderedResourceVars) {
1298 if (info->arg_kind == clspv::ArgKind::ReadOnlyImage ||
1299 info->arg_kind == clspv::ArgKind::WriteOnlyImage) {
1300 // We need "float" for the sampled component type.
1301 FindType(Type::getFloatTy(M.getContext()));
1302 // We only need to find it once.
1303 break;
1304 }
1305 }
1306
1307 for (const auto *info : ModuleOrderedResourceVars) {
1308 Type *type = info->var_fn->getReturnType();
1309
1310 switch (info->arg_kind) {
1311 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04001312 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04001313 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1314 StructTypesNeedingBlock.insert(sty);
1315 } else {
1316 errs() << *type << "\n";
1317 llvm_unreachable("Buffer arguments must map to structures!");
1318 }
1319 break;
1320 case clspv::ArgKind::Pod:
1321 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1322 StructTypesNeedingBlock.insert(sty);
1323 } else {
1324 errs() << *type << "\n";
1325 llvm_unreachable("POD arguments must map to structures!");
1326 }
1327 break;
1328 case clspv::ArgKind::ReadOnlyImage:
1329 case clspv::ArgKind::WriteOnlyImage:
1330 case clspv::ArgKind::Sampler:
1331 // Sampler and image types map to the pointee type but
1332 // in the uniform constant address space.
1333 type = PointerType::get(type->getPointerElementType(),
1334 clspv::AddressSpace::UniformConstant);
1335 break;
1336 default:
1337 break;
1338 }
1339
1340 // The converted type is the type of the OpVariable we will generate.
1341 // If the pointee type is an array of size zero, FindType will convert it
1342 // to a runtime array.
1343 FindType(type);
1344 }
1345
1346 // Traverse the arrays and structures underneath each Block, and
1347 // mark them as needing layout.
1348 std::vector<Type *> work_list(StructTypesNeedingBlock.begin(),
1349 StructTypesNeedingBlock.end());
1350 while (!work_list.empty()) {
1351 Type *type = work_list.back();
1352 work_list.pop_back();
1353 TypesNeedingLayout.insert(type);
1354 switch (type->getTypeID()) {
1355 case Type::ArrayTyID:
1356 work_list.push_back(type->getArrayElementType());
1357 if (!Hack_generate_runtime_array_stride_early) {
1358 // Remember this array type for deferred decoration.
1359 TypesNeedingArrayStride.insert(type);
1360 }
1361 break;
1362 case Type::StructTyID:
1363 for (auto *elem_ty : cast<StructType>(type)->elements()) {
1364 work_list.push_back(elem_ty);
1365 }
1366 default:
1367 // This type and its contained types don't get layout.
1368 break;
1369 }
1370 }
1371}
1372
Alan Baker202c8c72018-08-13 13:47:44 -04001373void SPIRVProducerPass::FindWorkgroupVars(Module &M) {
1374 // The SpecId assignment for pointer-to-local arguments is recorded in
1375 // module-level metadata. Translate that information into local argument
1376 // information.
1377 NamedMDNode *nmd = M.getNamedMetadata(clspv::LocalSpecIdMetadataName());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001378 if (!nmd)
1379 return;
Alan Baker202c8c72018-08-13 13:47:44 -04001380 for (auto operand : nmd->operands()) {
1381 MDTuple *tuple = cast<MDTuple>(operand);
1382 ValueAsMetadata *fn_md = cast<ValueAsMetadata>(tuple->getOperand(0));
1383 Function *func = cast<Function>(fn_md->getValue());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001384 ConstantAsMetadata *arg_index_md =
1385 cast<ConstantAsMetadata>(tuple->getOperand(1));
1386 int arg_index = static_cast<int>(
1387 cast<ConstantInt>(arg_index_md->getValue())->getSExtValue());
1388 Argument *arg = &*(func->arg_begin() + arg_index);
Alan Baker202c8c72018-08-13 13:47:44 -04001389
1390 ConstantAsMetadata *spec_id_md =
1391 cast<ConstantAsMetadata>(tuple->getOperand(2));
alan-bakerb6b09dc2018-11-08 16:59:28 -05001392 int spec_id = static_cast<int>(
1393 cast<ConstantInt>(spec_id_md->getValue())->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04001394
1395 max_local_spec_id_ = std::max(max_local_spec_id_, spec_id + 1);
1396 LocalArgSpecIds[arg] = spec_id;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001397 if (LocalSpecIdInfoMap.count(spec_id))
1398 continue;
Alan Baker202c8c72018-08-13 13:47:44 -04001399
1400 // We haven't seen this SpecId yet, so generate the LocalArgInfo for it.
1401 LocalArgInfo info{nextID, arg->getType()->getPointerElementType(),
1402 nextID + 1, nextID + 2,
1403 nextID + 3, spec_id};
1404 LocalSpecIdInfoMap[spec_id] = info;
1405 nextID += 4;
1406
1407 // Ensure the types necessary for this argument get generated.
1408 Type *IdxTy = Type::getInt32Ty(M.getContext());
1409 FindConstant(ConstantInt::get(IdxTy, 0));
1410 FindType(IdxTy);
1411 FindType(arg->getType());
1412 }
1413}
1414
David Neto22f144c2017-06-12 14:26:21 -04001415void SPIRVProducerPass::FindType(Type *Ty) {
1416 TypeList &TyList = getTypeList();
1417
1418 if (0 != TyList.idFor(Ty)) {
1419 return;
1420 }
1421
1422 if (Ty->isPointerTy()) {
1423 auto AddrSpace = Ty->getPointerAddressSpace();
1424 if ((AddressSpace::Constant == AddrSpace) ||
1425 (AddressSpace::Global == AddrSpace)) {
1426 auto PointeeTy = Ty->getPointerElementType();
1427
1428 if (PointeeTy->isStructTy() &&
1429 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1430 FindType(PointeeTy);
1431 auto ActualPointerTy =
1432 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1433 FindType(ActualPointerTy);
1434 return;
1435 }
1436 }
1437 }
1438
David Neto862b7d82018-06-14 18:48:37 -04001439 // By convention, LLVM array type with 0 elements will map to
1440 // OpTypeRuntimeArray. Otherwise, it will map to OpTypeArray, which
1441 // has a constant number of elements. We need to support type of the
1442 // constant.
1443 if (auto *arrayTy = dyn_cast<ArrayType>(Ty)) {
1444 if (arrayTy->getNumElements() > 0) {
1445 LLVMContext &Context = Ty->getContext();
1446 FindType(Type::getInt32Ty(Context));
1447 }
David Neto22f144c2017-06-12 14:26:21 -04001448 }
1449
1450 for (Type *SubTy : Ty->subtypes()) {
1451 FindType(SubTy);
1452 }
1453
1454 TyList.insert(Ty);
1455}
1456
1457void SPIRVProducerPass::FindConstantPerGlobalVar(GlobalVariable &GV) {
1458 // If the global variable has a (non undef) initializer.
1459 if (GV.hasInitializer() && !isa<UndefValue>(GV.getInitializer())) {
David Neto862b7d82018-06-14 18:48:37 -04001460 // Generate the constant if it's not the initializer to a module scope
1461 // constant that we will expect in a storage buffer.
1462 const bool module_scope_constant_external_init =
1463 (GV.getType()->getPointerAddressSpace() == AddressSpace::Constant) &&
1464 clspv::Option::ModuleConstantsInStorageBuffer();
1465 if (!module_scope_constant_external_init) {
1466 FindConstant(GV.getInitializer());
1467 }
David Neto22f144c2017-06-12 14:26:21 -04001468 }
1469}
1470
1471void SPIRVProducerPass::FindConstantPerFunc(Function &F) {
1472 // Investigate constants in function body.
1473 for (BasicBlock &BB : F) {
1474 for (Instruction &I : BB) {
David Neto862b7d82018-06-14 18:48:37 -04001475 if (auto *call = dyn_cast<CallInst>(&I)) {
1476 auto name = call->getCalledFunction()->getName();
1477 if (name == "clspv.sampler.var.literal") {
1478 // We've handled these constants elsewhere, so skip it.
1479 continue;
1480 }
Alan Baker202c8c72018-08-13 13:47:44 -04001481 if (name.startswith(clspv::ResourceAccessorFunction())) {
1482 continue;
1483 }
1484 if (name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001485 continue;
1486 }
Kévin Petit617a76d2019-04-04 13:54:16 +01001487 if (name.startswith(clspv::SPIRVOpIntrinsicFunction())) {
1488 // Skip the first operand that has the SPIR-V Opcode
1489 for (unsigned i = 1; i < I.getNumOperands(); i++) {
1490 if (isa<Constant>(I.getOperand(i)) &&
1491 !isa<GlobalValue>(I.getOperand(i))) {
1492 FindConstant(I.getOperand(i));
1493 }
1494 }
1495 continue;
1496 }
David Neto22f144c2017-06-12 14:26:21 -04001497 }
1498
1499 if (isa<AllocaInst>(I)) {
1500 // Alloca instruction has constant for the number of element. Ignore it.
1501 continue;
1502 } else if (isa<ShuffleVectorInst>(I)) {
1503 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1504 // Ignore constant for mask of shuffle vector instruction.
1505 if (i == 2) {
1506 continue;
1507 }
1508
1509 if (isa<Constant>(I.getOperand(i)) &&
1510 !isa<GlobalValue>(I.getOperand(i))) {
1511 FindConstant(I.getOperand(i));
1512 }
1513 }
1514
1515 continue;
1516 } else if (isa<InsertElementInst>(I)) {
1517 // Handle InsertElement with <4 x i8> specially.
1518 Type *CompositeTy = I.getOperand(0)->getType();
1519 if (is4xi8vec(CompositeTy)) {
1520 LLVMContext &Context = CompositeTy->getContext();
1521 if (isa<Constant>(I.getOperand(0))) {
1522 FindConstant(I.getOperand(0));
1523 }
1524
1525 if (isa<Constant>(I.getOperand(1))) {
1526 FindConstant(I.getOperand(1));
1527 }
1528
1529 // Add mask constant 0xFF.
1530 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1531 FindConstant(CstFF);
1532
1533 // Add shift amount constant.
1534 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
1535 uint64_t Idx = CI->getZExtValue();
1536 Constant *CstShiftAmount =
1537 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1538 FindConstant(CstShiftAmount);
1539 }
1540
1541 continue;
1542 }
1543
1544 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1545 // Ignore constant for index of InsertElement instruction.
1546 if (i == 2) {
1547 continue;
1548 }
1549
1550 if (isa<Constant>(I.getOperand(i)) &&
1551 !isa<GlobalValue>(I.getOperand(i))) {
1552 FindConstant(I.getOperand(i));
1553 }
1554 }
1555
1556 continue;
1557 } else if (isa<ExtractElementInst>(I)) {
1558 // Handle ExtractElement with <4 x i8> specially.
1559 Type *CompositeTy = I.getOperand(0)->getType();
1560 if (is4xi8vec(CompositeTy)) {
1561 LLVMContext &Context = CompositeTy->getContext();
1562 if (isa<Constant>(I.getOperand(0))) {
1563 FindConstant(I.getOperand(0));
1564 }
1565
1566 // Add mask constant 0xFF.
1567 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1568 FindConstant(CstFF);
1569
1570 // Add shift amount constant.
1571 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1572 uint64_t Idx = CI->getZExtValue();
1573 Constant *CstShiftAmount =
1574 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1575 FindConstant(CstShiftAmount);
1576 } else {
1577 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
1578 FindConstant(Cst8);
1579 }
1580
1581 continue;
1582 }
1583
1584 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1585 // Ignore constant for index of ExtractElement instruction.
1586 if (i == 1) {
1587 continue;
1588 }
1589
1590 if (isa<Constant>(I.getOperand(i)) &&
1591 !isa<GlobalValue>(I.getOperand(i))) {
1592 FindConstant(I.getOperand(i));
1593 }
1594 }
1595
1596 continue;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001597 } else if ((Instruction::Xor == I.getOpcode()) &&
1598 I.getType()->isIntegerTy(1)) {
1599 // We special case for Xor where the type is i1 and one of the arguments
1600 // is a constant 1 (true), this is an OpLogicalNot in SPIR-V, and we
1601 // don't need the constant
David Neto22f144c2017-06-12 14:26:21 -04001602 bool foundConstantTrue = false;
1603 for (Use &Op : I.operands()) {
1604 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1605 auto CI = cast<ConstantInt>(Op);
1606
1607 if (CI->isZero() || foundConstantTrue) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05001608 // If we already found the true constant, we might (probably only
1609 // on -O0) have an OpLogicalNot which is taking a constant
1610 // argument, so discover it anyway.
David Neto22f144c2017-06-12 14:26:21 -04001611 FindConstant(Op);
1612 } else {
1613 foundConstantTrue = true;
1614 }
1615 }
1616 }
1617
1618 continue;
David Netod2de94a2017-08-28 17:27:47 -04001619 } else if (isa<TruncInst>(I)) {
alan-bakerb39c8262019-03-08 14:03:37 -05001620 // Special case if i8 is not generally handled.
1621 if (!clspv::Option::Int8Support()) {
1622 // For truncation to i8 we mask against 255.
1623 Type *ToTy = I.getType();
1624 if (8u == ToTy->getPrimitiveSizeInBits()) {
1625 LLVMContext &Context = ToTy->getContext();
1626 Constant *Cst255 =
1627 ConstantInt::get(Type::getInt32Ty(Context), 0xff);
1628 FindConstant(Cst255);
1629 }
David Netod2de94a2017-08-28 17:27:47 -04001630 }
Neil Henning39672102017-09-29 14:33:13 +01001631 } else if (isa<AtomicRMWInst>(I)) {
1632 LLVMContext &Context = I.getContext();
1633
1634 FindConstant(
1635 ConstantInt::get(Type::getInt32Ty(Context), spv::ScopeDevice));
1636 FindConstant(ConstantInt::get(
1637 Type::getInt32Ty(Context),
1638 spv::MemorySemanticsUniformMemoryMask |
1639 spv::MemorySemanticsSequentiallyConsistentMask));
David Neto22f144c2017-06-12 14:26:21 -04001640 }
1641
1642 for (Use &Op : I.operands()) {
1643 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1644 FindConstant(Op);
1645 }
1646 }
1647 }
1648 }
1649}
1650
1651void SPIRVProducerPass::FindConstant(Value *V) {
David Neto22f144c2017-06-12 14:26:21 -04001652 ValueList &CstList = getConstantList();
1653
David Netofb9a7972017-08-25 17:08:24 -04001654 // If V is already tracked, ignore it.
1655 if (0 != CstList.idFor(V)) {
David Neto22f144c2017-06-12 14:26:21 -04001656 return;
1657 }
1658
David Neto862b7d82018-06-14 18:48:37 -04001659 if (isa<GlobalValue>(V) && clspv::Option::ModuleConstantsInStorageBuffer()) {
1660 return;
1661 }
1662
David Neto22f144c2017-06-12 14:26:21 -04001663 Constant *Cst = cast<Constant>(V);
David Neto862b7d82018-06-14 18:48:37 -04001664 Type *CstTy = Cst->getType();
David Neto22f144c2017-06-12 14:26:21 -04001665
1666 // Handle constant with <4 x i8> type specially.
David Neto22f144c2017-06-12 14:26:21 -04001667 if (is4xi8vec(CstTy)) {
1668 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001669 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001670 }
1671 }
1672
1673 if (Cst->getNumOperands()) {
1674 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end(); I != E;
1675 ++I) {
1676 FindConstant(*I);
1677 }
1678
David Netofb9a7972017-08-25 17:08:24 -04001679 CstList.insert(Cst);
David Neto22f144c2017-06-12 14:26:21 -04001680 return;
1681 } else if (const ConstantDataSequential *CDS =
1682 dyn_cast<ConstantDataSequential>(Cst)) {
1683 // Add constants for each element to constant list.
1684 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
1685 Constant *EleCst = CDS->getElementAsConstant(i);
1686 FindConstant(EleCst);
1687 }
1688 }
1689
1690 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001691 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001692 }
1693}
1694
1695spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1696 switch (AddrSpace) {
1697 default:
1698 llvm_unreachable("Unsupported OpenCL address space");
1699 case AddressSpace::Private:
1700 return spv::StorageClassFunction;
1701 case AddressSpace::Global:
David Neto22f144c2017-06-12 14:26:21 -04001702 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001703 case AddressSpace::Constant:
1704 return clspv::Option::ConstantArgsInUniformBuffer()
1705 ? spv::StorageClassUniform
1706 : spv::StorageClassStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -04001707 case AddressSpace::Input:
1708 return spv::StorageClassInput;
1709 case AddressSpace::Local:
1710 return spv::StorageClassWorkgroup;
1711 case AddressSpace::UniformConstant:
1712 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001713 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001714 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001715 case AddressSpace::ModuleScopePrivate:
1716 return spv::StorageClassPrivate;
1717 }
1718}
1719
David Neto862b7d82018-06-14 18:48:37 -04001720spv::StorageClass
1721SPIRVProducerPass::GetStorageClassForArgKind(clspv::ArgKind arg_kind) const {
1722 switch (arg_kind) {
1723 case clspv::ArgKind::Buffer:
1724 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001725 case clspv::ArgKind::BufferUBO:
1726 return spv::StorageClassUniform;
David Neto862b7d82018-06-14 18:48:37 -04001727 case clspv::ArgKind::Pod:
1728 return clspv::Option::PodArgsInUniformBuffer()
1729 ? spv::StorageClassUniform
1730 : spv::StorageClassStorageBuffer;
1731 case clspv::ArgKind::Local:
1732 return spv::StorageClassWorkgroup;
1733 case clspv::ArgKind::ReadOnlyImage:
1734 case clspv::ArgKind::WriteOnlyImage:
1735 case clspv::ArgKind::Sampler:
1736 return spv::StorageClassUniformConstant;
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001737 default:
1738 llvm_unreachable("Unsupported storage class for argument kind");
David Neto862b7d82018-06-14 18:48:37 -04001739 }
1740}
1741
David Neto22f144c2017-06-12 14:26:21 -04001742spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1743 return StringSwitch<spv::BuiltIn>(Name)
1744 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1745 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1746 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1747 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1748 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
1749 .Default(spv::BuiltInMax);
1750}
1751
1752void SPIRVProducerPass::GenerateExtInstImport() {
1753 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1754 uint32_t &ExtInstImportID = getOpExtInstImportID();
1755
1756 //
1757 // Generate OpExtInstImport.
1758 //
1759 // Ops[0] ... Ops[n] = Name (Literal String)
David Neto22f144c2017-06-12 14:26:21 -04001760 ExtInstImportID = nextID;
David Neto87846742018-04-11 17:36:22 -04001761 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpExtInstImport, nextID++,
1762 MkString("GLSL.std.450")));
David Neto22f144c2017-06-12 14:26:21 -04001763}
1764
alan-bakerb6b09dc2018-11-08 16:59:28 -05001765void SPIRVProducerPass::GenerateSPIRVTypes(LLVMContext &Context,
1766 Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04001767 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1768 ValueMapType &VMap = getValueMap();
1769 ValueMapType &AllocatedVMap = getAllocatedValueMap();
Alan Bakerfcda9482018-10-02 17:09:59 -04001770 const auto &DL = module.getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04001771
1772 // Map for OpTypeRuntimeArray. If argument has pointer type, 2 spirv type
1773 // instructions are generated. They are OpTypePointer and OpTypeRuntimeArray.
1774 DenseMap<Type *, uint32_t> OpRuntimeTyMap;
1775
1776 for (Type *Ty : getTypeList()) {
1777 // Update TypeMap with nextID for reference later.
1778 TypeMap[Ty] = nextID;
1779
1780 switch (Ty->getTypeID()) {
1781 default: {
1782 Ty->print(errs());
1783 llvm_unreachable("Unsupported type???");
1784 break;
1785 }
1786 case Type::MetadataTyID:
1787 case Type::LabelTyID: {
1788 // Ignore these types.
1789 break;
1790 }
1791 case Type::PointerTyID: {
1792 PointerType *PTy = cast<PointerType>(Ty);
1793 unsigned AddrSpace = PTy->getAddressSpace();
1794
1795 // For the purposes of our Vulkan SPIR-V type system, constant and global
1796 // are conflated.
1797 bool UseExistingOpTypePointer = false;
1798 if (AddressSpace::Constant == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001799 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1800 AddrSpace = AddressSpace::Global;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001801 // Check to see if we already created this type (for instance, if we
1802 // had a constant <type>* and a global <type>*, the type would be
1803 // created by one of these types, and shared by both).
Alan Bakerfcda9482018-10-02 17:09:59 -04001804 auto GlobalTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1805 if (0 < TypeMap.count(GlobalTy)) {
1806 TypeMap[PTy] = TypeMap[GlobalTy];
1807 UseExistingOpTypePointer = true;
1808 break;
1809 }
David Neto22f144c2017-06-12 14:26:21 -04001810 }
1811 } else if (AddressSpace::Global == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001812 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1813 AddrSpace = AddressSpace::Constant;
David Neto22f144c2017-06-12 14:26:21 -04001814
alan-bakerb6b09dc2018-11-08 16:59:28 -05001815 // Check to see if we already created this type (for instance, if we
1816 // had a constant <type>* and a global <type>*, the type would be
1817 // created by one of these types, and shared by both).
1818 auto ConstantTy =
1819 PTy->getPointerElementType()->getPointerTo(AddrSpace);
Alan Bakerfcda9482018-10-02 17:09:59 -04001820 if (0 < TypeMap.count(ConstantTy)) {
1821 TypeMap[PTy] = TypeMap[ConstantTy];
1822 UseExistingOpTypePointer = true;
1823 }
David Neto22f144c2017-06-12 14:26:21 -04001824 }
1825 }
1826
David Neto862b7d82018-06-14 18:48:37 -04001827 const bool HasArgUser = true;
David Neto22f144c2017-06-12 14:26:21 -04001828
David Neto862b7d82018-06-14 18:48:37 -04001829 if (HasArgUser && !UseExistingOpTypePointer) {
David Neto22f144c2017-06-12 14:26:21 -04001830 //
1831 // Generate OpTypePointer.
1832 //
1833
1834 // OpTypePointer
1835 // Ops[0] = Storage Class
1836 // Ops[1] = Element Type ID
1837 SPIRVOperandList Ops;
1838
David Neto257c3892018-04-11 13:19:45 -04001839 Ops << MkNum(GetStorageClass(AddrSpace))
1840 << MkId(lookupType(PTy->getElementType()));
David Neto22f144c2017-06-12 14:26:21 -04001841
David Neto87846742018-04-11 17:36:22 -04001842 auto *Inst = new SPIRVInstruction(spv::OpTypePointer, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001843 SPIRVInstList.push_back(Inst);
1844 }
David Neto22f144c2017-06-12 14:26:21 -04001845 break;
1846 }
1847 case Type::StructTyID: {
David Neto22f144c2017-06-12 14:26:21 -04001848 StructType *STy = cast<StructType>(Ty);
1849
1850 // Handle sampler type.
1851 if (STy->isOpaque()) {
1852 if (STy->getName().equals("opencl.sampler_t")) {
1853 //
1854 // Generate OpTypeSampler
1855 //
1856 // Empty Ops.
1857 SPIRVOperandList Ops;
1858
David Neto87846742018-04-11 17:36:22 -04001859 auto *Inst = new SPIRVInstruction(spv::OpTypeSampler, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001860 SPIRVInstList.push_back(Inst);
1861 break;
1862 } else if (STy->getName().equals("opencl.image2d_ro_t") ||
1863 STy->getName().equals("opencl.image2d_wo_t") ||
1864 STy->getName().equals("opencl.image3d_ro_t") ||
1865 STy->getName().equals("opencl.image3d_wo_t")) {
1866 //
1867 // Generate OpTypeImage
1868 //
1869 // Ops[0] = Sampled Type ID
1870 // Ops[1] = Dim ID
1871 // Ops[2] = Depth (Literal Number)
1872 // Ops[3] = Arrayed (Literal Number)
1873 // Ops[4] = MS (Literal Number)
1874 // Ops[5] = Sampled (Literal Number)
1875 // Ops[6] = Image Format ID
1876 //
1877 SPIRVOperandList Ops;
1878
1879 // TODO: Changed Sampled Type according to situations.
1880 uint32_t SampledTyID = lookupType(Type::getFloatTy(Context));
David Neto257c3892018-04-11 13:19:45 -04001881 Ops << MkId(SampledTyID);
David Neto22f144c2017-06-12 14:26:21 -04001882
1883 spv::Dim DimID = spv::Dim2D;
1884 if (STy->getName().equals("opencl.image3d_ro_t") ||
1885 STy->getName().equals("opencl.image3d_wo_t")) {
1886 DimID = spv::Dim3D;
1887 }
David Neto257c3892018-04-11 13:19:45 -04001888 Ops << MkNum(DimID);
David Neto22f144c2017-06-12 14:26:21 -04001889
1890 // TODO: Set up Depth.
David Neto257c3892018-04-11 13:19:45 -04001891 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001892
1893 // TODO: Set up Arrayed.
David Neto257c3892018-04-11 13:19:45 -04001894 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001895
1896 // TODO: Set up MS.
David Neto257c3892018-04-11 13:19:45 -04001897 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001898
1899 // TODO: Set up Sampled.
1900 //
1901 // From Spec
1902 //
1903 // 0 indicates this is only known at run time, not at compile time
1904 // 1 indicates will be used with sampler
1905 // 2 indicates will be used without a sampler (a storage image)
1906 uint32_t Sampled = 1;
1907 if (STy->getName().equals("opencl.image2d_wo_t") ||
1908 STy->getName().equals("opencl.image3d_wo_t")) {
1909 Sampled = 2;
1910 }
David Neto257c3892018-04-11 13:19:45 -04001911 Ops << MkNum(Sampled);
David Neto22f144c2017-06-12 14:26:21 -04001912
1913 // TODO: Set up Image Format.
David Neto257c3892018-04-11 13:19:45 -04001914 Ops << MkNum(spv::ImageFormatUnknown);
David Neto22f144c2017-06-12 14:26:21 -04001915
David Neto87846742018-04-11 17:36:22 -04001916 auto *Inst = new SPIRVInstruction(spv::OpTypeImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001917 SPIRVInstList.push_back(Inst);
1918 break;
1919 }
1920 }
1921
1922 //
1923 // Generate OpTypeStruct
1924 //
1925 // Ops[0] ... Ops[n] = Member IDs
1926 SPIRVOperandList Ops;
1927
1928 for (auto *EleTy : STy->elements()) {
David Neto862b7d82018-06-14 18:48:37 -04001929 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04001930 }
1931
David Neto22f144c2017-06-12 14:26:21 -04001932 uint32_t STyID = nextID;
1933
alan-bakerb6b09dc2018-11-08 16:59:28 -05001934 auto *Inst = new SPIRVInstruction(spv::OpTypeStruct, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001935 SPIRVInstList.push_back(Inst);
1936
1937 // Generate OpMemberDecorate.
1938 auto DecoInsertPoint =
1939 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
1940 [](SPIRVInstruction *Inst) -> bool {
1941 return Inst->getOpcode() != spv::OpDecorate &&
1942 Inst->getOpcode() != spv::OpMemberDecorate &&
1943 Inst->getOpcode() != spv::OpExtInstImport;
1944 });
1945
David Netoc463b372017-08-10 15:32:21 -04001946 const auto StructLayout = DL.getStructLayout(STy);
Alan Bakerfcda9482018-10-02 17:09:59 -04001947 // Search for the correct offsets if this type was remapped.
1948 std::vector<uint32_t> *offsets = nullptr;
1949 auto iter = RemappedUBOTypeOffsets.find(STy);
1950 if (iter != RemappedUBOTypeOffsets.end()) {
1951 offsets = &iter->second;
1952 }
David Netoc463b372017-08-10 15:32:21 -04001953
David Neto862b7d82018-06-14 18:48:37 -04001954 // #error TODO(dneto): Only do this if in TypesNeedingLayout.
David Neto22f144c2017-06-12 14:26:21 -04001955 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
1956 MemberIdx++) {
1957 // Ops[0] = Structure Type ID
1958 // Ops[1] = Member Index(Literal Number)
1959 // Ops[2] = Decoration (Offset)
1960 // Ops[3] = Byte Offset (Literal Number)
1961 Ops.clear();
1962
David Neto257c3892018-04-11 13:19:45 -04001963 Ops << MkId(STyID) << MkNum(MemberIdx) << MkNum(spv::DecorationOffset);
David Neto22f144c2017-06-12 14:26:21 -04001964
alan-bakerb6b09dc2018-11-08 16:59:28 -05001965 auto ByteOffset =
1966 static_cast<uint32_t>(StructLayout->getElementOffset(MemberIdx));
Alan Bakerfcda9482018-10-02 17:09:59 -04001967 if (offsets) {
1968 ByteOffset = (*offsets)[MemberIdx];
1969 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05001970 // const auto ByteOffset =
Alan Bakerfcda9482018-10-02 17:09:59 -04001971 // uint32_t(StructLayout->getElementOffset(MemberIdx));
David Neto257c3892018-04-11 13:19:45 -04001972 Ops << MkNum(ByteOffset);
David Neto22f144c2017-06-12 14:26:21 -04001973
David Neto87846742018-04-11 17:36:22 -04001974 auto *DecoInst = new SPIRVInstruction(spv::OpMemberDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001975 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04001976 }
1977
1978 // Generate OpDecorate.
David Neto862b7d82018-06-14 18:48:37 -04001979 if (StructTypesNeedingBlock.idFor(STy)) {
1980 Ops.clear();
1981 // Use Block decorations with StorageBuffer storage class.
1982 Ops << MkId(STyID) << MkNum(spv::DecorationBlock);
David Neto22f144c2017-06-12 14:26:21 -04001983
David Neto862b7d82018-06-14 18:48:37 -04001984 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
1985 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04001986 }
1987 break;
1988 }
1989 case Type::IntegerTyID: {
1990 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
1991
1992 if (BitWidth == 1) {
David Neto87846742018-04-11 17:36:22 -04001993 auto *Inst = new SPIRVInstruction(spv::OpTypeBool, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04001994 SPIRVInstList.push_back(Inst);
1995 } else {
alan-bakerb39c8262019-03-08 14:03:37 -05001996 if (!clspv::Option::Int8Support()) {
1997 // i8 is added to TypeMap as i32.
1998 // No matter what LLVM type is requested first, always alias the
1999 // second one's SPIR-V type to be the same as the one we generated
2000 // first.
2001 unsigned aliasToWidth = 0;
2002 if (BitWidth == 8) {
2003 aliasToWidth = 32;
2004 BitWidth = 32;
2005 } else if (BitWidth == 32) {
2006 aliasToWidth = 8;
2007 }
2008 if (aliasToWidth) {
2009 Type *otherType = Type::getIntNTy(Ty->getContext(), aliasToWidth);
2010 auto where = TypeMap.find(otherType);
2011 if (where == TypeMap.end()) {
2012 // Go ahead and make it, but also map the other type to it.
2013 TypeMap[otherType] = nextID;
2014 } else {
2015 // Alias this SPIR-V type the existing type.
2016 TypeMap[Ty] = where->second;
2017 break;
2018 }
David Neto391aeb12017-08-26 15:51:58 -04002019 }
David Neto22f144c2017-06-12 14:26:21 -04002020 }
2021
David Neto257c3892018-04-11 13:19:45 -04002022 SPIRVOperandList Ops;
2023 Ops << MkNum(BitWidth) << MkNum(0 /* not signed */);
David Neto22f144c2017-06-12 14:26:21 -04002024
2025 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002026 new SPIRVInstruction(spv::OpTypeInt, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002027 }
2028 break;
2029 }
2030 case Type::HalfTyID:
2031 case Type::FloatTyID:
2032 case Type::DoubleTyID: {
2033 SPIRVOperand *WidthOp = new SPIRVOperand(
2034 SPIRVOperandType::LITERAL_INTEGER, Ty->getPrimitiveSizeInBits());
2035
2036 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002037 new SPIRVInstruction(spv::OpTypeFloat, nextID++, WidthOp));
David Neto22f144c2017-06-12 14:26:21 -04002038 break;
2039 }
2040 case Type::ArrayTyID: {
David Neto22f144c2017-06-12 14:26:21 -04002041 ArrayType *ArrTy = cast<ArrayType>(Ty);
David Neto862b7d82018-06-14 18:48:37 -04002042 const uint64_t Length = ArrTy->getArrayNumElements();
2043 if (Length == 0) {
2044 // By convention, map it to a RuntimeArray.
David Neto22f144c2017-06-12 14:26:21 -04002045
David Neto862b7d82018-06-14 18:48:37 -04002046 // Only generate the type once.
2047 // TODO(dneto): Can it ever be generated more than once?
2048 // Doesn't LLVM type uniqueness guarantee we'll only see this
2049 // once?
2050 Type *EleTy = ArrTy->getArrayElementType();
2051 if (OpRuntimeTyMap.count(EleTy) == 0) {
2052 uint32_t OpTypeRuntimeArrayID = nextID;
2053 OpRuntimeTyMap[Ty] = nextID;
David Neto22f144c2017-06-12 14:26:21 -04002054
David Neto862b7d82018-06-14 18:48:37 -04002055 //
2056 // Generate OpTypeRuntimeArray.
2057 //
David Neto22f144c2017-06-12 14:26:21 -04002058
David Neto862b7d82018-06-14 18:48:37 -04002059 // OpTypeRuntimeArray
2060 // Ops[0] = Element Type ID
2061 SPIRVOperandList Ops;
2062 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04002063
David Neto862b7d82018-06-14 18:48:37 -04002064 SPIRVInstList.push_back(
2065 new SPIRVInstruction(spv::OpTypeRuntimeArray, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002066
David Neto862b7d82018-06-14 18:48:37 -04002067 if (Hack_generate_runtime_array_stride_early) {
2068 // Generate OpDecorate.
2069 auto DecoInsertPoint = std::find_if(
2070 SPIRVInstList.begin(), SPIRVInstList.end(),
2071 [](SPIRVInstruction *Inst) -> bool {
2072 return Inst->getOpcode() != spv::OpDecorate &&
2073 Inst->getOpcode() != spv::OpMemberDecorate &&
2074 Inst->getOpcode() != spv::OpExtInstImport;
2075 });
David Neto22f144c2017-06-12 14:26:21 -04002076
David Neto862b7d82018-06-14 18:48:37 -04002077 // Ops[0] = Target ID
2078 // Ops[1] = Decoration (ArrayStride)
2079 // Ops[2] = Stride Number(Literal Number)
2080 Ops.clear();
David Neto85082642018-03-24 06:55:20 -07002081
David Neto862b7d82018-06-14 18:48:37 -04002082 Ops << MkId(OpTypeRuntimeArrayID)
2083 << MkNum(spv::DecorationArrayStride)
Alan Bakerfcda9482018-10-02 17:09:59 -04002084 << MkNum(static_cast<uint32_t>(GetTypeAllocSize(EleTy, DL)));
David Neto22f144c2017-06-12 14:26:21 -04002085
David Neto862b7d82018-06-14 18:48:37 -04002086 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
2087 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
2088 }
2089 }
David Neto22f144c2017-06-12 14:26:21 -04002090
David Neto862b7d82018-06-14 18:48:37 -04002091 } else {
David Neto22f144c2017-06-12 14:26:21 -04002092
David Neto862b7d82018-06-14 18:48:37 -04002093 //
2094 // Generate OpConstant and OpTypeArray.
2095 //
2096
2097 //
2098 // Generate OpConstant for array length.
2099 //
2100 // Ops[0] = Result Type ID
2101 // Ops[1] .. Ops[n] = Values LiteralNumber
2102 SPIRVOperandList Ops;
2103
2104 Type *LengthTy = Type::getInt32Ty(Context);
2105 uint32_t ResTyID = lookupType(LengthTy);
2106 Ops << MkId(ResTyID);
2107
2108 assert(Length < UINT32_MAX);
2109 Ops << MkNum(static_cast<uint32_t>(Length));
2110
2111 // Add constant for length to constant list.
2112 Constant *CstLength = ConstantInt::get(LengthTy, Length);
2113 AllocatedVMap[CstLength] = nextID;
2114 VMap[CstLength] = nextID;
2115 uint32_t LengthID = nextID;
2116
2117 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
2118 SPIRVInstList.push_back(CstInst);
2119
2120 // Remember to generate ArrayStride later
2121 getTypesNeedingArrayStride().insert(Ty);
2122
2123 //
2124 // Generate OpTypeArray.
2125 //
2126 // Ops[0] = Element Type ID
2127 // Ops[1] = Array Length Constant ID
2128 Ops.clear();
2129
2130 uint32_t EleTyID = lookupType(ArrTy->getElementType());
2131 Ops << MkId(EleTyID) << MkId(LengthID);
2132
2133 // Update TypeMap with nextID.
2134 TypeMap[Ty] = nextID;
2135
2136 auto *ArrayInst = new SPIRVInstruction(spv::OpTypeArray, nextID++, Ops);
2137 SPIRVInstList.push_back(ArrayInst);
2138 }
David Neto22f144c2017-06-12 14:26:21 -04002139 break;
2140 }
2141 case Type::VectorTyID: {
alan-bakerb39c8262019-03-08 14:03:37 -05002142 // <4 x i8> is changed to i32 if i8 is not generally supported.
2143 if (!clspv::Option::Int8Support() &&
2144 Ty->getVectorElementType() == Type::getInt8Ty(Context)) {
David Neto22f144c2017-06-12 14:26:21 -04002145 if (Ty->getVectorNumElements() == 4) {
2146 TypeMap[Ty] = lookupType(Ty->getVectorElementType());
2147 break;
2148 } else {
2149 Ty->print(errs());
2150 llvm_unreachable("Support above i8 vector type");
2151 }
2152 }
2153
2154 // Ops[0] = Component Type ID
2155 // Ops[1] = Component Count (Literal Number)
David Neto257c3892018-04-11 13:19:45 -04002156 SPIRVOperandList Ops;
2157 Ops << MkId(lookupType(Ty->getVectorElementType()))
2158 << MkNum(Ty->getVectorNumElements());
David Neto22f144c2017-06-12 14:26:21 -04002159
alan-bakerb6b09dc2018-11-08 16:59:28 -05002160 SPIRVInstruction *inst =
2161 new SPIRVInstruction(spv::OpTypeVector, nextID++, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002162 SPIRVInstList.push_back(inst);
David Neto22f144c2017-06-12 14:26:21 -04002163 break;
2164 }
2165 case Type::VoidTyID: {
David Neto87846742018-04-11 17:36:22 -04002166 auto *Inst = new SPIRVInstruction(spv::OpTypeVoid, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04002167 SPIRVInstList.push_back(Inst);
2168 break;
2169 }
2170 case Type::FunctionTyID: {
2171 // Generate SPIRV instruction for function type.
2172 FunctionType *FTy = cast<FunctionType>(Ty);
2173
2174 // Ops[0] = Return Type ID
2175 // Ops[1] ... Ops[n] = Parameter Type IDs
2176 SPIRVOperandList Ops;
2177
2178 // Find SPIRV instruction for return type
David Netoc6f3ab22018-04-06 18:02:31 -04002179 Ops << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04002180
2181 // Find SPIRV instructions for parameter types
2182 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
2183 // Find SPIRV instruction for parameter type.
2184 auto ParamTy = FTy->getParamType(k);
2185 if (ParamTy->isPointerTy()) {
2186 auto PointeeTy = ParamTy->getPointerElementType();
2187 if (PointeeTy->isStructTy() &&
2188 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
2189 ParamTy = PointeeTy;
2190 }
2191 }
2192
David Netoc6f3ab22018-04-06 18:02:31 -04002193 Ops << MkId(lookupType(ParamTy));
David Neto22f144c2017-06-12 14:26:21 -04002194 }
2195
David Neto87846742018-04-11 17:36:22 -04002196 auto *Inst = new SPIRVInstruction(spv::OpTypeFunction, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002197 SPIRVInstList.push_back(Inst);
2198 break;
2199 }
2200 }
2201 }
2202
2203 // Generate OpTypeSampledImage.
2204 TypeMapType &OpImageTypeMap = getImageTypeMap();
2205 for (auto &ImageType : OpImageTypeMap) {
2206 //
2207 // Generate OpTypeSampledImage.
2208 //
2209 // Ops[0] = Image Type ID
2210 //
2211 SPIRVOperandList Ops;
2212
2213 Type *ImgTy = ImageType.first;
David Netoc6f3ab22018-04-06 18:02:31 -04002214 Ops << MkId(TypeMap[ImgTy]);
David Neto22f144c2017-06-12 14:26:21 -04002215
2216 // Update OpImageTypeMap.
2217 ImageType.second = nextID;
2218
David Neto87846742018-04-11 17:36:22 -04002219 auto *Inst = new SPIRVInstruction(spv::OpTypeSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002220 SPIRVInstList.push_back(Inst);
2221 }
David Netoc6f3ab22018-04-06 18:02:31 -04002222
2223 // Generate types for pointer-to-local arguments.
Alan Baker202c8c72018-08-13 13:47:44 -04002224 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2225 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002226 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002227
2228 // Generate the spec constant.
2229 SPIRVOperandList Ops;
2230 Ops << MkId(lookupType(Type::getInt32Ty(Context))) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04002231 SPIRVInstList.push_back(
2232 new SPIRVInstruction(spv::OpSpecConstant, arg_info.array_size_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002233
2234 // Generate the array type.
2235 Ops.clear();
2236 // The element type must have been created.
2237 uint32_t elem_ty_id = lookupType(arg_info.elem_type);
2238 assert(elem_ty_id);
2239 Ops << MkId(elem_ty_id) << MkId(arg_info.array_size_id);
2240
2241 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002242 new SPIRVInstruction(spv::OpTypeArray, arg_info.array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002243
2244 Ops.clear();
2245 Ops << MkNum(spv::StorageClassWorkgroup) << MkId(arg_info.array_type_id);
David Neto87846742018-04-11 17:36:22 -04002246 SPIRVInstList.push_back(new SPIRVInstruction(
2247 spv::OpTypePointer, arg_info.ptr_array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002248 }
David Neto22f144c2017-06-12 14:26:21 -04002249}
2250
2251void SPIRVProducerPass::GenerateSPIRVConstants() {
2252 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2253 ValueMapType &VMap = getValueMap();
2254 ValueMapType &AllocatedVMap = getAllocatedValueMap();
2255 ValueList &CstList = getConstantList();
David Neto482550a2018-03-24 05:21:07 -07002256 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04002257
2258 for (uint32_t i = 0; i < CstList.size(); i++) {
David Netofb9a7972017-08-25 17:08:24 -04002259 // UniqueVector ids are 1-based.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002260 Constant *Cst = cast<Constant>(CstList[i + 1]);
David Neto22f144c2017-06-12 14:26:21 -04002261
2262 // OpTypeArray's constant was already generated.
David Netofb9a7972017-08-25 17:08:24 -04002263 if (AllocatedVMap.find_as(Cst) != AllocatedVMap.end()) {
David Neto22f144c2017-06-12 14:26:21 -04002264 continue;
2265 }
2266
David Netofb9a7972017-08-25 17:08:24 -04002267 // Set ValueMap with nextID for reference later.
David Neto22f144c2017-06-12 14:26:21 -04002268 VMap[Cst] = nextID;
2269
2270 //
2271 // Generate OpConstant.
2272 //
2273
2274 // Ops[0] = Result Type ID
2275 // Ops[1] .. Ops[n] = Values LiteralNumber
2276 SPIRVOperandList Ops;
2277
David Neto257c3892018-04-11 13:19:45 -04002278 Ops << MkId(lookupType(Cst->getType()));
David Neto22f144c2017-06-12 14:26:21 -04002279
2280 std::vector<uint32_t> LiteralNum;
David Neto22f144c2017-06-12 14:26:21 -04002281 spv::Op Opcode = spv::OpNop;
2282
2283 if (isa<UndefValue>(Cst)) {
2284 // Ops[0] = Result Type ID
David Netoc66b3352017-10-20 14:28:46 -04002285 Opcode = spv::OpUndef;
Alan Baker9bf93fb2018-08-28 16:59:26 -04002286 if (hack_undef && IsTypeNullable(Cst->getType())) {
2287 Opcode = spv::OpConstantNull;
David Netoc66b3352017-10-20 14:28:46 -04002288 }
David Neto22f144c2017-06-12 14:26:21 -04002289 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
2290 unsigned BitWidth = CI->getBitWidth();
2291 if (BitWidth == 1) {
2292 // If the bitwidth of constant is 1, generate OpConstantTrue or
2293 // OpConstantFalse.
2294 if (CI->getZExtValue()) {
2295 // Ops[0] = Result Type ID
2296 Opcode = spv::OpConstantTrue;
2297 } else {
2298 // Ops[0] = Result Type ID
2299 Opcode = spv::OpConstantFalse;
2300 }
David Neto22f144c2017-06-12 14:26:21 -04002301 } else {
2302 auto V = CI->getZExtValue();
2303 LiteralNum.push_back(V & 0xFFFFFFFF);
2304
2305 if (BitWidth > 32) {
2306 LiteralNum.push_back(V >> 32);
2307 }
2308
2309 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002310
David Neto257c3892018-04-11 13:19:45 -04002311 Ops << MkInteger(LiteralNum);
2312
2313 if (BitWidth == 32 && V == 0) {
2314 constant_i32_zero_id_ = nextID;
2315 }
David Neto22f144c2017-06-12 14:26:21 -04002316 }
2317 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2318 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2319 Type *CFPTy = CFP->getType();
2320 if (CFPTy->isFloatTy()) {
2321 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
Kévin Petit02ee34e2019-04-04 19:03:22 +01002322 } else if (CFPTy->isDoubleTy()) {
2323 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2324 LiteralNum.push_back(FPVal >> 32);
David Neto22f144c2017-06-12 14:26:21 -04002325 } else {
2326 CFPTy->print(errs());
2327 llvm_unreachable("Implement this ConstantFP Type");
2328 }
2329
2330 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002331
David Neto257c3892018-04-11 13:19:45 -04002332 Ops << MkFloat(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002333 } else if (isa<ConstantDataSequential>(Cst) &&
2334 cast<ConstantDataSequential>(Cst)->isString()) {
2335 Cst->print(errs());
2336 llvm_unreachable("Implement this Constant");
2337
2338 } else if (const ConstantDataSequential *CDS =
2339 dyn_cast<ConstantDataSequential>(Cst)) {
David Neto49351ac2017-08-26 17:32:20 -04002340 // Let's convert <4 x i8> constant to int constant specially.
2341 // This case occurs when all the values are specified as constant
2342 // ints.
2343 Type *CstTy = Cst->getType();
2344 if (is4xi8vec(CstTy)) {
2345 LLVMContext &Context = CstTy->getContext();
2346
2347 //
2348 // Generate OpConstant with OpTypeInt 32 0.
2349 //
Neil Henning39672102017-09-29 14:33:13 +01002350 uint32_t IntValue = 0;
2351 for (unsigned k = 0; k < 4; k++) {
2352 const uint64_t Val = CDS->getElementAsInteger(k);
David Neto49351ac2017-08-26 17:32:20 -04002353 IntValue = (IntValue << 8) | (Val & 0xffu);
2354 }
2355
2356 Type *i32 = Type::getInt32Ty(Context);
2357 Constant *CstInt = ConstantInt::get(i32, IntValue);
2358 // If this constant is already registered on VMap, use it.
2359 if (VMap.count(CstInt)) {
2360 uint32_t CstID = VMap[CstInt];
2361 VMap[Cst] = CstID;
2362 continue;
2363 }
2364
David Neto257c3892018-04-11 13:19:45 -04002365 Ops << MkNum(IntValue);
David Neto49351ac2017-08-26 17:32:20 -04002366
David Neto87846742018-04-11 17:36:22 -04002367 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto49351ac2017-08-26 17:32:20 -04002368 SPIRVInstList.push_back(CstInst);
2369
2370 continue;
2371 }
2372
2373 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002374 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
2375 Constant *EleCst = CDS->getElementAsConstant(k);
2376 uint32_t EleCstID = VMap[EleCst];
David Neto257c3892018-04-11 13:19:45 -04002377 Ops << MkId(EleCstID);
David Neto22f144c2017-06-12 14:26:21 -04002378 }
2379
2380 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002381 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2382 // Let's convert <4 x i8> constant to int constant specially.
David Neto49351ac2017-08-26 17:32:20 -04002383 // This case occurs when at least one of the values is an undef.
David Neto22f144c2017-06-12 14:26:21 -04002384 Type *CstTy = Cst->getType();
2385 if (is4xi8vec(CstTy)) {
2386 LLVMContext &Context = CstTy->getContext();
2387
2388 //
2389 // Generate OpConstant with OpTypeInt 32 0.
2390 //
Neil Henning39672102017-09-29 14:33:13 +01002391 uint32_t IntValue = 0;
David Neto22f144c2017-06-12 14:26:21 -04002392 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2393 I != E; ++I) {
2394 uint64_t Val = 0;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002395 const Value *CV = *I;
Neil Henning39672102017-09-29 14:33:13 +01002396 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2397 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002398 }
David Neto49351ac2017-08-26 17:32:20 -04002399 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002400 }
2401
David Neto49351ac2017-08-26 17:32:20 -04002402 Type *i32 = Type::getInt32Ty(Context);
2403 Constant *CstInt = ConstantInt::get(i32, IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002404 // If this constant is already registered on VMap, use it.
2405 if (VMap.count(CstInt)) {
2406 uint32_t CstID = VMap[CstInt];
2407 VMap[Cst] = CstID;
David Neto19a1bad2017-08-25 15:01:41 -04002408 continue;
David Neto22f144c2017-06-12 14:26:21 -04002409 }
2410
David Neto257c3892018-04-11 13:19:45 -04002411 Ops << MkNum(IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002412
David Neto87846742018-04-11 17:36:22 -04002413 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002414 SPIRVInstList.push_back(CstInst);
2415
David Neto19a1bad2017-08-25 15:01:41 -04002416 continue;
David Neto22f144c2017-06-12 14:26:21 -04002417 }
2418
2419 // We use a constant composite in SPIR-V for our constant aggregate in
2420 // LLVM.
2421 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002422
2423 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
2424 // Look up the ID of the element of this aggregate (which we will
2425 // previously have created a constant for).
2426 uint32_t ElementConstantID = VMap[CA->getAggregateElement(k)];
2427
2428 // And add an operand to the composite we are constructing
David Neto257c3892018-04-11 13:19:45 -04002429 Ops << MkId(ElementConstantID);
David Neto22f144c2017-06-12 14:26:21 -04002430 }
2431 } else if (Cst->isNullValue()) {
2432 Opcode = spv::OpConstantNull;
David Neto22f144c2017-06-12 14:26:21 -04002433 } else {
2434 Cst->print(errs());
2435 llvm_unreachable("Unsupported Constant???");
2436 }
2437
alan-baker5b86ed72019-02-15 08:26:50 -05002438 if (Opcode == spv::OpConstantNull && Cst->getType()->isPointerTy()) {
2439 // Null pointer requires variable pointers.
2440 setVariablePointersCapabilities(Cst->getType()->getPointerAddressSpace());
2441 }
2442
David Neto87846742018-04-11 17:36:22 -04002443 auto *CstInst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002444 SPIRVInstList.push_back(CstInst);
2445 }
2446}
2447
2448void SPIRVProducerPass::GenerateSamplers(Module &M) {
2449 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto22f144c2017-06-12 14:26:21 -04002450
alan-bakerb6b09dc2018-11-08 16:59:28 -05002451 auto &sampler_map = getSamplerMap();
David Neto862b7d82018-06-14 18:48:37 -04002452 SamplerMapIndexToIDMap.clear();
David Neto22f144c2017-06-12 14:26:21 -04002453 DenseMap<unsigned, unsigned> SamplerLiteralToIDMap;
David Neto862b7d82018-06-14 18:48:37 -04002454 DenseMap<unsigned, unsigned> SamplerLiteralToDescriptorSetMap;
2455 DenseMap<unsigned, unsigned> SamplerLiteralToBindingMap;
David Neto22f144c2017-06-12 14:26:21 -04002456
David Neto862b7d82018-06-14 18:48:37 -04002457 // We might have samplers in the sampler map that are not used
2458 // in the translation unit. We need to allocate variables
2459 // for them and bindings too.
2460 DenseSet<unsigned> used_bindings;
David Neto22f144c2017-06-12 14:26:21 -04002461
alan-bakerb6b09dc2018-11-08 16:59:28 -05002462 auto *var_fn = M.getFunction("clspv.sampler.var.literal");
2463 if (!var_fn)
2464 return;
David Neto862b7d82018-06-14 18:48:37 -04002465 for (auto user : var_fn->users()) {
2466 // Populate SamplerLiteralToDescriptorSetMap and
2467 // SamplerLiteralToBindingMap.
2468 //
2469 // Look for calls like
2470 // call %opencl.sampler_t addrspace(2)*
2471 // @clspv.sampler.var.literal(
2472 // i32 descriptor,
2473 // i32 binding,
2474 // i32 index-into-sampler-map)
alan-bakerb6b09dc2018-11-08 16:59:28 -05002475 if (auto *call = dyn_cast<CallInst>(user)) {
2476 const size_t index_into_sampler_map = static_cast<size_t>(
2477 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04002478 if (index_into_sampler_map >= sampler_map.size()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002479 errs() << "Out of bounds index to sampler map: "
2480 << index_into_sampler_map;
David Neto862b7d82018-06-14 18:48:37 -04002481 llvm_unreachable("bad sampler init: out of bounds");
2482 }
2483
2484 auto sampler_value = sampler_map[index_into_sampler_map].first;
2485 const auto descriptor_set = static_cast<unsigned>(
2486 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
2487 const auto binding = static_cast<unsigned>(
2488 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
2489
2490 SamplerLiteralToDescriptorSetMap[sampler_value] = descriptor_set;
2491 SamplerLiteralToBindingMap[sampler_value] = binding;
2492 used_bindings.insert(binding);
2493 }
2494 }
2495
2496 unsigned index = 0;
2497 for (auto SamplerLiteral : sampler_map) {
David Neto22f144c2017-06-12 14:26:21 -04002498 // Generate OpVariable.
2499 //
2500 // GIDOps[0] : Result Type ID
2501 // GIDOps[1] : Storage Class
2502 SPIRVOperandList Ops;
2503
David Neto257c3892018-04-11 13:19:45 -04002504 Ops << MkId(lookupType(SamplerTy))
2505 << MkNum(spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002506
David Neto862b7d82018-06-14 18:48:37 -04002507 auto sampler_var_id = nextID++;
2508 auto *Inst = new SPIRVInstruction(spv::OpVariable, sampler_var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002509 SPIRVInstList.push_back(Inst);
2510
David Neto862b7d82018-06-14 18:48:37 -04002511 SamplerMapIndexToIDMap[index] = sampler_var_id;
2512 SamplerLiteralToIDMap[SamplerLiteral.first] = sampler_var_id;
David Neto22f144c2017-06-12 14:26:21 -04002513
2514 // Find Insert Point for OpDecorate.
2515 auto DecoInsertPoint =
2516 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2517 [](SPIRVInstruction *Inst) -> bool {
2518 return Inst->getOpcode() != spv::OpDecorate &&
2519 Inst->getOpcode() != spv::OpMemberDecorate &&
2520 Inst->getOpcode() != spv::OpExtInstImport;
2521 });
2522
2523 // Ops[0] = Target ID
2524 // Ops[1] = Decoration (DescriptorSet)
2525 // Ops[2] = LiteralNumber according to Decoration
2526 Ops.clear();
2527
David Neto862b7d82018-06-14 18:48:37 -04002528 unsigned descriptor_set;
2529 unsigned binding;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002530 if (SamplerLiteralToBindingMap.find(SamplerLiteral.first) ==
2531 SamplerLiteralToBindingMap.end()) {
David Neto862b7d82018-06-14 18:48:37 -04002532 // This sampler is not actually used. Find the next one.
2533 for (binding = 0; used_bindings.count(binding); binding++)
2534 ;
2535 descriptor_set = 0; // Literal samplers always use descriptor set 0.
2536 used_bindings.insert(binding);
2537 } else {
2538 descriptor_set = SamplerLiteralToDescriptorSetMap[SamplerLiteral.first];
2539 binding = SamplerLiteralToBindingMap[SamplerLiteral.first];
2540 }
2541
2542 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationDescriptorSet)
2543 << MkNum(descriptor_set);
David Neto22f144c2017-06-12 14:26:21 -04002544
alan-bakerf5e5f692018-11-27 08:33:24 -05002545 version0::DescriptorMapEntry::SamplerData sampler_data = {SamplerLiteral.first};
2546 descriptorMapEntries->emplace_back(std::move(sampler_data), descriptor_set, binding);
David Neto22f144c2017-06-12 14:26:21 -04002547
David Neto87846742018-04-11 17:36:22 -04002548 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002549 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2550
2551 // Ops[0] = Target ID
2552 // Ops[1] = Decoration (Binding)
2553 // Ops[2] = LiteralNumber according to Decoration
2554 Ops.clear();
David Neto862b7d82018-06-14 18:48:37 -04002555 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationBinding)
2556 << MkNum(binding);
David Neto22f144c2017-06-12 14:26:21 -04002557
David Neto87846742018-04-11 17:36:22 -04002558 auto *BindDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002559 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
David Neto862b7d82018-06-14 18:48:37 -04002560
2561 index++;
David Neto22f144c2017-06-12 14:26:21 -04002562 }
David Neto862b7d82018-06-14 18:48:37 -04002563}
David Neto22f144c2017-06-12 14:26:21 -04002564
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01002565void SPIRVProducerPass::GenerateResourceVars(Module &) {
David Neto862b7d82018-06-14 18:48:37 -04002566 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2567 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04002568
David Neto862b7d82018-06-14 18:48:37 -04002569 // Generate variables. Make one for each of resource var info object.
2570 for (auto *info : ModuleOrderedResourceVars) {
2571 Type *type = info->var_fn->getReturnType();
2572 // Remap the address space for opaque types.
2573 switch (info->arg_kind) {
2574 case clspv::ArgKind::Sampler:
2575 case clspv::ArgKind::ReadOnlyImage:
2576 case clspv::ArgKind::WriteOnlyImage:
2577 type = PointerType::get(type->getPointerElementType(),
2578 clspv::AddressSpace::UniformConstant);
2579 break;
2580 default:
2581 break;
2582 }
David Neto22f144c2017-06-12 14:26:21 -04002583
David Neto862b7d82018-06-14 18:48:37 -04002584 info->var_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04002585
David Neto862b7d82018-06-14 18:48:37 -04002586 const auto type_id = lookupType(type);
2587 const auto sc = GetStorageClassForArgKind(info->arg_kind);
2588 SPIRVOperandList Ops;
2589 Ops << MkId(type_id) << MkNum(sc);
David Neto22f144c2017-06-12 14:26:21 -04002590
David Neto862b7d82018-06-14 18:48:37 -04002591 auto *Inst = new SPIRVInstruction(spv::OpVariable, info->var_id, Ops);
2592 SPIRVInstList.push_back(Inst);
2593
2594 // Map calls to the variable-builtin-function.
2595 for (auto &U : info->var_fn->uses()) {
2596 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
2597 const auto set = unsigned(
2598 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
2599 const auto binding = unsigned(
2600 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
2601 if (set == info->descriptor_set && binding == info->binding) {
2602 switch (info->arg_kind) {
2603 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002604 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002605 case clspv::ArgKind::Pod:
2606 // The call maps to the variable directly.
2607 VMap[call] = info->var_id;
2608 break;
2609 case clspv::ArgKind::Sampler:
2610 case clspv::ArgKind::ReadOnlyImage:
2611 case clspv::ArgKind::WriteOnlyImage:
2612 // The call maps to a load we generate later.
2613 ResourceVarDeferredLoadCalls[call] = info->var_id;
2614 break;
2615 default:
2616 llvm_unreachable("Unhandled arg kind");
2617 }
2618 }
David Neto22f144c2017-06-12 14:26:21 -04002619 }
David Neto862b7d82018-06-14 18:48:37 -04002620 }
2621 }
David Neto22f144c2017-06-12 14:26:21 -04002622
David Neto862b7d82018-06-14 18:48:37 -04002623 // Generate associated decorations.
David Neto22f144c2017-06-12 14:26:21 -04002624
David Neto862b7d82018-06-14 18:48:37 -04002625 // Find Insert Point for OpDecorate.
2626 auto DecoInsertPoint =
2627 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2628 [](SPIRVInstruction *Inst) -> bool {
2629 return Inst->getOpcode() != spv::OpDecorate &&
2630 Inst->getOpcode() != spv::OpMemberDecorate &&
2631 Inst->getOpcode() != spv::OpExtInstImport;
2632 });
2633
2634 SPIRVOperandList Ops;
2635 for (auto *info : ModuleOrderedResourceVars) {
2636 // Decorate with DescriptorSet and Binding.
2637 Ops.clear();
2638 Ops << MkId(info->var_id) << MkNum(spv::DecorationDescriptorSet)
2639 << MkNum(info->descriptor_set);
2640 SPIRVInstList.insert(DecoInsertPoint,
2641 new SPIRVInstruction(spv::OpDecorate, Ops));
2642
2643 Ops.clear();
2644 Ops << MkId(info->var_id) << MkNum(spv::DecorationBinding)
2645 << MkNum(info->binding);
2646 SPIRVInstList.insert(DecoInsertPoint,
2647 new SPIRVInstruction(spv::OpDecorate, Ops));
2648
alan-bakere9308012019-03-15 10:25:13 -04002649 if (info->coherent) {
2650 // Decorate with Coherent if required for the variable.
2651 Ops.clear();
2652 Ops << MkId(info->var_id) << MkNum(spv::DecorationCoherent);
2653 SPIRVInstList.insert(DecoInsertPoint,
2654 new SPIRVInstruction(spv::OpDecorate, Ops));
2655 }
2656
David Neto862b7d82018-06-14 18:48:37 -04002657 // Generate NonWritable and NonReadable
2658 switch (info->arg_kind) {
2659 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002660 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002661 if (info->var_fn->getReturnType()->getPointerAddressSpace() ==
2662 clspv::AddressSpace::Constant) {
2663 Ops.clear();
2664 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
2665 SPIRVInstList.insert(DecoInsertPoint,
2666 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002667 }
David Neto862b7d82018-06-14 18:48:37 -04002668 break;
David Neto862b7d82018-06-14 18:48:37 -04002669 case clspv::ArgKind::WriteOnlyImage:
2670 Ops.clear();
2671 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonReadable);
2672 SPIRVInstList.insert(DecoInsertPoint,
2673 new SPIRVInstruction(spv::OpDecorate, Ops));
2674 break;
2675 default:
2676 break;
David Neto22f144c2017-06-12 14:26:21 -04002677 }
2678 }
2679}
2680
2681void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002682 Module &M = *GV.getParent();
David Neto22f144c2017-06-12 14:26:21 -04002683 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2684 ValueMapType &VMap = getValueMap();
2685 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07002686 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002687
2688 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2689 Type *Ty = GV.getType();
2690 PointerType *PTy = cast<PointerType>(Ty);
2691
2692 uint32_t InitializerID = 0;
2693
2694 // Workgroup size is handled differently (it goes into a constant)
2695 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2696 std::vector<bool> HasMDVec;
2697 uint32_t PrevXDimCst = 0xFFFFFFFF;
2698 uint32_t PrevYDimCst = 0xFFFFFFFF;
2699 uint32_t PrevZDimCst = 0xFFFFFFFF;
2700 for (Function &Func : *GV.getParent()) {
2701 if (Func.isDeclaration()) {
2702 continue;
2703 }
2704
2705 // We only need to check kernels.
2706 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2707 continue;
2708 }
2709
2710 if (const MDNode *MD =
2711 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2712 uint32_t CurXDimCst = static_cast<uint32_t>(
2713 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2714 uint32_t CurYDimCst = static_cast<uint32_t>(
2715 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2716 uint32_t CurZDimCst = static_cast<uint32_t>(
2717 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2718
2719 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2720 PrevZDimCst == 0xFFFFFFFF) {
2721 PrevXDimCst = CurXDimCst;
2722 PrevYDimCst = CurYDimCst;
2723 PrevZDimCst = CurZDimCst;
2724 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2725 CurZDimCst != PrevZDimCst) {
2726 llvm_unreachable(
2727 "reqd_work_group_size must be the same across all kernels");
2728 } else {
2729 continue;
2730 }
2731
2732 //
2733 // Generate OpConstantComposite.
2734 //
2735 // Ops[0] : Result Type ID
2736 // Ops[1] : Constant size for x dimension.
2737 // Ops[2] : Constant size for y dimension.
2738 // Ops[3] : Constant size for z dimension.
2739 SPIRVOperandList Ops;
2740
2741 uint32_t XDimCstID =
2742 VMap[mdconst::extract<ConstantInt>(MD->getOperand(0))];
2743 uint32_t YDimCstID =
2744 VMap[mdconst::extract<ConstantInt>(MD->getOperand(1))];
2745 uint32_t ZDimCstID =
2746 VMap[mdconst::extract<ConstantInt>(MD->getOperand(2))];
2747
2748 InitializerID = nextID;
2749
David Neto257c3892018-04-11 13:19:45 -04002750 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2751 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002752
David Neto87846742018-04-11 17:36:22 -04002753 auto *Inst =
2754 new SPIRVInstruction(spv::OpConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002755 SPIRVInstList.push_back(Inst);
2756
2757 HasMDVec.push_back(true);
2758 } else {
2759 HasMDVec.push_back(false);
2760 }
2761 }
2762
2763 // Check all kernels have same definitions for work_group_size.
2764 bool HasMD = false;
2765 if (!HasMDVec.empty()) {
2766 HasMD = HasMDVec[0];
2767 for (uint32_t i = 1; i < HasMDVec.size(); i++) {
2768 if (HasMD != HasMDVec[i]) {
2769 llvm_unreachable(
2770 "Kernels should have consistent work group size definition");
2771 }
2772 }
2773 }
2774
2775 // If all kernels do not have metadata for reqd_work_group_size, generate
2776 // OpSpecConstants for x/y/z dimension.
2777 if (!HasMD) {
2778 //
2779 // Generate OpSpecConstants for x/y/z dimension.
2780 //
2781 // Ops[0] : Result Type ID
2782 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
2783 uint32_t XDimCstID = 0;
2784 uint32_t YDimCstID = 0;
2785 uint32_t ZDimCstID = 0;
2786
David Neto22f144c2017-06-12 14:26:21 -04002787 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04002788 uint32_t result_type_id =
2789 lookupType(Ty->getPointerElementType()->getSequentialElementType());
David Neto22f144c2017-06-12 14:26:21 -04002790
David Neto257c3892018-04-11 13:19:45 -04002791 // X Dimension
2792 Ops << MkId(result_type_id) << MkNum(1);
2793 XDimCstID = nextID++;
2794 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002795 new SPIRVInstruction(spv::OpSpecConstant, XDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002796
2797 // Y Dimension
2798 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002799 Ops << MkId(result_type_id) << MkNum(1);
2800 YDimCstID = nextID++;
2801 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002802 new SPIRVInstruction(spv::OpSpecConstant, YDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002803
2804 // Z Dimension
2805 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002806 Ops << MkId(result_type_id) << MkNum(1);
2807 ZDimCstID = nextID++;
2808 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002809 new SPIRVInstruction(spv::OpSpecConstant, ZDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002810
David Neto257c3892018-04-11 13:19:45 -04002811 BuiltinDimVec.push_back(XDimCstID);
2812 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002813 BuiltinDimVec.push_back(ZDimCstID);
2814
David Neto22f144c2017-06-12 14:26:21 -04002815 //
2816 // Generate OpSpecConstantComposite.
2817 //
2818 // Ops[0] : Result Type ID
2819 // Ops[1] : Constant size for x dimension.
2820 // Ops[2] : Constant size for y dimension.
2821 // Ops[3] : Constant size for z dimension.
2822 InitializerID = nextID;
2823
2824 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002825 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2826 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002827
David Neto87846742018-04-11 17:36:22 -04002828 auto *Inst =
2829 new SPIRVInstruction(spv::OpSpecConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002830 SPIRVInstList.push_back(Inst);
2831 }
2832 }
2833
David Neto22f144c2017-06-12 14:26:21 -04002834 VMap[&GV] = nextID;
2835
2836 //
2837 // Generate OpVariable.
2838 //
2839 // GIDOps[0] : Result Type ID
2840 // GIDOps[1] : Storage Class
2841 SPIRVOperandList Ops;
2842
David Neto85082642018-03-24 06:55:20 -07002843 const auto AS = PTy->getAddressSpace();
David Netoc6f3ab22018-04-06 18:02:31 -04002844 Ops << MkId(lookupType(Ty)) << MkNum(GetStorageClass(AS));
David Neto22f144c2017-06-12 14:26:21 -04002845
David Neto85082642018-03-24 06:55:20 -07002846 if (GV.hasInitializer()) {
2847 InitializerID = VMap[GV.getInitializer()];
David Neto22f144c2017-06-12 14:26:21 -04002848 }
2849
David Neto85082642018-03-24 06:55:20 -07002850 const bool module_scope_constant_external_init =
David Neto862b7d82018-06-14 18:48:37 -04002851 (AS == AddressSpace::Constant) && GV.hasInitializer() &&
David Neto85082642018-03-24 06:55:20 -07002852 clspv::Option::ModuleConstantsInStorageBuffer();
2853
2854 if (0 != InitializerID) {
2855 if (!module_scope_constant_external_init) {
2856 // Emit the ID of the intiializer as part of the variable definition.
David Netoc6f3ab22018-04-06 18:02:31 -04002857 Ops << MkId(InitializerID);
David Neto85082642018-03-24 06:55:20 -07002858 }
2859 }
2860 const uint32_t var_id = nextID++;
2861
David Neto87846742018-04-11 17:36:22 -04002862 auto *Inst = new SPIRVInstruction(spv::OpVariable, var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002863 SPIRVInstList.push_back(Inst);
2864
2865 // If we have a builtin.
2866 if (spv::BuiltInMax != BuiltinType) {
2867 // Find Insert Point for OpDecorate.
2868 auto DecoInsertPoint =
2869 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2870 [](SPIRVInstruction *Inst) -> bool {
2871 return Inst->getOpcode() != spv::OpDecorate &&
2872 Inst->getOpcode() != spv::OpMemberDecorate &&
2873 Inst->getOpcode() != spv::OpExtInstImport;
2874 });
2875 //
2876 // Generate OpDecorate.
2877 //
2878 // DOps[0] = Target ID
2879 // DOps[1] = Decoration (Builtin)
2880 // DOps[2] = BuiltIn ID
2881 uint32_t ResultID;
2882
2883 // WorkgroupSize is different, we decorate the constant composite that has
2884 // its value, rather than the variable that we use to access the value.
2885 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2886 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04002887 // Save both the value and variable IDs for later.
2888 WorkgroupSizeValueID = InitializerID;
2889 WorkgroupSizeVarID = VMap[&GV];
David Neto22f144c2017-06-12 14:26:21 -04002890 } else {
2891 ResultID = VMap[&GV];
2892 }
2893
2894 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002895 DOps << MkId(ResultID) << MkNum(spv::DecorationBuiltIn)
2896 << MkNum(BuiltinType);
David Neto22f144c2017-06-12 14:26:21 -04002897
David Neto87846742018-04-11 17:36:22 -04002898 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, DOps);
David Neto22f144c2017-06-12 14:26:21 -04002899 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
David Neto85082642018-03-24 06:55:20 -07002900 } else if (module_scope_constant_external_init) {
2901 // This module scope constant is initialized from a storage buffer with data
2902 // provided by the host at binding 0 of the next descriptor set.
David Neto78383442018-06-15 20:31:56 -04002903 const uint32_t descriptor_set = TakeDescriptorIndex(&M);
David Neto85082642018-03-24 06:55:20 -07002904
David Neto862b7d82018-06-14 18:48:37 -04002905 // Emit the intializer to the descriptor map file.
David Neto85082642018-03-24 06:55:20 -07002906 // Use "kind,buffer" to indicate storage buffer. We might want to expand
2907 // that later to other types, like uniform buffer.
alan-bakerf5e5f692018-11-27 08:33:24 -05002908 std::string hexbytes;
2909 llvm::raw_string_ostream str(hexbytes);
2910 clspv::ConstantEmitter(DL, str).Emit(GV.getInitializer());
2911 version0::DescriptorMapEntry::ConstantData constant_data = {ArgKind::Buffer, str.str()};
2912 descriptorMapEntries->emplace_back(std::move(constant_data), descriptor_set, 0);
David Neto85082642018-03-24 06:55:20 -07002913
2914 // Find Insert Point for OpDecorate.
2915 auto DecoInsertPoint =
2916 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2917 [](SPIRVInstruction *Inst) -> bool {
2918 return Inst->getOpcode() != spv::OpDecorate &&
2919 Inst->getOpcode() != spv::OpMemberDecorate &&
2920 Inst->getOpcode() != spv::OpExtInstImport;
2921 });
2922
David Neto257c3892018-04-11 13:19:45 -04002923 // OpDecorate %var Binding <binding>
David Neto85082642018-03-24 06:55:20 -07002924 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002925 DOps << MkId(var_id) << MkNum(spv::DecorationBinding) << MkNum(0);
2926 DecoInsertPoint = SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04002927 DecoInsertPoint, new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto85082642018-03-24 06:55:20 -07002928
2929 // OpDecorate %var DescriptorSet <descriptor_set>
2930 DOps.clear();
David Neto257c3892018-04-11 13:19:45 -04002931 DOps << MkId(var_id) << MkNum(spv::DecorationDescriptorSet)
2932 << MkNum(descriptor_set);
David Netoc6f3ab22018-04-06 18:02:31 -04002933 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04002934 new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto22f144c2017-06-12 14:26:21 -04002935 }
2936}
2937
David Netoc6f3ab22018-04-06 18:02:31 -04002938void SPIRVProducerPass::GenerateWorkgroupVars() {
2939 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
Alan Baker202c8c72018-08-13 13:47:44 -04002940 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2941 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002942 LocalArgInfo &info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002943
2944 // Generate OpVariable.
2945 //
2946 // GIDOps[0] : Result Type ID
2947 // GIDOps[1] : Storage Class
2948 SPIRVOperandList Ops;
2949 Ops << MkId(info.ptr_array_type_id) << MkNum(spv::StorageClassWorkgroup);
2950
2951 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002952 new SPIRVInstruction(spv::OpVariable, info.variable_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002953 }
2954}
2955
David Neto862b7d82018-06-14 18:48:37 -04002956void SPIRVProducerPass::GenerateDescriptorMapInfo(const DataLayout &DL,
2957 Function &F) {
David Netoc5fb5242018-07-30 13:28:31 -04002958 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2959 return;
2960 }
David Neto862b7d82018-06-14 18:48:37 -04002961 // Gather the list of resources that are used by this function's arguments.
2962 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
2963
alan-bakerf5e5f692018-11-27 08:33:24 -05002964 // TODO(alan-baker): This should become unnecessary by fixing the rest of the
2965 // flow to generate pod_ubo arguments earlier.
David Neto862b7d82018-06-14 18:48:37 -04002966 auto remap_arg_kind = [](StringRef argKind) {
alan-bakerf5e5f692018-11-27 08:33:24 -05002967 std::string kind =
2968 clspv::Option::PodArgsInUniformBuffer() && argKind.equals("pod")
2969 ? "pod_ubo"
2970 : argKind;
2971 return GetArgKindFromName(kind);
David Neto862b7d82018-06-14 18:48:37 -04002972 };
2973
2974 auto *fty = F.getType()->getPointerElementType();
2975 auto *func_ty = dyn_cast<FunctionType>(fty);
2976
2977 // If we've clustereed POD arguments, then argument details are in metadata.
2978 // If an argument maps to a resource variable, then get descriptor set and
2979 // binding from the resoure variable. Other info comes from the metadata.
2980 const auto *arg_map = F.getMetadata("kernel_arg_map");
2981 if (arg_map) {
2982 for (const auto &arg : arg_map->operands()) {
2983 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
Kévin PETITa353c832018-03-20 23:21:21 +00002984 assert(arg_node->getNumOperands() == 7);
David Neto862b7d82018-06-14 18:48:37 -04002985 const auto name =
2986 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
2987 const auto old_index =
2988 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
2989 // Remapped argument index
alan-bakerb6b09dc2018-11-08 16:59:28 -05002990 const size_t new_index = static_cast<size_t>(
2991 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04002992 const auto offset =
2993 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
Kévin PETITa353c832018-03-20 23:21:21 +00002994 const auto arg_size =
2995 dyn_extract<ConstantInt>(arg_node->getOperand(4))->getZExtValue();
David Neto862b7d82018-06-14 18:48:37 -04002996 const auto argKind = remap_arg_kind(
Kévin PETITa353c832018-03-20 23:21:21 +00002997 dyn_cast<MDString>(arg_node->getOperand(5))->getString());
David Neto862b7d82018-06-14 18:48:37 -04002998 const auto spec_id =
Kévin PETITa353c832018-03-20 23:21:21 +00002999 dyn_extract<ConstantInt>(arg_node->getOperand(6))->getSExtValue();
alan-bakerf5e5f692018-11-27 08:33:24 -05003000
3001 uint32_t descriptor_set = 0;
3002 uint32_t binding = 0;
3003 version0::DescriptorMapEntry::KernelArgData kernel_data = {
3004 F.getName(),
3005 name,
3006 static_cast<uint32_t>(old_index),
3007 argKind,
3008 static_cast<uint32_t>(spec_id),
3009 // This will be set below for pointer-to-local args.
3010 0,
3011 static_cast<uint32_t>(offset),
3012 static_cast<uint32_t>(arg_size)};
David Neto862b7d82018-06-14 18:48:37 -04003013 if (spec_id > 0) {
alan-bakerf5e5f692018-11-27 08:33:24 -05003014 kernel_data.local_element_size = static_cast<uint32_t>(GetTypeAllocSize(
3015 func_ty->getParamType(unsigned(new_index))->getPointerElementType(),
3016 DL));
David Neto862b7d82018-06-14 18:48:37 -04003017 } else {
3018 auto *info = resource_var_at_index[new_index];
3019 assert(info);
alan-bakerf5e5f692018-11-27 08:33:24 -05003020 descriptor_set = info->descriptor_set;
3021 binding = info->binding;
David Neto862b7d82018-06-14 18:48:37 -04003022 }
alan-bakerf5e5f692018-11-27 08:33:24 -05003023 descriptorMapEntries->emplace_back(std::move(kernel_data), descriptor_set, binding);
David Neto862b7d82018-06-14 18:48:37 -04003024 }
3025 } else {
3026 // There is no argument map.
3027 // Take descriptor info from the resource variable calls.
Kévin PETITa353c832018-03-20 23:21:21 +00003028 // Take argument name and size from the arguments list.
David Neto862b7d82018-06-14 18:48:37 -04003029
3030 SmallVector<Argument *, 4> arguments;
3031 for (auto &arg : F.args()) {
3032 arguments.push_back(&arg);
3033 }
3034
3035 unsigned arg_index = 0;
3036 for (auto *info : resource_var_at_index) {
3037 if (info) {
Kévin PETITa353c832018-03-20 23:21:21 +00003038 auto arg = arguments[arg_index];
alan-bakerb6b09dc2018-11-08 16:59:28 -05003039 unsigned arg_size = 0;
Kévin PETITa353c832018-03-20 23:21:21 +00003040 if (info->arg_kind == clspv::ArgKind::Pod) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05003041 arg_size = static_cast<uint32_t>(DL.getTypeStoreSize(arg->getType()));
Kévin PETITa353c832018-03-20 23:21:21 +00003042 }
3043
alan-bakerf5e5f692018-11-27 08:33:24 -05003044 // Local pointer arguments are unused in this case. Offset is always zero.
3045 version0::DescriptorMapEntry::KernelArgData kernel_data = {
3046 F.getName(), arg->getName(),
3047 arg_index, remap_arg_kind(clspv::GetArgKindName(info->arg_kind)),
3048 0, 0,
3049 0, arg_size};
3050 descriptorMapEntries->emplace_back(std::move(kernel_data),
3051 info->descriptor_set, info->binding);
David Neto862b7d82018-06-14 18:48:37 -04003052 }
3053 arg_index++;
3054 }
3055 // Generate mappings for pointer-to-local arguments.
3056 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
3057 Argument *arg = arguments[arg_index];
Alan Baker202c8c72018-08-13 13:47:44 -04003058 auto where = LocalArgSpecIds.find(arg);
3059 if (where != LocalArgSpecIds.end()) {
3060 auto &local_arg_info = LocalSpecIdInfoMap[where->second];
alan-bakerf5e5f692018-11-27 08:33:24 -05003061 // Pod arguments members are unused in this case.
3062 version0::DescriptorMapEntry::KernelArgData kernel_data = {
3063 F.getName(),
3064 arg->getName(),
3065 arg_index,
3066 ArgKind::Local,
3067 static_cast<uint32_t>(local_arg_info.spec_id),
3068 static_cast<uint32_t>(GetTypeAllocSize(local_arg_info.elem_type, DL)),
3069 0,
3070 0};
3071 // Pointer-to-local arguments do not utilize descriptor set and binding.
3072 descriptorMapEntries->emplace_back(std::move(kernel_data), 0, 0);
David Neto862b7d82018-06-14 18:48:37 -04003073 }
3074 }
3075 }
3076}
3077
David Neto22f144c2017-06-12 14:26:21 -04003078void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
3079 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3080 ValueMapType &VMap = getValueMap();
3081 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04003082 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
3083 auto &GlobalConstArgSet = getGlobalConstArgSet();
3084
3085 FunctionType *FTy = F.getFunctionType();
3086
3087 //
David Neto22f144c2017-06-12 14:26:21 -04003088 // Generate OPFunction.
3089 //
3090
3091 // FOps[0] : Result Type ID
3092 // FOps[1] : Function Control
3093 // FOps[2] : Function Type ID
3094 SPIRVOperandList FOps;
3095
3096 // Find SPIRV instruction for return type.
David Neto257c3892018-04-11 13:19:45 -04003097 FOps << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04003098
3099 // Check function attributes for SPIRV Function Control.
3100 uint32_t FuncControl = spv::FunctionControlMaskNone;
3101 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
3102 FuncControl |= spv::FunctionControlInlineMask;
3103 }
3104 if (F.hasFnAttribute(Attribute::NoInline)) {
3105 FuncControl |= spv::FunctionControlDontInlineMask;
3106 }
3107 // TODO: Check llvm attribute for Function Control Pure.
3108 if (F.hasFnAttribute(Attribute::ReadOnly)) {
3109 FuncControl |= spv::FunctionControlPureMask;
3110 }
3111 // TODO: Check llvm attribute for Function Control Const.
3112 if (F.hasFnAttribute(Attribute::ReadNone)) {
3113 FuncControl |= spv::FunctionControlConstMask;
3114 }
3115
David Neto257c3892018-04-11 13:19:45 -04003116 FOps << MkNum(FuncControl);
David Neto22f144c2017-06-12 14:26:21 -04003117
3118 uint32_t FTyID;
3119 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3120 SmallVector<Type *, 4> NewFuncParamTys;
3121 FunctionType *NewFTy =
3122 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
3123 FTyID = lookupType(NewFTy);
3124 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07003125 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04003126 if (GlobalConstFuncTyMap.count(FTy)) {
3127 FTyID = lookupType(GlobalConstFuncTyMap[FTy].first);
3128 } else {
3129 FTyID = lookupType(FTy);
3130 }
3131 }
3132
David Neto257c3892018-04-11 13:19:45 -04003133 FOps << MkId(FTyID);
David Neto22f144c2017-06-12 14:26:21 -04003134
3135 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3136 EntryPoints.push_back(std::make_pair(&F, nextID));
3137 }
3138
3139 VMap[&F] = nextID;
3140
David Neto482550a2018-03-24 05:21:07 -07003141 if (clspv::Option::ShowIDs()) {
David Netob05675d2018-02-16 12:37:49 -05003142 errs() << "Function " << F.getName() << " is " << nextID << "\n";
3143 }
David Neto22f144c2017-06-12 14:26:21 -04003144 // Generate SPIRV instruction for function.
David Neto87846742018-04-11 17:36:22 -04003145 auto *FuncInst = new SPIRVInstruction(spv::OpFunction, nextID++, FOps);
David Neto22f144c2017-06-12 14:26:21 -04003146 SPIRVInstList.push_back(FuncInst);
3147
3148 //
3149 // Generate OpFunctionParameter for Normal function.
3150 //
3151
3152 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
alan-bakere9308012019-03-15 10:25:13 -04003153
3154 // Find Insert Point for OpDecorate.
3155 auto DecoInsertPoint =
3156 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
3157 [](SPIRVInstruction *Inst) -> bool {
3158 return Inst->getOpcode() != spv::OpDecorate &&
3159 Inst->getOpcode() != spv::OpMemberDecorate &&
3160 Inst->getOpcode() != spv::OpExtInstImport;
3161 });
3162
David Neto22f144c2017-06-12 14:26:21 -04003163 // Iterate Argument for name instead of param type from function type.
3164 unsigned ArgIdx = 0;
3165 for (Argument &Arg : F.args()) {
alan-bakere9308012019-03-15 10:25:13 -04003166 uint32_t param_id = nextID++;
3167 VMap[&Arg] = param_id;
3168
3169 if (CalledWithCoherentResource(Arg)) {
3170 // If the arg is passed a coherent resource ever, then decorate this
3171 // parameter with Coherent too.
3172 SPIRVOperandList decoration_ops;
3173 decoration_ops << MkId(param_id) << MkNum(spv::DecorationCoherent);
3174 SPIRVInstList.insert(DecoInsertPoint,
3175 new SPIRVInstruction(spv::OpDecorate, decoration_ops));
3176 }
David Neto22f144c2017-06-12 14:26:21 -04003177
3178 // ParamOps[0] : Result Type ID
3179 SPIRVOperandList ParamOps;
3180
3181 // Find SPIRV instruction for parameter type.
3182 uint32_t ParamTyID = lookupType(Arg.getType());
3183 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
3184 if (GlobalConstFuncTyMap.count(FTy)) {
3185 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
3186 Type *EleTy = PTy->getPointerElementType();
3187 Type *ArgTy =
3188 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
3189 ParamTyID = lookupType(ArgTy);
3190 GlobalConstArgSet.insert(&Arg);
3191 }
3192 }
3193 }
David Neto257c3892018-04-11 13:19:45 -04003194 ParamOps << MkId(ParamTyID);
David Neto22f144c2017-06-12 14:26:21 -04003195
3196 // Generate SPIRV instruction for parameter.
David Neto87846742018-04-11 17:36:22 -04003197 auto *ParamInst =
alan-bakere9308012019-03-15 10:25:13 -04003198 new SPIRVInstruction(spv::OpFunctionParameter, param_id, ParamOps);
David Neto22f144c2017-06-12 14:26:21 -04003199 SPIRVInstList.push_back(ParamInst);
3200
3201 ArgIdx++;
3202 }
3203 }
3204}
3205
alan-bakerb6b09dc2018-11-08 16:59:28 -05003206void SPIRVProducerPass::GenerateModuleInfo(Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04003207 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3208 EntryPointVecType &EntryPoints = getEntryPointVec();
3209 ValueMapType &VMap = getValueMap();
3210 ValueList &EntryPointInterfaces = getEntryPointInterfacesVec();
3211 uint32_t &ExtInstImportID = getOpExtInstImportID();
3212 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
3213
3214 // Set up insert point.
3215 auto InsertPoint = SPIRVInstList.begin();
3216
3217 //
3218 // Generate OpCapability
3219 //
3220 // TODO: Which llvm information is mapped to SPIRV Capapbility?
3221
3222 // Ops[0] = Capability
3223 SPIRVOperandList Ops;
3224
David Neto87846742018-04-11 17:36:22 -04003225 auto *CapInst =
3226 new SPIRVInstruction(spv::OpCapability, {MkNum(spv::CapabilityShader)});
David Neto22f144c2017-06-12 14:26:21 -04003227 SPIRVInstList.insert(InsertPoint, CapInst);
3228
3229 for (Type *Ty : getTypeList()) {
alan-bakerb39c8262019-03-08 14:03:37 -05003230 if (clspv::Option::Int8Support() && Ty->isIntegerTy(8)) {
3231 // Generate OpCapability for i8 type.
3232 SPIRVInstList.insert(InsertPoint,
3233 new SPIRVInstruction(spv::OpCapability,
3234 {MkNum(spv::CapabilityInt8)}));
3235 } else if (Ty->isIntegerTy(16)) {
David Neto22f144c2017-06-12 14:26:21 -04003236 // Generate OpCapability for i16 type.
David Neto87846742018-04-11 17:36:22 -04003237 SPIRVInstList.insert(InsertPoint,
3238 new SPIRVInstruction(spv::OpCapability,
3239 {MkNum(spv::CapabilityInt16)}));
David Neto22f144c2017-06-12 14:26:21 -04003240 } else if (Ty->isIntegerTy(64)) {
3241 // Generate OpCapability for i64 type.
David Neto87846742018-04-11 17:36:22 -04003242 SPIRVInstList.insert(InsertPoint,
3243 new SPIRVInstruction(spv::OpCapability,
3244 {MkNum(spv::CapabilityInt64)}));
David Neto22f144c2017-06-12 14:26:21 -04003245 } else if (Ty->isHalfTy()) {
3246 // Generate OpCapability for half type.
3247 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003248 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3249 {MkNum(spv::CapabilityFloat16)}));
David Neto22f144c2017-06-12 14:26:21 -04003250 } else if (Ty->isDoubleTy()) {
3251 // Generate OpCapability for double type.
3252 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003253 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3254 {MkNum(spv::CapabilityFloat64)}));
David Neto22f144c2017-06-12 14:26:21 -04003255 } else if (auto *STy = dyn_cast<StructType>(Ty)) {
3256 if (STy->isOpaque()) {
David Neto565571c2017-08-21 12:00:05 -04003257 if (STy->getName().equals("opencl.image2d_wo_t") ||
3258 STy->getName().equals("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04003259 // Generate OpCapability for write only image type.
3260 SPIRVInstList.insert(
3261 InsertPoint,
3262 new SPIRVInstruction(
David Neto87846742018-04-11 17:36:22 -04003263 spv::OpCapability,
3264 {MkNum(spv::CapabilityStorageImageWriteWithoutFormat)}));
David Neto22f144c2017-06-12 14:26:21 -04003265 }
3266 }
3267 }
3268 }
3269
David Neto5c22a252018-03-15 16:07:41 -04003270 { // OpCapability ImageQuery
3271 bool hasImageQuery = false;
3272 for (const char *imageQuery : {
3273 "_Z15get_image_width14ocl_image2d_ro",
3274 "_Z15get_image_width14ocl_image2d_wo",
3275 "_Z16get_image_height14ocl_image2d_ro",
3276 "_Z16get_image_height14ocl_image2d_wo",
3277 }) {
3278 if (module.getFunction(imageQuery)) {
3279 hasImageQuery = true;
3280 break;
3281 }
3282 }
3283 if (hasImageQuery) {
David Neto87846742018-04-11 17:36:22 -04003284 auto *ImageQueryCapInst = new SPIRVInstruction(
3285 spv::OpCapability, {MkNum(spv::CapabilityImageQuery)});
David Neto5c22a252018-03-15 16:07:41 -04003286 SPIRVInstList.insert(InsertPoint, ImageQueryCapInst);
3287 }
3288 }
3289
David Neto22f144c2017-06-12 14:26:21 -04003290 if (hasVariablePointers()) {
3291 //
David Neto22f144c2017-06-12 14:26:21 -04003292 // Generate OpCapability.
3293 //
3294 // Ops[0] = Capability
3295 //
3296 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003297 Ops << MkNum(spv::CapabilityVariablePointers);
David Neto22f144c2017-06-12 14:26:21 -04003298
David Neto87846742018-04-11 17:36:22 -04003299 SPIRVInstList.insert(InsertPoint,
3300 new SPIRVInstruction(spv::OpCapability, Ops));
alan-baker5b86ed72019-02-15 08:26:50 -05003301 } else if (hasVariablePointersStorageBuffer()) {
3302 //
3303 // Generate OpCapability.
3304 //
3305 // Ops[0] = Capability
3306 //
3307 Ops.clear();
3308 Ops << MkNum(spv::CapabilityVariablePointersStorageBuffer);
David Neto22f144c2017-06-12 14:26:21 -04003309
alan-baker5b86ed72019-02-15 08:26:50 -05003310 SPIRVInstList.insert(InsertPoint,
3311 new SPIRVInstruction(spv::OpCapability, Ops));
3312 }
3313
3314 // Always add the storage buffer extension
3315 {
David Neto22f144c2017-06-12 14:26:21 -04003316 //
3317 // Generate OpExtension.
3318 //
3319 // Ops[0] = Name (Literal String)
3320 //
alan-baker5b86ed72019-02-15 08:26:50 -05003321 auto *ExtensionInst = new SPIRVInstruction(
3322 spv::OpExtension, {MkString("SPV_KHR_storage_buffer_storage_class")});
3323 SPIRVInstList.insert(InsertPoint, ExtensionInst);
3324 }
David Neto22f144c2017-06-12 14:26:21 -04003325
alan-baker5b86ed72019-02-15 08:26:50 -05003326 if (hasVariablePointers() || hasVariablePointersStorageBuffer()) {
3327 //
3328 // Generate OpExtension.
3329 //
3330 // Ops[0] = Name (Literal String)
3331 //
3332 auto *ExtensionInst = new SPIRVInstruction(
3333 spv::OpExtension, {MkString("SPV_KHR_variable_pointers")});
3334 SPIRVInstList.insert(InsertPoint, ExtensionInst);
David Neto22f144c2017-06-12 14:26:21 -04003335 }
3336
3337 if (ExtInstImportID) {
3338 ++InsertPoint;
3339 }
3340
3341 //
3342 // Generate OpMemoryModel
3343 //
3344 // Memory model for Vulkan will always be GLSL450.
3345
3346 // Ops[0] = Addressing Model
3347 // Ops[1] = Memory Model
3348 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003349 Ops << MkNum(spv::AddressingModelLogical) << MkNum(spv::MemoryModelGLSL450);
David Neto22f144c2017-06-12 14:26:21 -04003350
David Neto87846742018-04-11 17:36:22 -04003351 auto *MemModelInst = new SPIRVInstruction(spv::OpMemoryModel, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003352 SPIRVInstList.insert(InsertPoint, MemModelInst);
3353
3354 //
3355 // Generate OpEntryPoint
3356 //
3357 for (auto EntryPoint : EntryPoints) {
3358 // Ops[0] = Execution Model
3359 // Ops[1] = EntryPoint ID
3360 // Ops[2] = Name (Literal String)
3361 // ...
3362 //
3363 // TODO: Do we need to consider Interface ID for forward references???
3364 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003365 const StringRef &name = EntryPoint.first->getName();
David Neto257c3892018-04-11 13:19:45 -04003366 Ops << MkNum(spv::ExecutionModelGLCompute) << MkId(EntryPoint.second)
3367 << MkString(name);
David Neto22f144c2017-06-12 14:26:21 -04003368
David Neto22f144c2017-06-12 14:26:21 -04003369 for (Value *Interface : EntryPointInterfaces) {
David Neto257c3892018-04-11 13:19:45 -04003370 Ops << MkId(VMap[Interface]);
David Neto22f144c2017-06-12 14:26:21 -04003371 }
3372
David Neto87846742018-04-11 17:36:22 -04003373 auto *EntryPointInst = new SPIRVInstruction(spv::OpEntryPoint, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003374 SPIRVInstList.insert(InsertPoint, EntryPointInst);
3375 }
3376
3377 for (auto EntryPoint : EntryPoints) {
3378 if (const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
3379 ->getMetadata("reqd_work_group_size")) {
3380
3381 if (!BuiltinDimVec.empty()) {
3382 llvm_unreachable(
3383 "Kernels should have consistent work group size definition");
3384 }
3385
3386 //
3387 // Generate OpExecutionMode
3388 //
3389
3390 // Ops[0] = Entry Point ID
3391 // Ops[1] = Execution Mode
3392 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
3393 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003394 Ops << MkId(EntryPoint.second) << MkNum(spv::ExecutionModeLocalSize);
David Neto22f144c2017-06-12 14:26:21 -04003395
3396 uint32_t XDim = static_cast<uint32_t>(
3397 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3398 uint32_t YDim = static_cast<uint32_t>(
3399 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3400 uint32_t ZDim = static_cast<uint32_t>(
3401 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3402
David Neto257c3892018-04-11 13:19:45 -04003403 Ops << MkNum(XDim) << MkNum(YDim) << MkNum(ZDim);
David Neto22f144c2017-06-12 14:26:21 -04003404
David Neto87846742018-04-11 17:36:22 -04003405 auto *ExecModeInst = new SPIRVInstruction(spv::OpExecutionMode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003406 SPIRVInstList.insert(InsertPoint, ExecModeInst);
3407 }
3408 }
3409
3410 //
3411 // Generate OpSource.
3412 //
3413 // Ops[0] = SourceLanguage ID
3414 // Ops[1] = Version (LiteralNum)
3415 //
3416 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003417 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(120);
David Neto22f144c2017-06-12 14:26:21 -04003418
David Neto87846742018-04-11 17:36:22 -04003419 auto *OpenSourceInst = new SPIRVInstruction(spv::OpSource, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003420 SPIRVInstList.insert(InsertPoint, OpenSourceInst);
3421
3422 if (!BuiltinDimVec.empty()) {
3423 //
3424 // Generate OpDecorates for x/y/z dimension.
3425 //
3426 // Ops[0] = Target ID
3427 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04003428 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04003429
3430 // X Dimension
3431 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003432 Ops << MkId(BuiltinDimVec[0]) << MkNum(spv::DecorationSpecId) << MkNum(0);
David Neto87846742018-04-11 17:36:22 -04003433 SPIRVInstList.insert(InsertPoint,
3434 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003435
3436 // Y Dimension
3437 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003438 Ops << MkId(BuiltinDimVec[1]) << MkNum(spv::DecorationSpecId) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04003439 SPIRVInstList.insert(InsertPoint,
3440 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003441
3442 // Z Dimension
3443 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003444 Ops << MkId(BuiltinDimVec[2]) << MkNum(spv::DecorationSpecId) << MkNum(2);
David Neto87846742018-04-11 17:36:22 -04003445 SPIRVInstList.insert(InsertPoint,
3446 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003447 }
3448}
3449
David Netob6e2e062018-04-25 10:32:06 -04003450void SPIRVProducerPass::GenerateEntryPointInitialStores() {
3451 // Work around a driver bug. Initializers on Private variables might not
3452 // work. So the start of the kernel should store the initializer value to the
3453 // variables. Yes, *every* entry point pays this cost if *any* entry point
3454 // uses this builtin. At this point I judge this to be an acceptable tradeoff
3455 // of complexity vs. runtime, for a broken driver.
alan-bakerb6b09dc2018-11-08 16:59:28 -05003456 // TODO(dneto): Remove this at some point once fixed drivers are widely
3457 // available.
David Netob6e2e062018-04-25 10:32:06 -04003458 if (WorkgroupSizeVarID) {
3459 assert(WorkgroupSizeValueID);
3460
3461 SPIRVOperandList Ops;
3462 Ops << MkId(WorkgroupSizeVarID) << MkId(WorkgroupSizeValueID);
3463
3464 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
3465 getSPIRVInstList().push_back(Inst);
3466 }
3467}
3468
David Neto22f144c2017-06-12 14:26:21 -04003469void SPIRVProducerPass::GenerateFuncBody(Function &F) {
3470 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3471 ValueMapType &VMap = getValueMap();
3472
David Netob6e2e062018-04-25 10:32:06 -04003473 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04003474
3475 for (BasicBlock &BB : F) {
3476 // Register BasicBlock to ValueMap.
3477 VMap[&BB] = nextID;
3478
3479 //
3480 // Generate OpLabel for Basic Block.
3481 //
3482 SPIRVOperandList Ops;
David Neto87846742018-04-11 17:36:22 -04003483 auto *Inst = new SPIRVInstruction(spv::OpLabel, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003484 SPIRVInstList.push_back(Inst);
3485
David Neto6dcd4712017-06-23 11:06:47 -04003486 // OpVariable instructions must come first.
3487 for (Instruction &I : BB) {
alan-baker5b86ed72019-02-15 08:26:50 -05003488 if (auto *alloca = dyn_cast<AllocaInst>(&I)) {
3489 // Allocating a pointer requires variable pointers.
3490 if (alloca->getAllocatedType()->isPointerTy()) {
3491 setVariablePointersCapabilities(alloca->getAllocatedType()->getPointerAddressSpace());
3492 }
David Neto6dcd4712017-06-23 11:06:47 -04003493 GenerateInstruction(I);
3494 }
3495 }
3496
David Neto22f144c2017-06-12 14:26:21 -04003497 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04003498 if (clspv::Option::HackInitializers()) {
3499 GenerateEntryPointInitialStores();
3500 }
David Neto22f144c2017-06-12 14:26:21 -04003501 }
3502
3503 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003504 if (!isa<AllocaInst>(I)) {
3505 GenerateInstruction(I);
3506 }
David Neto22f144c2017-06-12 14:26:21 -04003507 }
3508 }
3509}
3510
3511spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3512 const std::map<CmpInst::Predicate, spv::Op> Map = {
3513 {CmpInst::ICMP_EQ, spv::OpIEqual},
3514 {CmpInst::ICMP_NE, spv::OpINotEqual},
3515 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3516 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3517 {CmpInst::ICMP_ULT, spv::OpULessThan},
3518 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3519 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3520 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3521 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3522 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3523 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3524 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3525 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3526 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3527 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3528 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3529 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3530 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3531 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3532 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3533 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3534 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3535
3536 assert(0 != Map.count(I->getPredicate()));
3537
3538 return Map.at(I->getPredicate());
3539}
3540
3541spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3542 const std::map<unsigned, spv::Op> Map{
3543 {Instruction::Trunc, spv::OpUConvert},
3544 {Instruction::ZExt, spv::OpUConvert},
3545 {Instruction::SExt, spv::OpSConvert},
3546 {Instruction::FPToUI, spv::OpConvertFToU},
3547 {Instruction::FPToSI, spv::OpConvertFToS},
3548 {Instruction::UIToFP, spv::OpConvertUToF},
3549 {Instruction::SIToFP, spv::OpConvertSToF},
3550 {Instruction::FPTrunc, spv::OpFConvert},
3551 {Instruction::FPExt, spv::OpFConvert},
3552 {Instruction::BitCast, spv::OpBitcast}};
3553
3554 assert(0 != Map.count(I.getOpcode()));
3555
3556 return Map.at(I.getOpcode());
3557}
3558
3559spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
Kévin Petit24272b62018-10-18 19:16:12 +00003560 if (I.getType()->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003561 switch (I.getOpcode()) {
3562 default:
3563 break;
3564 case Instruction::Or:
3565 return spv::OpLogicalOr;
3566 case Instruction::And:
3567 return spv::OpLogicalAnd;
3568 case Instruction::Xor:
3569 return spv::OpLogicalNotEqual;
3570 }
3571 }
3572
alan-bakerb6b09dc2018-11-08 16:59:28 -05003573 const std::map<unsigned, spv::Op> Map{
David Neto22f144c2017-06-12 14:26:21 -04003574 {Instruction::Add, spv::OpIAdd},
3575 {Instruction::FAdd, spv::OpFAdd},
3576 {Instruction::Sub, spv::OpISub},
3577 {Instruction::FSub, spv::OpFSub},
3578 {Instruction::Mul, spv::OpIMul},
3579 {Instruction::FMul, spv::OpFMul},
3580 {Instruction::UDiv, spv::OpUDiv},
3581 {Instruction::SDiv, spv::OpSDiv},
3582 {Instruction::FDiv, spv::OpFDiv},
3583 {Instruction::URem, spv::OpUMod},
3584 {Instruction::SRem, spv::OpSRem},
3585 {Instruction::FRem, spv::OpFRem},
3586 {Instruction::Or, spv::OpBitwiseOr},
3587 {Instruction::Xor, spv::OpBitwiseXor},
3588 {Instruction::And, spv::OpBitwiseAnd},
3589 {Instruction::Shl, spv::OpShiftLeftLogical},
3590 {Instruction::LShr, spv::OpShiftRightLogical},
3591 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3592
3593 assert(0 != Map.count(I.getOpcode()));
3594
3595 return Map.at(I.getOpcode());
3596}
3597
3598void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
3599 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3600 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04003601 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
3602 LLVMContext &Context = I.getParent()->getParent()->getParent()->getContext();
3603
3604 // Register Instruction to ValueMap.
3605 if (0 == VMap[&I]) {
3606 VMap[&I] = nextID;
3607 }
3608
3609 switch (I.getOpcode()) {
3610 default: {
3611 if (Instruction::isCast(I.getOpcode())) {
3612 //
3613 // Generate SPIRV instructions for cast operators.
3614 //
3615
David Netod2de94a2017-08-28 17:27:47 -04003616 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003617 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003618 auto toI8 = Ty == Type::getInt8Ty(Context);
3619 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003620 // Handle zext, sext and uitofp with i1 type specially.
3621 if ((I.getOpcode() == Instruction::ZExt ||
3622 I.getOpcode() == Instruction::SExt ||
3623 I.getOpcode() == Instruction::UIToFP) &&
alan-bakerb6b09dc2018-11-08 16:59:28 -05003624 OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003625 //
3626 // Generate OpSelect.
3627 //
3628
3629 // Ops[0] = Result Type ID
3630 // Ops[1] = Condition ID
3631 // Ops[2] = True Constant ID
3632 // Ops[3] = False Constant ID
3633 SPIRVOperandList Ops;
3634
David Neto257c3892018-04-11 13:19:45 -04003635 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003636
David Neto22f144c2017-06-12 14:26:21 -04003637 uint32_t CondID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003638 Ops << MkId(CondID);
David Neto22f144c2017-06-12 14:26:21 -04003639
3640 uint32_t TrueID = 0;
3641 if (I.getOpcode() == Instruction::ZExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00003642 TrueID = VMap[ConstantInt::get(I.getType(), 1)];
David Neto22f144c2017-06-12 14:26:21 -04003643 } else if (I.getOpcode() == Instruction::SExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00003644 TrueID = VMap[ConstantInt::getSigned(I.getType(), -1)];
David Neto22f144c2017-06-12 14:26:21 -04003645 } else {
3646 TrueID = VMap[ConstantFP::get(Context, APFloat(1.0f))];
3647 }
David Neto257c3892018-04-11 13:19:45 -04003648 Ops << MkId(TrueID);
David Neto22f144c2017-06-12 14:26:21 -04003649
3650 uint32_t FalseID = 0;
3651 if (I.getOpcode() == Instruction::ZExt) {
3652 FalseID = VMap[Constant::getNullValue(I.getType())];
3653 } else if (I.getOpcode() == Instruction::SExt) {
3654 FalseID = VMap[Constant::getNullValue(I.getType())];
3655 } else {
3656 FalseID = VMap[ConstantFP::get(Context, APFloat(0.0f))];
3657 }
David Neto257c3892018-04-11 13:19:45 -04003658 Ops << MkId(FalseID);
David Neto22f144c2017-06-12 14:26:21 -04003659
David Neto87846742018-04-11 17:36:22 -04003660 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003661 SPIRVInstList.push_back(Inst);
alan-bakerb39c8262019-03-08 14:03:37 -05003662 } else if (!clspv::Option::Int8Support() &&
3663 I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
David Netod2de94a2017-08-28 17:27:47 -04003664 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3665 // 8 bits.
3666 // Before:
3667 // %result = trunc i32 %a to i8
3668 // After
3669 // %result = OpBitwiseAnd %uint %a %uint_255
3670
3671 SPIRVOperandList Ops;
3672
David Neto257c3892018-04-11 13:19:45 -04003673 Ops << MkId(lookupType(OpTy)) << MkId(VMap[I.getOperand(0)]);
David Netod2de94a2017-08-28 17:27:47 -04003674
3675 Type *UintTy = Type::getInt32Ty(Context);
3676 uint32_t MaskID = VMap[ConstantInt::get(UintTy, 255)];
David Neto257c3892018-04-11 13:19:45 -04003677 Ops << MkId(MaskID);
David Netod2de94a2017-08-28 17:27:47 -04003678
David Neto87846742018-04-11 17:36:22 -04003679 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Netod2de94a2017-08-28 17:27:47 -04003680 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003681 } else {
3682 // Ops[0] = Result Type ID
3683 // Ops[1] = Source Value ID
3684 SPIRVOperandList Ops;
3685
David Neto257c3892018-04-11 13:19:45 -04003686 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003687
David Neto87846742018-04-11 17:36:22 -04003688 auto *Inst = new SPIRVInstruction(GetSPIRVCastOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003689 SPIRVInstList.push_back(Inst);
3690 }
3691 } else if (isa<BinaryOperator>(I)) {
3692 //
3693 // Generate SPIRV instructions for binary operators.
3694 //
3695
3696 // Handle xor with i1 type specially.
3697 if (I.getOpcode() == Instruction::Xor &&
3698 I.getType() == Type::getInt1Ty(Context) &&
Kévin Petit24272b62018-10-18 19:16:12 +00003699 ((isa<ConstantInt>(I.getOperand(0)) &&
3700 !cast<ConstantInt>(I.getOperand(0))->isZero()) ||
3701 (isa<ConstantInt>(I.getOperand(1)) &&
3702 !cast<ConstantInt>(I.getOperand(1))->isZero()))) {
David Neto22f144c2017-06-12 14:26:21 -04003703 //
3704 // Generate OpLogicalNot.
3705 //
3706 // Ops[0] = Result Type ID
3707 // Ops[1] = Operand
3708 SPIRVOperandList Ops;
3709
David Neto257c3892018-04-11 13:19:45 -04003710 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003711
3712 Value *CondV = I.getOperand(0);
3713 if (isa<Constant>(I.getOperand(0))) {
3714 CondV = I.getOperand(1);
3715 }
David Neto257c3892018-04-11 13:19:45 -04003716 Ops << MkId(VMap[CondV]);
David Neto22f144c2017-06-12 14:26:21 -04003717
David Neto87846742018-04-11 17:36:22 -04003718 auto *Inst = new SPIRVInstruction(spv::OpLogicalNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003719 SPIRVInstList.push_back(Inst);
3720 } else {
3721 // Ops[0] = Result Type ID
3722 // Ops[1] = Operand 0
3723 // Ops[2] = Operand 1
3724 SPIRVOperandList Ops;
3725
David Neto257c3892018-04-11 13:19:45 -04003726 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
3727 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003728
David Neto87846742018-04-11 17:36:22 -04003729 auto *Inst =
3730 new SPIRVInstruction(GetSPIRVBinaryOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003731 SPIRVInstList.push_back(Inst);
3732 }
3733 } else {
3734 I.print(errs());
3735 llvm_unreachable("Unsupported instruction???");
3736 }
3737 break;
3738 }
3739 case Instruction::GetElementPtr: {
3740 auto &GlobalConstArgSet = getGlobalConstArgSet();
3741
3742 //
3743 // Generate OpAccessChain.
3744 //
3745 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
3746
3747 //
3748 // Generate OpAccessChain.
3749 //
3750
3751 // Ops[0] = Result Type ID
3752 // Ops[1] = Base ID
3753 // Ops[2] ... Ops[n] = Indexes ID
3754 SPIRVOperandList Ops;
3755
alan-bakerb6b09dc2018-11-08 16:59:28 -05003756 PointerType *ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04003757 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
3758 GlobalConstArgSet.count(GEP->getPointerOperand())) {
3759 // Use pointer type with private address space for global constant.
3760 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04003761 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04003762 }
David Neto257c3892018-04-11 13:19:45 -04003763
3764 Ops << MkId(lookupType(ResultType));
David Neto22f144c2017-06-12 14:26:21 -04003765
David Neto862b7d82018-06-14 18:48:37 -04003766 // Generate the base pointer.
3767 Ops << MkId(VMap[GEP->getPointerOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04003768
David Neto862b7d82018-06-14 18:48:37 -04003769 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04003770
3771 //
3772 // Follows below rules for gep.
3773 //
David Neto862b7d82018-06-14 18:48:37 -04003774 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
3775 // first index.
David Neto22f144c2017-06-12 14:26:21 -04003776 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
3777 // first index.
3778 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
3779 // use gep's first index.
3780 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
3781 // gep's first index.
3782 //
3783 spv::Op Opcode = spv::OpAccessChain;
3784 unsigned offset = 0;
3785 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04003786 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04003787 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04003788 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04003789 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04003790 }
David Neto862b7d82018-06-14 18:48:37 -04003791 } else {
David Neto22f144c2017-06-12 14:26:21 -04003792 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04003793 }
3794
3795 if (Opcode == spv::OpPtrAccessChain) {
David Neto1a1a0582017-07-07 12:01:44 -04003796 // Do we need to generate ArrayStride? Check against the GEP result type
3797 // rather than the pointer type of the base because when indexing into
3798 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
3799 // for something else in the SPIR-V.
3800 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
alan-baker5b86ed72019-02-15 08:26:50 -05003801 auto address_space = ResultType->getAddressSpace();
3802 setVariablePointersCapabilities(address_space);
3803 switch (GetStorageClass(address_space)) {
Alan Bakerfcda9482018-10-02 17:09:59 -04003804 case spv::StorageClassStorageBuffer:
3805 case spv::StorageClassUniform:
David Neto1a1a0582017-07-07 12:01:44 -04003806 // Save the need to generate an ArrayStride decoration. But defer
3807 // generation until later, so we only make one decoration.
David Neto85082642018-03-24 06:55:20 -07003808 getTypesNeedingArrayStride().insert(ResultType);
Alan Bakerfcda9482018-10-02 17:09:59 -04003809 break;
3810 default:
3811 break;
David Neto1a1a0582017-07-07 12:01:44 -04003812 }
David Neto22f144c2017-06-12 14:26:21 -04003813 }
3814
3815 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
David Neto257c3892018-04-11 13:19:45 -04003816 Ops << MkId(VMap[*II]);
David Neto22f144c2017-06-12 14:26:21 -04003817 }
3818
David Neto87846742018-04-11 17:36:22 -04003819 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003820 SPIRVInstList.push_back(Inst);
3821 break;
3822 }
3823 case Instruction::ExtractValue: {
3824 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3825 // Ops[0] = Result Type ID
3826 // Ops[1] = Composite ID
3827 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3828 SPIRVOperandList Ops;
3829
David Neto257c3892018-04-11 13:19:45 -04003830 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003831
3832 uint32_t CompositeID = VMap[EVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003833 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003834
3835 for (auto &Index : EVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003836 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003837 }
3838
David Neto87846742018-04-11 17:36:22 -04003839 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003840 SPIRVInstList.push_back(Inst);
3841 break;
3842 }
3843 case Instruction::InsertValue: {
3844 InsertValueInst *IVI = cast<InsertValueInst>(&I);
3845 // Ops[0] = Result Type ID
3846 // Ops[1] = Object ID
3847 // Ops[2] = Composite ID
3848 // Ops[3] ... Ops[n] = Indexes (Literal Number)
3849 SPIRVOperandList Ops;
3850
3851 uint32_t ResTyID = lookupType(I.getType());
David Neto257c3892018-04-11 13:19:45 -04003852 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04003853
3854 uint32_t ObjectID = VMap[IVI->getInsertedValueOperand()];
David Neto257c3892018-04-11 13:19:45 -04003855 Ops << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04003856
3857 uint32_t CompositeID = VMap[IVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003858 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003859
3860 for (auto &Index : IVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003861 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003862 }
3863
David Neto87846742018-04-11 17:36:22 -04003864 auto *Inst = new SPIRVInstruction(spv::OpCompositeInsert, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003865 SPIRVInstList.push_back(Inst);
3866 break;
3867 }
3868 case Instruction::Select: {
3869 //
3870 // Generate OpSelect.
3871 //
3872
3873 // Ops[0] = Result Type ID
3874 // Ops[1] = Condition ID
3875 // Ops[2] = True Constant ID
3876 // Ops[3] = False Constant ID
3877 SPIRVOperandList Ops;
3878
3879 // Find SPIRV instruction for parameter type.
3880 auto Ty = I.getType();
3881 if (Ty->isPointerTy()) {
3882 auto PointeeTy = Ty->getPointerElementType();
3883 if (PointeeTy->isStructTy() &&
3884 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
3885 Ty = PointeeTy;
alan-baker5b86ed72019-02-15 08:26:50 -05003886 } else {
3887 // Selecting between pointers requires variable pointers.
3888 setVariablePointersCapabilities(Ty->getPointerAddressSpace());
3889 if (!hasVariablePointers() && !selectFromSameObject(&I)) {
3890 setVariablePointers(true);
3891 }
David Neto22f144c2017-06-12 14:26:21 -04003892 }
3893 }
3894
David Neto257c3892018-04-11 13:19:45 -04003895 Ops << MkId(lookupType(Ty)) << MkId(VMap[I.getOperand(0)])
3896 << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003897
David Neto87846742018-04-11 17:36:22 -04003898 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003899 SPIRVInstList.push_back(Inst);
3900 break;
3901 }
3902 case Instruction::ExtractElement: {
3903 // Handle <4 x i8> type manually.
3904 Type *CompositeTy = I.getOperand(0)->getType();
3905 if (is4xi8vec(CompositeTy)) {
3906 //
3907 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
3908 // <4 x i8>.
3909 //
3910
3911 //
3912 // Generate OpShiftRightLogical
3913 //
3914 // Ops[0] = Result Type ID
3915 // Ops[1] = Operand 0
3916 // Ops[2] = Operand 1
3917 //
3918 SPIRVOperandList Ops;
3919
David Neto257c3892018-04-11 13:19:45 -04003920 Ops << MkId(lookupType(CompositeTy));
David Neto22f144c2017-06-12 14:26:21 -04003921
3922 uint32_t Op0ID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003923 Ops << MkId(Op0ID);
David Neto22f144c2017-06-12 14:26:21 -04003924
3925 uint32_t Op1ID = 0;
3926 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
3927 // Handle constant index.
3928 uint64_t Idx = CI->getZExtValue();
3929 Value *ShiftAmount =
3930 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3931 Op1ID = VMap[ShiftAmount];
3932 } else {
3933 // Handle variable index.
3934 SPIRVOperandList TmpOps;
3935
David Neto257c3892018-04-11 13:19:45 -04003936 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3937 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003938
3939 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003940 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003941
3942 Op1ID = nextID;
3943
David Neto87846742018-04-11 17:36:22 -04003944 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003945 SPIRVInstList.push_back(TmpInst);
3946 }
David Neto257c3892018-04-11 13:19:45 -04003947 Ops << MkId(Op1ID);
David Neto22f144c2017-06-12 14:26:21 -04003948
3949 uint32_t ShiftID = nextID;
3950
David Neto87846742018-04-11 17:36:22 -04003951 auto *Inst =
3952 new SPIRVInstruction(spv::OpShiftRightLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003953 SPIRVInstList.push_back(Inst);
3954
3955 //
3956 // Generate OpBitwiseAnd
3957 //
3958 // Ops[0] = Result Type ID
3959 // Ops[1] = Operand 0
3960 // Ops[2] = Operand 1
3961 //
3962 Ops.clear();
3963
David Neto257c3892018-04-11 13:19:45 -04003964 Ops << MkId(lookupType(CompositeTy)) << MkId(ShiftID);
David Neto22f144c2017-06-12 14:26:21 -04003965
3966 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
David Neto257c3892018-04-11 13:19:45 -04003967 Ops << MkId(VMap[CstFF]);
David Neto22f144c2017-06-12 14:26:21 -04003968
David Neto9b2d6252017-09-06 15:47:37 -04003969 // Reset mapping for this value to the result of the bitwise and.
3970 VMap[&I] = nextID;
3971
David Neto87846742018-04-11 17:36:22 -04003972 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003973 SPIRVInstList.push_back(Inst);
3974 break;
3975 }
3976
3977 // Ops[0] = Result Type ID
3978 // Ops[1] = Composite ID
3979 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3980 SPIRVOperandList Ops;
3981
David Neto257c3892018-04-11 13:19:45 -04003982 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003983
3984 spv::Op Opcode = spv::OpCompositeExtract;
3985 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
David Neto257c3892018-04-11 13:19:45 -04003986 Ops << MkNum(static_cast<uint32_t>(CI->getZExtValue()));
David Neto22f144c2017-06-12 14:26:21 -04003987 } else {
David Neto257c3892018-04-11 13:19:45 -04003988 Ops << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003989 Opcode = spv::OpVectorExtractDynamic;
3990 }
3991
David Neto87846742018-04-11 17:36:22 -04003992 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003993 SPIRVInstList.push_back(Inst);
3994 break;
3995 }
3996 case Instruction::InsertElement: {
3997 // Handle <4 x i8> type manually.
3998 Type *CompositeTy = I.getOperand(0)->getType();
3999 if (is4xi8vec(CompositeTy)) {
4000 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
4001 uint32_t CstFFID = VMap[CstFF];
4002
4003 uint32_t ShiftAmountID = 0;
4004 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
4005 // Handle constant index.
4006 uint64_t Idx = CI->getZExtValue();
4007 Value *ShiftAmount =
4008 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
4009 ShiftAmountID = VMap[ShiftAmount];
4010 } else {
4011 // Handle variable index.
4012 SPIRVOperandList TmpOps;
4013
David Neto257c3892018-04-11 13:19:45 -04004014 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
4015 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004016
4017 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04004018 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04004019
4020 ShiftAmountID = nextID;
4021
David Neto87846742018-04-11 17:36:22 -04004022 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004023 SPIRVInstList.push_back(TmpInst);
4024 }
4025
4026 //
4027 // Generate mask operations.
4028 //
4029
4030 // ShiftLeft mask according to index of insertelement.
4031 SPIRVOperandList Ops;
4032
David Neto257c3892018-04-11 13:19:45 -04004033 const uint32_t ResTyID = lookupType(CompositeTy);
4034 Ops << MkId(ResTyID) << MkId(CstFFID) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004035
4036 uint32_t MaskID = nextID;
4037
David Neto87846742018-04-11 17:36:22 -04004038 auto *Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004039 SPIRVInstList.push_back(Inst);
4040
4041 // Inverse mask.
4042 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004043 Ops << MkId(ResTyID) << MkId(MaskID);
David Neto22f144c2017-06-12 14:26:21 -04004044
4045 uint32_t InvMaskID = nextID;
4046
David Neto87846742018-04-11 17:36:22 -04004047 Inst = new SPIRVInstruction(spv::OpNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004048 SPIRVInstList.push_back(Inst);
4049
4050 // Apply mask.
4051 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004052 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(0)]) << MkId(InvMaskID);
David Neto22f144c2017-06-12 14:26:21 -04004053
4054 uint32_t OrgValID = nextID;
4055
David Neto87846742018-04-11 17:36:22 -04004056 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004057 SPIRVInstList.push_back(Inst);
4058
4059 // Create correct value according to index of insertelement.
4060 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05004061 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(1)])
4062 << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004063
4064 uint32_t InsertValID = nextID;
4065
David Neto87846742018-04-11 17:36:22 -04004066 Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004067 SPIRVInstList.push_back(Inst);
4068
4069 // Insert value to original value.
4070 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004071 Ops << MkId(ResTyID) << MkId(OrgValID) << MkId(InsertValID);
David Neto22f144c2017-06-12 14:26:21 -04004072
David Netoa394f392017-08-26 20:45:29 -04004073 VMap[&I] = nextID;
4074
David Neto87846742018-04-11 17:36:22 -04004075 Inst = new SPIRVInstruction(spv::OpBitwiseOr, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004076 SPIRVInstList.push_back(Inst);
4077
4078 break;
4079 }
4080
David Neto22f144c2017-06-12 14:26:21 -04004081 SPIRVOperandList Ops;
4082
James Priced26efea2018-06-09 23:28:32 +01004083 // Ops[0] = Result Type ID
4084 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004085
4086 spv::Op Opcode = spv::OpCompositeInsert;
4087 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04004088 const auto value = CI->getZExtValue();
4089 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01004090 // Ops[1] = Object ID
4091 // Ops[2] = Composite ID
4092 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004093 Ops << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(0)])
James Priced26efea2018-06-09 23:28:32 +01004094 << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004095 } else {
James Priced26efea2018-06-09 23:28:32 +01004096 // Ops[1] = Composite ID
4097 // Ops[2] = Object ID
4098 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004099 Ops << MkId(VMap[I.getOperand(0)]) << MkId(VMap[I.getOperand(1)])
James Priced26efea2018-06-09 23:28:32 +01004100 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004101 Opcode = spv::OpVectorInsertDynamic;
4102 }
4103
David Neto87846742018-04-11 17:36:22 -04004104 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004105 SPIRVInstList.push_back(Inst);
4106 break;
4107 }
4108 case Instruction::ShuffleVector: {
4109 // Ops[0] = Result Type ID
4110 // Ops[1] = Vector 1 ID
4111 // Ops[2] = Vector 2 ID
4112 // Ops[3] ... Ops[n] = Components (Literal Number)
4113 SPIRVOperandList Ops;
4114
David Neto257c3892018-04-11 13:19:45 -04004115 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4116 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004117
4118 uint64_t NumElements = 0;
4119 if (Constant *Cst = dyn_cast<Constant>(I.getOperand(2))) {
4120 NumElements = cast<VectorType>(Cst->getType())->getNumElements();
4121
4122 if (Cst->isNullValue()) {
4123 for (unsigned i = 0; i < NumElements; i++) {
David Neto257c3892018-04-11 13:19:45 -04004124 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04004125 }
4126 } else if (const ConstantDataSequential *CDS =
4127 dyn_cast<ConstantDataSequential>(Cst)) {
4128 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
4129 std::vector<uint32_t> LiteralNum;
David Neto257c3892018-04-11 13:19:45 -04004130 const auto value = CDS->getElementAsInteger(i);
4131 assert(value <= UINT32_MAX);
4132 Ops << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004133 }
4134 } else if (const ConstantVector *CV = dyn_cast<ConstantVector>(Cst)) {
4135 for (unsigned i = 0; i < CV->getNumOperands(); i++) {
4136 auto Op = CV->getOperand(i);
4137
4138 uint32_t literal = 0;
4139
4140 if (auto CI = dyn_cast<ConstantInt>(Op)) {
4141 literal = static_cast<uint32_t>(CI->getZExtValue());
4142 } else if (auto UI = dyn_cast<UndefValue>(Op)) {
4143 literal = 0xFFFFFFFFu;
4144 } else {
4145 Op->print(errs());
4146 llvm_unreachable("Unsupported element in ConstantVector!");
4147 }
4148
David Neto257c3892018-04-11 13:19:45 -04004149 Ops << MkNum(literal);
David Neto22f144c2017-06-12 14:26:21 -04004150 }
4151 } else {
4152 Cst->print(errs());
4153 llvm_unreachable("Unsupported constant mask in ShuffleVector!");
4154 }
4155 }
4156
David Neto87846742018-04-11 17:36:22 -04004157 auto *Inst = new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004158 SPIRVInstList.push_back(Inst);
4159 break;
4160 }
4161 case Instruction::ICmp:
4162 case Instruction::FCmp: {
4163 CmpInst *CmpI = cast<CmpInst>(&I);
4164
David Netod4ca2e62017-07-06 18:47:35 -04004165 // Pointer equality is invalid.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004166 Type *ArgTy = CmpI->getOperand(0)->getType();
David Netod4ca2e62017-07-06 18:47:35 -04004167 if (isa<PointerType>(ArgTy)) {
4168 CmpI->print(errs());
4169 std::string name = I.getParent()->getParent()->getName();
4170 errs()
4171 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4172 << "in function " << name << "\n";
4173 llvm_unreachable("Pointer equality check is invalid");
4174 break;
4175 }
4176
David Neto257c3892018-04-11 13:19:45 -04004177 // Ops[0] = Result Type ID
4178 // Ops[1] = Operand 1 ID
4179 // Ops[2] = Operand 2 ID
4180 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004181
David Neto257c3892018-04-11 13:19:45 -04004182 Ops << MkId(lookupType(CmpI->getType())) << MkId(VMap[CmpI->getOperand(0)])
4183 << MkId(VMap[CmpI->getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004184
4185 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
David Neto87846742018-04-11 17:36:22 -04004186 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004187 SPIRVInstList.push_back(Inst);
4188 break;
4189 }
4190 case Instruction::Br: {
4191 // Branch instrucion is deferred because it needs label's ID. Record slot's
4192 // location on SPIRVInstructionList.
4193 DeferredInsts.push_back(
4194 std::make_tuple(&I, --SPIRVInstList.end(), 0 /* No id */));
4195 break;
4196 }
4197 case Instruction::Switch: {
4198 I.print(errs());
4199 llvm_unreachable("Unsupported instruction???");
4200 break;
4201 }
4202 case Instruction::IndirectBr: {
4203 I.print(errs());
4204 llvm_unreachable("Unsupported instruction???");
4205 break;
4206 }
4207 case Instruction::PHI: {
4208 // Branch instrucion is deferred because it needs label's ID. Record slot's
4209 // location on SPIRVInstructionList.
4210 DeferredInsts.push_back(
4211 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4212 break;
4213 }
4214 case Instruction::Alloca: {
4215 //
4216 // Generate OpVariable.
4217 //
4218 // Ops[0] : Result Type ID
4219 // Ops[1] : Storage Class
4220 SPIRVOperandList Ops;
4221
David Neto257c3892018-04-11 13:19:45 -04004222 Ops << MkId(lookupType(I.getType())) << MkNum(spv::StorageClassFunction);
David Neto22f144c2017-06-12 14:26:21 -04004223
David Neto87846742018-04-11 17:36:22 -04004224 auto *Inst = new SPIRVInstruction(spv::OpVariable, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004225 SPIRVInstList.push_back(Inst);
4226 break;
4227 }
4228 case Instruction::Load: {
4229 LoadInst *LD = cast<LoadInst>(&I);
4230 //
4231 // Generate OpLoad.
4232 //
alan-baker5b86ed72019-02-15 08:26:50 -05004233
4234 if (LD->getType()->isPointerTy()) {
4235 // Loading a pointer requires variable pointers.
4236 setVariablePointersCapabilities(LD->getType()->getPointerAddressSpace());
4237 }
David Neto22f144c2017-06-12 14:26:21 -04004238
David Neto0a2f98d2017-09-15 19:38:40 -04004239 uint32_t ResTyID = lookupType(LD->getType());
David Netoa60b00b2017-09-15 16:34:09 -04004240 uint32_t PointerID = VMap[LD->getPointerOperand()];
4241
4242 // This is a hack to work around what looks like a driver bug.
4243 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004244 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4245 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004246 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004247 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004248 // Generate a bitwise-and of the original value with itself.
4249 // We should have been able to get away with just an OpCopyObject,
4250 // but we need something more complex to get past certain driver bugs.
4251 // This is ridiculous, but necessary.
4252 // TODO(dneto): Revisit this once drivers fix their bugs.
4253
4254 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004255 Ops << MkId(ResTyID) << MkId(WorkgroupSizeValueID)
4256 << MkId(WorkgroupSizeValueID);
David Neto0a2f98d2017-09-15 19:38:40 -04004257
David Neto87846742018-04-11 17:36:22 -04004258 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto0a2f98d2017-09-15 19:38:40 -04004259 SPIRVInstList.push_back(Inst);
David Netoa60b00b2017-09-15 16:34:09 -04004260 break;
4261 }
4262
4263 // This is the normal path. Generate a load.
4264
David Neto22f144c2017-06-12 14:26:21 -04004265 // Ops[0] = Result Type ID
4266 // Ops[1] = Pointer ID
4267 // Ops[2] ... Ops[n] = Optional Memory Access
4268 //
4269 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004270
David Neto22f144c2017-06-12 14:26:21 -04004271 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004272 Ops << MkId(ResTyID) << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04004273
David Neto87846742018-04-11 17:36:22 -04004274 auto *Inst = new SPIRVInstruction(spv::OpLoad, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004275 SPIRVInstList.push_back(Inst);
4276 break;
4277 }
4278 case Instruction::Store: {
4279 StoreInst *ST = cast<StoreInst>(&I);
4280 //
4281 // Generate OpStore.
4282 //
4283
alan-baker5b86ed72019-02-15 08:26:50 -05004284 if (ST->getValueOperand()->getType()->isPointerTy()) {
4285 // Storing a pointer requires variable pointers.
4286 setVariablePointersCapabilities(
4287 ST->getValueOperand()->getType()->getPointerAddressSpace());
4288 }
4289
David Neto22f144c2017-06-12 14:26:21 -04004290 // Ops[0] = Pointer ID
4291 // Ops[1] = Object ID
4292 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4293 //
4294 // TODO: Do we need to implement Optional Memory Access???
David Neto257c3892018-04-11 13:19:45 -04004295 SPIRVOperandList Ops;
4296 Ops << MkId(VMap[ST->getPointerOperand()])
4297 << MkId(VMap[ST->getValueOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004298
David Neto87846742018-04-11 17:36:22 -04004299 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004300 SPIRVInstList.push_back(Inst);
4301 break;
4302 }
4303 case Instruction::AtomicCmpXchg: {
4304 I.print(errs());
4305 llvm_unreachable("Unsupported instruction???");
4306 break;
4307 }
4308 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004309 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4310
4311 spv::Op opcode;
4312
4313 switch (AtomicRMW->getOperation()) {
4314 default:
4315 I.print(errs());
4316 llvm_unreachable("Unsupported instruction???");
4317 case llvm::AtomicRMWInst::Add:
4318 opcode = spv::OpAtomicIAdd;
4319 break;
4320 case llvm::AtomicRMWInst::Sub:
4321 opcode = spv::OpAtomicISub;
4322 break;
4323 case llvm::AtomicRMWInst::Xchg:
4324 opcode = spv::OpAtomicExchange;
4325 break;
4326 case llvm::AtomicRMWInst::Min:
4327 opcode = spv::OpAtomicSMin;
4328 break;
4329 case llvm::AtomicRMWInst::Max:
4330 opcode = spv::OpAtomicSMax;
4331 break;
4332 case llvm::AtomicRMWInst::UMin:
4333 opcode = spv::OpAtomicUMin;
4334 break;
4335 case llvm::AtomicRMWInst::UMax:
4336 opcode = spv::OpAtomicUMax;
4337 break;
4338 case llvm::AtomicRMWInst::And:
4339 opcode = spv::OpAtomicAnd;
4340 break;
4341 case llvm::AtomicRMWInst::Or:
4342 opcode = spv::OpAtomicOr;
4343 break;
4344 case llvm::AtomicRMWInst::Xor:
4345 opcode = spv::OpAtomicXor;
4346 break;
4347 }
4348
4349 //
4350 // Generate OpAtomic*.
4351 //
4352 SPIRVOperandList Ops;
4353
David Neto257c3892018-04-11 13:19:45 -04004354 Ops << MkId(lookupType(I.getType()))
4355 << MkId(VMap[AtomicRMW->getPointerOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004356
4357 auto IntTy = Type::getInt32Ty(I.getContext());
Neil Henning39672102017-09-29 14:33:13 +01004358 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
David Neto257c3892018-04-11 13:19:45 -04004359 Ops << MkId(VMap[ConstantScopeDevice]);
Neil Henning39672102017-09-29 14:33:13 +01004360
4361 const auto ConstantMemorySemantics = ConstantInt::get(
4362 IntTy, spv::MemorySemanticsUniformMemoryMask |
4363 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto257c3892018-04-11 13:19:45 -04004364 Ops << MkId(VMap[ConstantMemorySemantics]);
Neil Henning39672102017-09-29 14:33:13 +01004365
David Neto257c3892018-04-11 13:19:45 -04004366 Ops << MkId(VMap[AtomicRMW->getValOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004367
4368 VMap[&I] = nextID;
4369
David Neto87846742018-04-11 17:36:22 -04004370 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
Neil Henning39672102017-09-29 14:33:13 +01004371 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004372 break;
4373 }
4374 case Instruction::Fence: {
4375 I.print(errs());
4376 llvm_unreachable("Unsupported instruction???");
4377 break;
4378 }
4379 case Instruction::Call: {
4380 CallInst *Call = dyn_cast<CallInst>(&I);
4381 Function *Callee = Call->getCalledFunction();
4382
Alan Baker202c8c72018-08-13 13:47:44 -04004383 if (Callee->getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004384 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
4385 // Generate an OpLoad
4386 SPIRVOperandList Ops;
4387 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004388
David Neto862b7d82018-06-14 18:48:37 -04004389 Ops << MkId(lookupType(Call->getType()->getPointerElementType()))
4390 << MkId(ResourceVarDeferredLoadCalls[Call]);
4391
4392 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
4393 SPIRVInstList.push_back(Inst);
4394 VMap[Call] = load_id;
4395 break;
4396
4397 } else {
4398 // This maps to an OpVariable we've already generated.
4399 // No code is generated for the call.
4400 }
4401 break;
alan-bakerb6b09dc2018-11-08 16:59:28 -05004402 } else if (Callee->getName().startswith(
4403 clspv::WorkgroupAccessorFunction())) {
Alan Baker202c8c72018-08-13 13:47:44 -04004404 // Don't codegen an instruction here, but instead map this call directly
4405 // to the workgroup variable id.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004406 int spec_id = static_cast<int>(
4407 cast<ConstantInt>(Call->getOperand(0))->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04004408 const auto &info = LocalSpecIdInfoMap[spec_id];
4409 VMap[Call] = info.variable_id;
4410 break;
David Neto862b7d82018-06-14 18:48:37 -04004411 }
4412
4413 // Sampler initializers become a load of the corresponding sampler.
4414
4415 if (Callee->getName().equals("clspv.sampler.var.literal")) {
4416 // Map this to a load from the variable.
4417 const auto index_into_sampler_map =
4418 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4419
4420 // Generate an OpLoad
David Neto22f144c2017-06-12 14:26:21 -04004421 SPIRVOperandList Ops;
David Neto862b7d82018-06-14 18:48:37 -04004422 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004423
David Neto257c3892018-04-11 13:19:45 -04004424 Ops << MkId(lookupType(SamplerTy->getPointerElementType()))
alan-bakerb6b09dc2018-11-08 16:59:28 -05004425 << MkId(SamplerMapIndexToIDMap[static_cast<unsigned>(
4426 index_into_sampler_map)]);
David Neto22f144c2017-06-12 14:26:21 -04004427
David Neto862b7d82018-06-14 18:48:37 -04004428 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004429 SPIRVInstList.push_back(Inst);
David Neto862b7d82018-06-14 18:48:37 -04004430 VMap[Call] = load_id;
David Neto22f144c2017-06-12 14:26:21 -04004431 break;
4432 }
4433
Kévin Petit349c9502019-03-28 17:24:14 +00004434 // Handle SPIR-V intrinsics
4435 spv::Op opcode = StringSwitch<spv::Op>(Callee->getName())
Kévin Petit349c9502019-03-28 17:24:14 +00004436 .Case("spirv.atomic_add", spv::OpAtomicIAdd)
4437 .Case("spirv.atomic_sub", spv::OpAtomicISub)
4438 .Case("spirv.atomic_exchange", spv::OpAtomicExchange)
4439 .Case("spirv.atomic_inc", spv::OpAtomicIIncrement)
4440 .Case("spirv.atomic_dec", spv::OpAtomicIDecrement)
4441 .Case("spirv.atomic_compare_exchange", spv::OpAtomicCompareExchange)
4442 .Case("spirv.atomic_umin", spv::OpAtomicUMin)
4443 .Case("spirv.atomic_smin", spv::OpAtomicSMin)
4444 .Case("spirv.atomic_umax", spv::OpAtomicUMax)
4445 .Case("spirv.atomic_smax", spv::OpAtomicSMax)
4446 .Case("spirv.atomic_and", spv::OpAtomicAnd)
4447 .Case("spirv.atomic_or", spv::OpAtomicOr)
4448 .Case("spirv.atomic_xor", spv::OpAtomicXor)
4449 .Case("__spirv_control_barrier", spv::OpControlBarrier)
4450 .Case("__spirv_memory_barrier", spv::OpMemoryBarrier)
Kévin Petitfd6c24f2019-04-03 15:30:59 +01004451 .StartsWith("spirv.store_null", spv::OpStore)
Kévin Petit349c9502019-03-28 17:24:14 +00004452 .StartsWith("__spirv_isinf", spv::OpIsInf)
4453 .StartsWith("__spirv_isnan", spv::OpIsNan)
4454 .StartsWith("__spirv_allDv", spv::OpAll)
4455 .StartsWith("__spirv_anyDv", spv::OpAny)
4456 .Default(spv::OpNop);
David Neto22f144c2017-06-12 14:26:21 -04004457
Kévin Petit617a76d2019-04-04 13:54:16 +01004458 // If the switch above didn't have an entry maybe the intrinsic
4459 // is using the name mangling logic.
4460 bool usesMangler = false;
4461 if (opcode == spv::OpNop) {
4462 if (Callee->getName().startswith(clspv::SPIRVOpIntrinsicFunction())) {
4463 auto OpCst = cast<ConstantInt>(Call->getOperand(0));
4464 opcode = static_cast<spv::Op>(OpCst->getZExtValue());
4465 usesMangler = true;
4466 }
4467 }
4468
Kévin Petit349c9502019-03-28 17:24:14 +00004469 if (opcode != spv::OpNop) {
4470
David Neto22f144c2017-06-12 14:26:21 -04004471 SPIRVOperandList Ops;
4472
Kévin Petit349c9502019-03-28 17:24:14 +00004473 if (!I.getType()->isVoidTy()) {
4474 Ops << MkId(lookupType(I.getType()));
4475 }
David Neto22f144c2017-06-12 14:26:21 -04004476
Kévin Petit617a76d2019-04-04 13:54:16 +01004477 unsigned firstOperand = usesMangler ? 1 : 0;
4478 for (unsigned i = firstOperand; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004479 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004480 }
4481
Kévin Petit349c9502019-03-28 17:24:14 +00004482 if (!I.getType()->isVoidTy()) {
4483 VMap[&I] = nextID;
Kévin Petit8a560882019-03-21 15:24:34 +00004484 }
4485
Kévin Petit349c9502019-03-28 17:24:14 +00004486 SPIRVInstruction *Inst;
4487 if (!I.getType()->isVoidTy()) {
4488 Inst = new SPIRVInstruction(opcode, nextID++, Ops);
4489 } else {
4490 Inst = new SPIRVInstruction(opcode, Ops);
4491 }
Kévin Petit8a560882019-03-21 15:24:34 +00004492 SPIRVInstList.push_back(Inst);
4493 break;
4494 }
4495
David Neto22f144c2017-06-12 14:26:21 -04004496 if (Callee->getName().startswith("_Z3dot")) {
4497 // If the argument is a vector type, generate OpDot
4498 if (Call->getArgOperand(0)->getType()->isVectorTy()) {
4499 //
4500 // Generate OpDot.
4501 //
4502 SPIRVOperandList Ops;
4503
David Neto257c3892018-04-11 13:19:45 -04004504 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004505
4506 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004507 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004508 }
4509
4510 VMap[&I] = nextID;
4511
David Neto87846742018-04-11 17:36:22 -04004512 auto *Inst = new SPIRVInstruction(spv::OpDot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004513 SPIRVInstList.push_back(Inst);
4514 } else {
4515 //
4516 // Generate OpFMul.
4517 //
4518 SPIRVOperandList Ops;
4519
David Neto257c3892018-04-11 13:19:45 -04004520 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004521
4522 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004523 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004524 }
4525
4526 VMap[&I] = nextID;
4527
David Neto87846742018-04-11 17:36:22 -04004528 auto *Inst = new SPIRVInstruction(spv::OpFMul, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004529 SPIRVInstList.push_back(Inst);
4530 }
4531 break;
4532 }
4533
David Neto8505ebf2017-10-13 18:50:50 -04004534 if (Callee->getName().startswith("_Z4fmod")) {
4535 // OpenCL fmod(x,y) is x - y * trunc(x/y)
4536 // The sign for a non-zero result is taken from x.
4537 // (Try an example.)
4538 // So translate to OpFRem
4539
4540 SPIRVOperandList Ops;
4541
David Neto257c3892018-04-11 13:19:45 -04004542 Ops << MkId(lookupType(I.getType()));
David Neto8505ebf2017-10-13 18:50:50 -04004543
4544 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004545 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto8505ebf2017-10-13 18:50:50 -04004546 }
4547
4548 VMap[&I] = nextID;
4549
David Neto87846742018-04-11 17:36:22 -04004550 auto *Inst = new SPIRVInstruction(spv::OpFRem, nextID++, Ops);
David Neto8505ebf2017-10-13 18:50:50 -04004551 SPIRVInstList.push_back(Inst);
4552 break;
4553 }
4554
David Neto22f144c2017-06-12 14:26:21 -04004555 // spirv.copy_memory.* intrinsics become OpMemoryMemory's.
4556 if (Callee->getName().startswith("spirv.copy_memory")) {
4557 //
4558 // Generate OpCopyMemory.
4559 //
4560
4561 // Ops[0] = Dst ID
4562 // Ops[1] = Src ID
4563 // Ops[2] = Memory Access
4564 // Ops[3] = Alignment
4565
4566 auto IsVolatile =
4567 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
4568
4569 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
4570 : spv::MemoryAccessMaskNone;
4571
4572 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
4573
4574 auto Alignment =
4575 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4576
David Neto257c3892018-04-11 13:19:45 -04004577 SPIRVOperandList Ops;
4578 Ops << MkId(VMap[Call->getArgOperand(0)])
4579 << MkId(VMap[Call->getArgOperand(1)]) << MkNum(MemoryAccess)
4580 << MkNum(static_cast<uint32_t>(Alignment));
David Neto22f144c2017-06-12 14:26:21 -04004581
David Neto87846742018-04-11 17:36:22 -04004582 auto *Inst = new SPIRVInstruction(spv::OpCopyMemory, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004583
4584 SPIRVInstList.push_back(Inst);
4585
4586 break;
4587 }
4588
David Neto22f144c2017-06-12 14:26:21 -04004589 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
4590 // Additionally, OpTypeSampledImage is generated.
4591 if (Callee->getName().equals(
4592 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
4593 Callee->getName().equals(
4594 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
4595 //
4596 // Generate OpSampledImage.
4597 //
4598 // Ops[0] = Result Type ID
4599 // Ops[1] = Image ID
4600 // Ops[2] = Sampler ID
4601 //
4602 SPIRVOperandList Ops;
4603
4604 Value *Image = Call->getArgOperand(0);
4605 Value *Sampler = Call->getArgOperand(1);
4606 Value *Coordinate = Call->getArgOperand(2);
4607
4608 TypeMapType &OpImageTypeMap = getImageTypeMap();
4609 Type *ImageTy = Image->getType()->getPointerElementType();
4610 uint32_t ImageTyID = OpImageTypeMap[ImageTy];
David Neto22f144c2017-06-12 14:26:21 -04004611 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004612 uint32_t SamplerID = VMap[Sampler];
David Neto257c3892018-04-11 13:19:45 -04004613
4614 Ops << MkId(ImageTyID) << MkId(ImageID) << MkId(SamplerID);
David Neto22f144c2017-06-12 14:26:21 -04004615
4616 uint32_t SampledImageID = nextID;
4617
David Neto87846742018-04-11 17:36:22 -04004618 auto *Inst = new SPIRVInstruction(spv::OpSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004619 SPIRVInstList.push_back(Inst);
4620
4621 //
4622 // Generate OpImageSampleExplicitLod.
4623 //
4624 // Ops[0] = Result Type ID
4625 // Ops[1] = Sampled Image ID
4626 // Ops[2] = Coordinate ID
4627 // Ops[3] = Image Operands Type ID
4628 // Ops[4] ... Ops[n] = Operands ID
4629 //
4630 Ops.clear();
4631
David Neto257c3892018-04-11 13:19:45 -04004632 Ops << MkId(lookupType(Call->getType())) << MkId(SampledImageID)
4633 << MkId(VMap[Coordinate]) << MkNum(spv::ImageOperandsLodMask);
David Neto22f144c2017-06-12 14:26:21 -04004634
4635 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
David Neto257c3892018-04-11 13:19:45 -04004636 Ops << MkId(VMap[CstFP0]);
David Neto22f144c2017-06-12 14:26:21 -04004637
4638 VMap[&I] = nextID;
4639
David Neto87846742018-04-11 17:36:22 -04004640 Inst = new SPIRVInstruction(spv::OpImageSampleExplicitLod, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004641 SPIRVInstList.push_back(Inst);
4642 break;
4643 }
4644
4645 // write_imagef is mapped to OpImageWrite.
4646 if (Callee->getName().equals(
4647 "_Z12write_imagef14ocl_image2d_woDv2_iDv4_f") ||
4648 Callee->getName().equals(
4649 "_Z12write_imagef14ocl_image3d_woDv4_iDv4_f")) {
4650 //
4651 // Generate OpImageWrite.
4652 //
4653 // Ops[0] = Image ID
4654 // Ops[1] = Coordinate ID
4655 // Ops[2] = Texel ID
4656 // Ops[3] = (Optional) Image Operands Type (Literal Number)
4657 // Ops[4] ... Ops[n] = (Optional) Operands ID
4658 //
4659 SPIRVOperandList Ops;
4660
4661 Value *Image = Call->getArgOperand(0);
4662 Value *Coordinate = Call->getArgOperand(1);
4663 Value *Texel = Call->getArgOperand(2);
4664
4665 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004666 uint32_t CoordinateID = VMap[Coordinate];
David Neto22f144c2017-06-12 14:26:21 -04004667 uint32_t TexelID = VMap[Texel];
David Neto257c3892018-04-11 13:19:45 -04004668 Ops << MkId(ImageID) << MkId(CoordinateID) << MkId(TexelID);
David Neto22f144c2017-06-12 14:26:21 -04004669
David Neto87846742018-04-11 17:36:22 -04004670 auto *Inst = new SPIRVInstruction(spv::OpImageWrite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004671 SPIRVInstList.push_back(Inst);
4672 break;
4673 }
4674
David Neto5c22a252018-03-15 16:07:41 -04004675 // get_image_width is mapped to OpImageQuerySize
4676 if (Callee->getName().equals("_Z15get_image_width14ocl_image2d_ro") ||
4677 Callee->getName().equals("_Z15get_image_width14ocl_image2d_wo") ||
4678 Callee->getName().equals("_Z16get_image_height14ocl_image2d_ro") ||
4679 Callee->getName().equals("_Z16get_image_height14ocl_image2d_wo")) {
4680 //
4681 // Generate OpImageQuerySize, then pull out the right component.
4682 // Assume 2D image for now.
4683 //
4684 // Ops[0] = Image ID
4685 //
4686 // %sizes = OpImageQuerySizes %uint2 %im
4687 // %result = OpCompositeExtract %uint %sizes 0-or-1
4688 SPIRVOperandList Ops;
4689
4690 // Implement:
4691 // %sizes = OpImageQuerySizes %uint2 %im
4692 uint32_t SizesTypeID =
4693 TypeMap[VectorType::get(Type::getInt32Ty(Context), 2)];
David Neto5c22a252018-03-15 16:07:41 -04004694 Value *Image = Call->getArgOperand(0);
4695 uint32_t ImageID = VMap[Image];
David Neto257c3892018-04-11 13:19:45 -04004696 Ops << MkId(SizesTypeID) << MkId(ImageID);
David Neto5c22a252018-03-15 16:07:41 -04004697
4698 uint32_t SizesID = nextID++;
David Neto87846742018-04-11 17:36:22 -04004699 auto *QueryInst =
4700 new SPIRVInstruction(spv::OpImageQuerySize, SizesID, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004701 SPIRVInstList.push_back(QueryInst);
4702
4703 // Reset value map entry since we generated an intermediate instruction.
4704 VMap[&I] = nextID;
4705
4706 // Implement:
4707 // %result = OpCompositeExtract %uint %sizes 0-or-1
4708 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004709 Ops << MkId(TypeMap[I.getType()]) << MkId(SizesID);
David Neto5c22a252018-03-15 16:07:41 -04004710
4711 uint32_t component = Callee->getName().contains("height") ? 1 : 0;
David Neto257c3892018-04-11 13:19:45 -04004712 Ops << MkNum(component);
David Neto5c22a252018-03-15 16:07:41 -04004713
David Neto87846742018-04-11 17:36:22 -04004714 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004715 SPIRVInstList.push_back(Inst);
4716 break;
4717 }
4718
David Neto22f144c2017-06-12 14:26:21 -04004719 // Call instrucion is deferred because it needs function's ID. Record
4720 // slot's location on SPIRVInstructionList.
4721 DeferredInsts.push_back(
4722 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4723
David Neto3fbb4072017-10-16 11:28:14 -04004724 // Check whether the implementation of this call uses an extended
4725 // instruction plus one more value-producing instruction. If so, then
4726 // reserve the id for the extra value-producing slot.
4727 glsl::ExtInst EInst = getIndirectExtInstEnum(Callee->getName());
4728 if (EInst != kGlslExtInstBad) {
4729 // Reserve a spot for the extra value.
David Neto4d02a532017-09-17 12:57:44 -04004730 // Increase nextID.
David Neto22f144c2017-06-12 14:26:21 -04004731 VMap[&I] = nextID;
4732 nextID++;
4733 }
4734 break;
4735 }
4736 case Instruction::Ret: {
4737 unsigned NumOps = I.getNumOperands();
4738 if (NumOps == 0) {
4739 //
4740 // Generate OpReturn.
4741 //
David Neto87846742018-04-11 17:36:22 -04004742 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpReturn, {}));
David Neto22f144c2017-06-12 14:26:21 -04004743 } else {
4744 //
4745 // Generate OpReturnValue.
4746 //
4747
4748 // Ops[0] = Return Value ID
4749 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004750
4751 Ops << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004752
David Neto87846742018-04-11 17:36:22 -04004753 auto *Inst = new SPIRVInstruction(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004754 SPIRVInstList.push_back(Inst);
4755 break;
4756 }
4757 break;
4758 }
4759 }
4760}
4761
4762void SPIRVProducerPass::GenerateFuncEpilogue() {
4763 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4764
4765 //
4766 // Generate OpFunctionEnd
4767 //
4768
David Neto87846742018-04-11 17:36:22 -04004769 auto *Inst = new SPIRVInstruction(spv::OpFunctionEnd, {});
David Neto22f144c2017-06-12 14:26:21 -04004770 SPIRVInstList.push_back(Inst);
4771}
4772
4773bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
alan-bakerb39c8262019-03-08 14:03:37 -05004774 // Don't specialize <4 x i8> if i8 is generally supported.
4775 if (clspv::Option::Int8Support())
4776 return false;
4777
David Neto22f144c2017-06-12 14:26:21 -04004778 LLVMContext &Context = Ty->getContext();
4779 if (Ty->isVectorTy()) {
4780 if (Ty->getVectorElementType() == Type::getInt8Ty(Context) &&
4781 Ty->getVectorNumElements() == 4) {
4782 return true;
4783 }
4784 }
4785
4786 return false;
4787}
4788
David Neto257c3892018-04-11 13:19:45 -04004789uint32_t SPIRVProducerPass::GetI32Zero() {
4790 if (0 == constant_i32_zero_id_) {
4791 llvm_unreachable("Requesting a 32-bit integer constant but it is not "
4792 "defined in the SPIR-V module");
4793 }
4794 return constant_i32_zero_id_;
4795}
4796
David Neto22f144c2017-06-12 14:26:21 -04004797void SPIRVProducerPass::HandleDeferredInstruction() {
4798 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4799 ValueMapType &VMap = getValueMap();
4800 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4801
4802 for (auto DeferredInst = DeferredInsts.rbegin();
4803 DeferredInst != DeferredInsts.rend(); ++DeferredInst) {
4804 Value *Inst = std::get<0>(*DeferredInst);
4805 SPIRVInstructionList::iterator InsertPoint = ++std::get<1>(*DeferredInst);
4806 if (InsertPoint != SPIRVInstList.end()) {
4807 while ((*InsertPoint)->getOpcode() == spv::OpPhi) {
4808 ++InsertPoint;
4809 }
4810 }
4811
4812 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
4813 // Check whether basic block, which has this branch instruction, is loop
4814 // header or not. If it is loop header, generate OpLoopMerge and
4815 // OpBranchConditional.
4816 Function *Func = Br->getParent()->getParent();
4817 DominatorTree &DT =
4818 getAnalysis<DominatorTreeWrapperPass>(*Func).getDomTree();
4819 const LoopInfo &LI =
4820 getAnalysis<LoopInfoWrapperPass>(*Func).getLoopInfo();
4821
4822 BasicBlock *BrBB = Br->getParent();
4823 if (LI.isLoopHeader(BrBB)) {
4824 Value *ContinueBB = nullptr;
4825 Value *MergeBB = nullptr;
4826
4827 Loop *L = LI.getLoopFor(BrBB);
4828 MergeBB = L->getExitBlock();
4829 if (!MergeBB) {
4830 // StructurizeCFG pass converts CFG into triangle shape and the cfg
4831 // has regions with single entry/exit. As a result, loop should not
4832 // have multiple exits.
4833 llvm_unreachable("Loop has multiple exits???");
4834 }
4835
4836 if (L->isLoopLatch(BrBB)) {
4837 ContinueBB = BrBB;
4838 } else {
4839 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
4840 // block.
4841 BasicBlock *Header = L->getHeader();
4842 BasicBlock *Latch = L->getLoopLatch();
4843 for (BasicBlock *BB : L->blocks()) {
4844 if (BB == Header) {
4845 continue;
4846 }
4847
4848 // Check whether block dominates block with back-edge.
4849 if (DT.dominates(BB, Latch)) {
4850 ContinueBB = BB;
4851 }
4852 }
4853
4854 if (!ContinueBB) {
4855 llvm_unreachable("Wrong continue block from loop");
4856 }
4857 }
4858
4859 //
4860 // Generate OpLoopMerge.
4861 //
4862 // Ops[0] = Merge Block ID
4863 // Ops[1] = Continue Target ID
4864 // Ops[2] = Selection Control
4865 SPIRVOperandList Ops;
4866
4867 // StructurizeCFG pass already manipulated CFG. Just use false block of
4868 // branch instruction as merge block.
4869 uint32_t MergeBBID = VMap[MergeBB];
David Neto22f144c2017-06-12 14:26:21 -04004870 uint32_t ContinueBBID = VMap[ContinueBB];
David Neto257c3892018-04-11 13:19:45 -04004871 Ops << MkId(MergeBBID) << MkId(ContinueBBID)
4872 << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004873
David Neto87846742018-04-11 17:36:22 -04004874 auto *MergeInst = new SPIRVInstruction(spv::OpLoopMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004875 SPIRVInstList.insert(InsertPoint, MergeInst);
4876
4877 } else if (Br->isConditional()) {
4878 bool HasBackEdge = false;
4879
4880 for (unsigned i = 0; i < Br->getNumSuccessors(); i++) {
4881 if (LI.isLoopHeader(Br->getSuccessor(i))) {
4882 HasBackEdge = true;
4883 }
4884 }
4885 if (!HasBackEdge) {
4886 //
4887 // Generate OpSelectionMerge.
4888 //
4889 // Ops[0] = Merge Block ID
4890 // Ops[1] = Selection Control
4891 SPIRVOperandList Ops;
4892
4893 // StructurizeCFG pass already manipulated CFG. Just use false block
4894 // of branch instruction as merge block.
4895 uint32_t MergeBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004896 Ops << MkId(MergeBBID) << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004897
David Neto87846742018-04-11 17:36:22 -04004898 auto *MergeInst = new SPIRVInstruction(spv::OpSelectionMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004899 SPIRVInstList.insert(InsertPoint, MergeInst);
4900 }
4901 }
4902
4903 if (Br->isConditional()) {
4904 //
4905 // Generate OpBranchConditional.
4906 //
4907 // Ops[0] = Condition ID
4908 // Ops[1] = True Label ID
4909 // Ops[2] = False Label ID
4910 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
4911 SPIRVOperandList Ops;
4912
4913 uint32_t CondID = VMap[Br->getCondition()];
David Neto22f144c2017-06-12 14:26:21 -04004914 uint32_t TrueBBID = VMap[Br->getSuccessor(0)];
David Neto22f144c2017-06-12 14:26:21 -04004915 uint32_t FalseBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004916
4917 Ops << MkId(CondID) << MkId(TrueBBID) << MkId(FalseBBID);
David Neto22f144c2017-06-12 14:26:21 -04004918
David Neto87846742018-04-11 17:36:22 -04004919 auto *BrInst = new SPIRVInstruction(spv::OpBranchConditional, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004920 SPIRVInstList.insert(InsertPoint, BrInst);
4921 } else {
4922 //
4923 // Generate OpBranch.
4924 //
4925 // Ops[0] = Target Label ID
4926 SPIRVOperandList Ops;
4927
4928 uint32_t TargetID = VMap[Br->getSuccessor(0)];
David Neto257c3892018-04-11 13:19:45 -04004929 Ops << MkId(TargetID);
David Neto22f144c2017-06-12 14:26:21 -04004930
David Neto87846742018-04-11 17:36:22 -04004931 SPIRVInstList.insert(InsertPoint,
4932 new SPIRVInstruction(spv::OpBranch, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004933 }
4934 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
alan-baker5b86ed72019-02-15 08:26:50 -05004935 if (PHI->getType()->isPointerTy()) {
4936 // OpPhi on pointers requires variable pointers.
4937 setVariablePointersCapabilities(
4938 PHI->getType()->getPointerAddressSpace());
4939 if (!hasVariablePointers() && !selectFromSameObject(PHI)) {
4940 setVariablePointers(true);
4941 }
4942 }
4943
David Neto22f144c2017-06-12 14:26:21 -04004944 //
4945 // Generate OpPhi.
4946 //
4947 // Ops[0] = Result Type ID
4948 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
4949 SPIRVOperandList Ops;
4950
David Neto257c3892018-04-11 13:19:45 -04004951 Ops << MkId(lookupType(PHI->getType()));
David Neto22f144c2017-06-12 14:26:21 -04004952
David Neto22f144c2017-06-12 14:26:21 -04004953 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
4954 uint32_t VarID = VMap[PHI->getIncomingValue(i)];
David Neto22f144c2017-06-12 14:26:21 -04004955 uint32_t ParentID = VMap[PHI->getIncomingBlock(i)];
David Neto257c3892018-04-11 13:19:45 -04004956 Ops << MkId(VarID) << MkId(ParentID);
David Neto22f144c2017-06-12 14:26:21 -04004957 }
4958
4959 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04004960 InsertPoint,
4961 new SPIRVInstruction(spv::OpPhi, std::get<2>(*DeferredInst), Ops));
David Neto22f144c2017-06-12 14:26:21 -04004962 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
4963 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04004964 auto callee_name = Callee->getName();
4965 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04004966
4967 if (EInst) {
4968 uint32_t &ExtInstImportID = getOpExtInstImportID();
4969
4970 //
4971 // Generate OpExtInst.
4972 //
4973
4974 // Ops[0] = Result Type ID
4975 // Ops[1] = Set ID (OpExtInstImport ID)
4976 // Ops[2] = Instruction Number (Literal Number)
4977 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
4978 SPIRVOperandList Ops;
4979
David Neto862b7d82018-06-14 18:48:37 -04004980 Ops << MkId(lookupType(Call->getType())) << MkId(ExtInstImportID)
4981 << MkNum(EInst);
David Neto22f144c2017-06-12 14:26:21 -04004982
David Neto22f144c2017-06-12 14:26:21 -04004983 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
4984 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004985 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004986 }
4987
David Neto87846742018-04-11 17:36:22 -04004988 auto *ExtInst = new SPIRVInstruction(spv::OpExtInst,
4989 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04004990 SPIRVInstList.insert(InsertPoint, ExtInst);
4991
David Neto3fbb4072017-10-16 11:28:14 -04004992 const auto IndirectExtInst = getIndirectExtInstEnum(callee_name);
4993 if (IndirectExtInst != kGlslExtInstBad) {
4994 // Generate one more instruction that uses the result of the extended
4995 // instruction. Its result id is one more than the id of the
4996 // extended instruction.
David Neto22f144c2017-06-12 14:26:21 -04004997 LLVMContext &Context =
4998 Call->getParent()->getParent()->getParent()->getContext();
David Neto22f144c2017-06-12 14:26:21 -04004999
David Neto3fbb4072017-10-16 11:28:14 -04005000 auto generate_extra_inst = [this, &Context, &Call, &DeferredInst,
5001 &VMap, &SPIRVInstList, &InsertPoint](
5002 spv::Op opcode, Constant *constant) {
5003 //
5004 // Generate instruction like:
5005 // result = opcode constant <extinst-result>
5006 //
5007 // Ops[0] = Result Type ID
5008 // Ops[1] = Operand 0 ;; the constant, suitably splatted
5009 // Ops[2] = Operand 1 ;; the result of the extended instruction
5010 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04005011
David Neto3fbb4072017-10-16 11:28:14 -04005012 Type *resultTy = Call->getType();
David Neto257c3892018-04-11 13:19:45 -04005013 Ops << MkId(lookupType(resultTy));
David Neto3fbb4072017-10-16 11:28:14 -04005014
5015 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
5016 constant = ConstantVector::getSplat(
5017 static_cast<unsigned>(vectorTy->getNumElements()), constant);
5018 }
David Neto257c3892018-04-11 13:19:45 -04005019 Ops << MkId(VMap[constant]) << MkId(std::get<2>(*DeferredInst));
David Neto3fbb4072017-10-16 11:28:14 -04005020
5021 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005022 InsertPoint, new SPIRVInstruction(
5023 opcode, std::get<2>(*DeferredInst) + 1, Ops));
David Neto3fbb4072017-10-16 11:28:14 -04005024 };
5025
5026 switch (IndirectExtInst) {
5027 case glsl::ExtInstFindUMsb: // Implementing clz
5028 generate_extra_inst(
5029 spv::OpISub, ConstantInt::get(Type::getInt32Ty(Context), 31));
5030 break;
5031 case glsl::ExtInstAcos: // Implementing acospi
5032 case glsl::ExtInstAsin: // Implementing asinpi
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005033 case glsl::ExtInstAtan: // Implementing atanpi
David Neto3fbb4072017-10-16 11:28:14 -04005034 case glsl::ExtInstAtan2: // Implementing atan2pi
5035 generate_extra_inst(
5036 spv::OpFMul,
5037 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
5038 break;
5039
5040 default:
5041 assert(false && "internally inconsistent");
David Neto4d02a532017-09-17 12:57:44 -04005042 }
David Neto22f144c2017-06-12 14:26:21 -04005043 }
David Neto3fbb4072017-10-16 11:28:14 -04005044
alan-bakerb39c8262019-03-08 14:03:37 -05005045 } else if (callee_name.startswith("_Z8popcount")) {
David Neto22f144c2017-06-12 14:26:21 -04005046 //
5047 // Generate OpBitCount
5048 //
5049 // Ops[0] = Result Type ID
5050 // Ops[1] = Base ID
David Neto257c3892018-04-11 13:19:45 -04005051 SPIRVOperandList Ops;
5052 Ops << MkId(lookupType(Call->getType()))
5053 << MkId(VMap[Call->getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04005054
5055 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005056 InsertPoint, new SPIRVInstruction(spv::OpBitCount,
David Neto22f144c2017-06-12 14:26:21 -04005057 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005058
David Neto862b7d82018-06-14 18:48:37 -04005059 } else if (callee_name.startswith(kCompositeConstructFunctionPrefix)) {
David Netoab03f432017-11-03 17:00:44 -04005060
5061 // Generate an OpCompositeConstruct
5062 SPIRVOperandList Ops;
5063
5064 // The result type.
David Neto257c3892018-04-11 13:19:45 -04005065 Ops << MkId(lookupType(Call->getType()));
David Netoab03f432017-11-03 17:00:44 -04005066
5067 for (Use &use : Call->arg_operands()) {
David Neto257c3892018-04-11 13:19:45 -04005068 Ops << MkId(VMap[use.get()]);
David Netoab03f432017-11-03 17:00:44 -04005069 }
5070
5071 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005072 InsertPoint, new SPIRVInstruction(spv::OpCompositeConstruct,
5073 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005074
Alan Baker202c8c72018-08-13 13:47:44 -04005075 } else if (callee_name.startswith(clspv::ResourceAccessorFunction())) {
5076
5077 // We have already mapped the call's result value to an ID.
5078 // Don't generate any code now.
5079
5080 } else if (callee_name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04005081
5082 // We have already mapped the call's result value to an ID.
5083 // Don't generate any code now.
5084
David Neto22f144c2017-06-12 14:26:21 -04005085 } else {
alan-baker5b86ed72019-02-15 08:26:50 -05005086 if (Call->getType()->isPointerTy()) {
5087 // Functions returning pointers require variable pointers.
5088 setVariablePointersCapabilities(
5089 Call->getType()->getPointerAddressSpace());
5090 }
5091
David Neto22f144c2017-06-12 14:26:21 -04005092 //
5093 // Generate OpFunctionCall.
5094 //
5095
5096 // Ops[0] = Result Type ID
5097 // Ops[1] = Callee Function ID
5098 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
5099 SPIRVOperandList Ops;
5100
David Neto862b7d82018-06-14 18:48:37 -04005101 Ops << MkId(lookupType(Call->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005102
5103 uint32_t CalleeID = VMap[Callee];
David Neto43568eb2017-10-13 18:25:25 -04005104 if (CalleeID == 0) {
5105 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04005106 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04005107 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
5108 // causes an infinite loop. Instead, go ahead and generate
5109 // the bad function call. A validator will catch the 0-Id.
5110 // llvm_unreachable("Can't translate function call");
5111 }
David Neto22f144c2017-06-12 14:26:21 -04005112
David Neto257c3892018-04-11 13:19:45 -04005113 Ops << MkId(CalleeID);
David Neto22f144c2017-06-12 14:26:21 -04005114
David Neto22f144c2017-06-12 14:26:21 -04005115 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5116 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
alan-baker5b86ed72019-02-15 08:26:50 -05005117 auto *operand = Call->getOperand(i);
5118 if (operand->getType()->isPointerTy()) {
5119 auto sc =
5120 GetStorageClass(operand->getType()->getPointerAddressSpace());
5121 if (sc == spv::StorageClassStorageBuffer) {
5122 // Passing SSBO by reference requires variable pointers storage
5123 // buffer.
5124 setVariablePointersStorageBuffer(true);
5125 } else if (sc == spv::StorageClassWorkgroup) {
5126 // Workgroup references require variable pointers if they are not
5127 // memory object declarations.
5128 if (auto *operand_call = dyn_cast<CallInst>(operand)) {
5129 // Workgroup accessor represents a variable reference.
5130 if (!operand_call->getCalledFunction()->getName().startswith(
5131 clspv::WorkgroupAccessorFunction()))
5132 setVariablePointers(true);
5133 } else {
5134 // Arguments are function parameters.
5135 if (!isa<Argument>(operand))
5136 setVariablePointers(true);
5137 }
5138 }
5139 }
5140 Ops << MkId(VMap[operand]);
David Neto22f144c2017-06-12 14:26:21 -04005141 }
5142
David Neto87846742018-04-11 17:36:22 -04005143 auto *CallInst = new SPIRVInstruction(spv::OpFunctionCall,
5144 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005145 SPIRVInstList.insert(InsertPoint, CallInst);
5146 }
5147 }
5148 }
5149}
5150
David Neto1a1a0582017-07-07 12:01:44 -04005151void SPIRVProducerPass::HandleDeferredDecorations(const DataLayout &DL) {
Alan Baker202c8c72018-08-13 13:47:44 -04005152 if (getTypesNeedingArrayStride().empty() && LocalArgSpecIds.empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04005153 return;
David Netoc6f3ab22018-04-06 18:02:31 -04005154 }
David Neto1a1a0582017-07-07 12:01:44 -04005155
5156 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto1a1a0582017-07-07 12:01:44 -04005157
5158 // Find an iterator pointing just past the last decoration.
5159 bool seen_decorations = false;
5160 auto DecoInsertPoint =
5161 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
5162 [&seen_decorations](SPIRVInstruction *Inst) -> bool {
5163 const bool is_decoration =
5164 Inst->getOpcode() == spv::OpDecorate ||
5165 Inst->getOpcode() == spv::OpMemberDecorate;
5166 if (is_decoration) {
5167 seen_decorations = true;
5168 return false;
5169 } else {
5170 return seen_decorations;
5171 }
5172 });
5173
David Netoc6f3ab22018-04-06 18:02:31 -04005174 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
5175 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07005176 for (auto *type : getTypesNeedingArrayStride()) {
5177 Type *elemTy = nullptr;
5178 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
5179 elemTy = ptrTy->getElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005180 } else if (auto *arrayTy = dyn_cast<ArrayType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005181 elemTy = arrayTy->getArrayElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005182 } else if (auto *seqTy = dyn_cast<SequentialType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005183 elemTy = seqTy->getSequentialElementType();
5184 } else {
5185 errs() << "Unhandled strided type " << *type << "\n";
5186 llvm_unreachable("Unhandled strided type");
5187 }
David Neto1a1a0582017-07-07 12:01:44 -04005188
5189 // Ops[0] = Target ID
5190 // Ops[1] = Decoration (ArrayStride)
5191 // Ops[2] = Stride number (Literal Number)
5192 SPIRVOperandList Ops;
5193
David Neto85082642018-03-24 06:55:20 -07005194 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Alan Bakerfcda9482018-10-02 17:09:59 -04005195 const uint32_t stride = static_cast<uint32_t>(GetTypeAllocSize(elemTy, DL));
David Neto257c3892018-04-11 13:19:45 -04005196
5197 Ops << MkId(lookupType(type)) << MkNum(spv::DecorationArrayStride)
5198 << MkNum(stride);
David Neto1a1a0582017-07-07 12:01:44 -04005199
David Neto87846742018-04-11 17:36:22 -04005200 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto1a1a0582017-07-07 12:01:44 -04005201 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
5202 }
David Netoc6f3ab22018-04-06 18:02:31 -04005203
5204 // Emit SpecId decorations targeting the array size value.
Alan Baker202c8c72018-08-13 13:47:44 -04005205 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
5206 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005207 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04005208 SPIRVOperandList Ops;
5209 Ops << MkId(arg_info.array_size_id) << MkNum(spv::DecorationSpecId)
5210 << MkNum(arg_info.spec_id);
5211 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04005212 new SPIRVInstruction(spv::OpDecorate, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04005213 }
David Neto1a1a0582017-07-07 12:01:44 -04005214}
5215
David Neto22f144c2017-06-12 14:26:21 -04005216glsl::ExtInst SPIRVProducerPass::getExtInstEnum(StringRef Name) {
5217 return StringSwitch<glsl::ExtInst>(Name)
alan-bakerb39c8262019-03-08 14:03:37 -05005218 .Case("_Z3absc", glsl::ExtInst::ExtInstSAbs)
5219 .Case("_Z3absDv2_c", glsl::ExtInst::ExtInstSAbs)
5220 .Case("_Z3absDv3_c", glsl::ExtInst::ExtInstSAbs)
5221 .Case("_Z3absDv4_c", glsl::ExtInst::ExtInstSAbs)
Kévin Petit2444e9b2018-11-09 14:14:37 +00005222 .Case("_Z3abss", glsl::ExtInst::ExtInstSAbs)
5223 .Case("_Z3absDv2_s", glsl::ExtInst::ExtInstSAbs)
5224 .Case("_Z3absDv3_s", glsl::ExtInst::ExtInstSAbs)
5225 .Case("_Z3absDv4_s", glsl::ExtInst::ExtInstSAbs)
David Neto22f144c2017-06-12 14:26:21 -04005226 .Case("_Z3absi", glsl::ExtInst::ExtInstSAbs)
5227 .Case("_Z3absDv2_i", glsl::ExtInst::ExtInstSAbs)
5228 .Case("_Z3absDv3_i", glsl::ExtInst::ExtInstSAbs)
5229 .Case("_Z3absDv4_i", glsl::ExtInst::ExtInstSAbs)
Kévin Petit2444e9b2018-11-09 14:14:37 +00005230 .Case("_Z3absl", glsl::ExtInst::ExtInstSAbs)
5231 .Case("_Z3absDv2_l", glsl::ExtInst::ExtInstSAbs)
5232 .Case("_Z3absDv3_l", glsl::ExtInst::ExtInstSAbs)
5233 .Case("_Z3absDv4_l", glsl::ExtInst::ExtInstSAbs)
alan-bakerb39c8262019-03-08 14:03:37 -05005234 .Case("_Z5clampccc", glsl::ExtInst::ExtInstSClamp)
5235 .Case("_Z5clampDv2_cS_S_", glsl::ExtInst::ExtInstSClamp)
5236 .Case("_Z5clampDv3_cS_S_", glsl::ExtInst::ExtInstSClamp)
5237 .Case("_Z5clampDv4_cS_S_", glsl::ExtInst::ExtInstSClamp)
5238 .Case("_Z5clamphhh", glsl::ExtInst::ExtInstUClamp)
5239 .Case("_Z5clampDv2_hS_S_", glsl::ExtInst::ExtInstUClamp)
5240 .Case("_Z5clampDv3_hS_S_", glsl::ExtInst::ExtInstUClamp)
5241 .Case("_Z5clampDv4_hS_S_", glsl::ExtInst::ExtInstUClamp)
Kévin Petit495255d2019-03-06 13:56:48 +00005242 .Case("_Z5clampsss", glsl::ExtInst::ExtInstSClamp)
5243 .Case("_Z5clampDv2_sS_S_", glsl::ExtInst::ExtInstSClamp)
5244 .Case("_Z5clampDv3_sS_S_", glsl::ExtInst::ExtInstSClamp)
5245 .Case("_Z5clampDv4_sS_S_", glsl::ExtInst::ExtInstSClamp)
5246 .Case("_Z5clampttt", glsl::ExtInst::ExtInstUClamp)
5247 .Case("_Z5clampDv2_tS_S_", glsl::ExtInst::ExtInstUClamp)
5248 .Case("_Z5clampDv3_tS_S_", glsl::ExtInst::ExtInstUClamp)
5249 .Case("_Z5clampDv4_tS_S_", glsl::ExtInst::ExtInstUClamp)
David Neto22f144c2017-06-12 14:26:21 -04005250 .Case("_Z5clampiii", glsl::ExtInst::ExtInstSClamp)
5251 .Case("_Z5clampDv2_iS_S_", glsl::ExtInst::ExtInstSClamp)
5252 .Case("_Z5clampDv3_iS_S_", glsl::ExtInst::ExtInstSClamp)
5253 .Case("_Z5clampDv4_iS_S_", glsl::ExtInst::ExtInstSClamp)
5254 .Case("_Z5clampjjj", glsl::ExtInst::ExtInstUClamp)
5255 .Case("_Z5clampDv2_jS_S_", glsl::ExtInst::ExtInstUClamp)
5256 .Case("_Z5clampDv3_jS_S_", glsl::ExtInst::ExtInstUClamp)
5257 .Case("_Z5clampDv4_jS_S_", glsl::ExtInst::ExtInstUClamp)
Kévin Petit495255d2019-03-06 13:56:48 +00005258 .Case("_Z5clamplll", glsl::ExtInst::ExtInstSClamp)
5259 .Case("_Z5clampDv2_lS_S_", glsl::ExtInst::ExtInstSClamp)
5260 .Case("_Z5clampDv3_lS_S_", glsl::ExtInst::ExtInstSClamp)
5261 .Case("_Z5clampDv4_lS_S_", glsl::ExtInst::ExtInstSClamp)
5262 .Case("_Z5clampmmm", glsl::ExtInst::ExtInstUClamp)
5263 .Case("_Z5clampDv2_mS_S_", glsl::ExtInst::ExtInstUClamp)
5264 .Case("_Z5clampDv3_mS_S_", glsl::ExtInst::ExtInstUClamp)
5265 .Case("_Z5clampDv4_mS_S_", glsl::ExtInst::ExtInstUClamp)
David Neto22f144c2017-06-12 14:26:21 -04005266 .Case("_Z5clampfff", glsl::ExtInst::ExtInstFClamp)
5267 .Case("_Z5clampDv2_fS_S_", glsl::ExtInst::ExtInstFClamp)
5268 .Case("_Z5clampDv3_fS_S_", glsl::ExtInst::ExtInstFClamp)
5269 .Case("_Z5clampDv4_fS_S_", glsl::ExtInst::ExtInstFClamp)
alan-bakerb39c8262019-03-08 14:03:37 -05005270 .Case("_Z3maxcc", glsl::ExtInst::ExtInstSMax)
5271 .Case("_Z3maxDv2_cS_", glsl::ExtInst::ExtInstSMax)
5272 .Case("_Z3maxDv3_cS_", glsl::ExtInst::ExtInstSMax)
5273 .Case("_Z3maxDv4_cS_", glsl::ExtInst::ExtInstSMax)
5274 .Case("_Z3maxhh", glsl::ExtInst::ExtInstUMax)
5275 .Case("_Z3maxDv2_hS_", glsl::ExtInst::ExtInstUMax)
5276 .Case("_Z3maxDv3_hS_", glsl::ExtInst::ExtInstUMax)
5277 .Case("_Z3maxDv4_hS_", glsl::ExtInst::ExtInstUMax)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005278 .Case("_Z3maxss", glsl::ExtInst::ExtInstSMax)
5279 .Case("_Z3maxDv2_sS_", glsl::ExtInst::ExtInstSMax)
5280 .Case("_Z3maxDv3_sS_", glsl::ExtInst::ExtInstSMax)
5281 .Case("_Z3maxDv4_sS_", glsl::ExtInst::ExtInstSMax)
5282 .Case("_Z3maxtt", glsl::ExtInst::ExtInstUMax)
5283 .Case("_Z3maxDv2_tS_", glsl::ExtInst::ExtInstUMax)
5284 .Case("_Z3maxDv3_tS_", glsl::ExtInst::ExtInstUMax)
5285 .Case("_Z3maxDv4_tS_", glsl::ExtInst::ExtInstUMax)
David Neto22f144c2017-06-12 14:26:21 -04005286 .Case("_Z3maxii", glsl::ExtInst::ExtInstSMax)
5287 .Case("_Z3maxDv2_iS_", glsl::ExtInst::ExtInstSMax)
5288 .Case("_Z3maxDv3_iS_", glsl::ExtInst::ExtInstSMax)
5289 .Case("_Z3maxDv4_iS_", glsl::ExtInst::ExtInstSMax)
5290 .Case("_Z3maxjj", glsl::ExtInst::ExtInstUMax)
5291 .Case("_Z3maxDv2_jS_", glsl::ExtInst::ExtInstUMax)
5292 .Case("_Z3maxDv3_jS_", glsl::ExtInst::ExtInstUMax)
5293 .Case("_Z3maxDv4_jS_", glsl::ExtInst::ExtInstUMax)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005294 .Case("_Z3maxll", glsl::ExtInst::ExtInstSMax)
5295 .Case("_Z3maxDv2_lS_", glsl::ExtInst::ExtInstSMax)
5296 .Case("_Z3maxDv3_lS_", glsl::ExtInst::ExtInstSMax)
5297 .Case("_Z3maxDv4_lS_", glsl::ExtInst::ExtInstSMax)
5298 .Case("_Z3maxmm", glsl::ExtInst::ExtInstUMax)
5299 .Case("_Z3maxDv2_mS_", glsl::ExtInst::ExtInstUMax)
5300 .Case("_Z3maxDv3_mS_", glsl::ExtInst::ExtInstUMax)
5301 .Case("_Z3maxDv4_mS_", glsl::ExtInst::ExtInstUMax)
David Neto22f144c2017-06-12 14:26:21 -04005302 .Case("_Z3maxff", glsl::ExtInst::ExtInstFMax)
5303 .Case("_Z3maxDv2_fS_", glsl::ExtInst::ExtInstFMax)
5304 .Case("_Z3maxDv3_fS_", glsl::ExtInst::ExtInstFMax)
5305 .Case("_Z3maxDv4_fS_", glsl::ExtInst::ExtInstFMax)
5306 .StartsWith("_Z4fmax", glsl::ExtInst::ExtInstFMax)
alan-bakerb39c8262019-03-08 14:03:37 -05005307 .Case("_Z3mincc", glsl::ExtInst::ExtInstSMin)
5308 .Case("_Z3minDv2_cS_", glsl::ExtInst::ExtInstSMin)
5309 .Case("_Z3minDv3_cS_", glsl::ExtInst::ExtInstSMin)
5310 .Case("_Z3minDv4_cS_", glsl::ExtInst::ExtInstSMin)
5311 .Case("_Z3minhh", glsl::ExtInst::ExtInstUMin)
5312 .Case("_Z3minDv2_hS_", glsl::ExtInst::ExtInstUMin)
5313 .Case("_Z3minDv3_hS_", glsl::ExtInst::ExtInstUMin)
5314 .Case("_Z3minDv4_hS_", glsl::ExtInst::ExtInstUMin)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005315 .Case("_Z3minss", glsl::ExtInst::ExtInstSMin)
5316 .Case("_Z3minDv2_sS_", glsl::ExtInst::ExtInstSMin)
5317 .Case("_Z3minDv3_sS_", glsl::ExtInst::ExtInstSMin)
5318 .Case("_Z3minDv4_sS_", glsl::ExtInst::ExtInstSMin)
5319 .Case("_Z3mintt", glsl::ExtInst::ExtInstUMin)
5320 .Case("_Z3minDv2_tS_", glsl::ExtInst::ExtInstUMin)
5321 .Case("_Z3minDv3_tS_", glsl::ExtInst::ExtInstUMin)
5322 .Case("_Z3minDv4_tS_", glsl::ExtInst::ExtInstUMin)
David Neto22f144c2017-06-12 14:26:21 -04005323 .Case("_Z3minii", glsl::ExtInst::ExtInstSMin)
5324 .Case("_Z3minDv2_iS_", glsl::ExtInst::ExtInstSMin)
5325 .Case("_Z3minDv3_iS_", glsl::ExtInst::ExtInstSMin)
5326 .Case("_Z3minDv4_iS_", glsl::ExtInst::ExtInstSMin)
5327 .Case("_Z3minjj", glsl::ExtInst::ExtInstUMin)
5328 .Case("_Z3minDv2_jS_", glsl::ExtInst::ExtInstUMin)
5329 .Case("_Z3minDv3_jS_", glsl::ExtInst::ExtInstUMin)
5330 .Case("_Z3minDv4_jS_", glsl::ExtInst::ExtInstUMin)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005331 .Case("_Z3minll", glsl::ExtInst::ExtInstSMin)
5332 .Case("_Z3minDv2_lS_", glsl::ExtInst::ExtInstSMin)
5333 .Case("_Z3minDv3_lS_", glsl::ExtInst::ExtInstSMin)
5334 .Case("_Z3minDv4_lS_", glsl::ExtInst::ExtInstSMin)
5335 .Case("_Z3minmm", glsl::ExtInst::ExtInstUMin)
5336 .Case("_Z3minDv2_mS_", glsl::ExtInst::ExtInstUMin)
5337 .Case("_Z3minDv3_mS_", glsl::ExtInst::ExtInstUMin)
5338 .Case("_Z3minDv4_mS_", glsl::ExtInst::ExtInstUMin)
David Neto22f144c2017-06-12 14:26:21 -04005339 .Case("_Z3minff", glsl::ExtInst::ExtInstFMin)
5340 .Case("_Z3minDv2_fS_", glsl::ExtInst::ExtInstFMin)
5341 .Case("_Z3minDv3_fS_", glsl::ExtInst::ExtInstFMin)
5342 .Case("_Z3minDv4_fS_", glsl::ExtInst::ExtInstFMin)
5343 .StartsWith("_Z4fmin", glsl::ExtInst::ExtInstFMin)
5344 .StartsWith("_Z7degrees", glsl::ExtInst::ExtInstDegrees)
5345 .StartsWith("_Z7radians", glsl::ExtInst::ExtInstRadians)
5346 .StartsWith("_Z3mix", glsl::ExtInst::ExtInstFMix)
5347 .StartsWith("_Z4acos", glsl::ExtInst::ExtInstAcos)
5348 .StartsWith("_Z5acosh", glsl::ExtInst::ExtInstAcosh)
5349 .StartsWith("_Z4asin", glsl::ExtInst::ExtInstAsin)
5350 .StartsWith("_Z5asinh", glsl::ExtInst::ExtInstAsinh)
5351 .StartsWith("_Z4atan", glsl::ExtInst::ExtInstAtan)
5352 .StartsWith("_Z5atan2", glsl::ExtInst::ExtInstAtan2)
5353 .StartsWith("_Z5atanh", glsl::ExtInst::ExtInstAtanh)
5354 .StartsWith("_Z4ceil", glsl::ExtInst::ExtInstCeil)
5355 .StartsWith("_Z3sin", glsl::ExtInst::ExtInstSin)
5356 .StartsWith("_Z4sinh", glsl::ExtInst::ExtInstSinh)
5357 .StartsWith("_Z8half_sin", glsl::ExtInst::ExtInstSin)
5358 .StartsWith("_Z10native_sin", glsl::ExtInst::ExtInstSin)
5359 .StartsWith("_Z3cos", glsl::ExtInst::ExtInstCos)
5360 .StartsWith("_Z4cosh", glsl::ExtInst::ExtInstCosh)
5361 .StartsWith("_Z8half_cos", glsl::ExtInst::ExtInstCos)
5362 .StartsWith("_Z10native_cos", glsl::ExtInst::ExtInstCos)
5363 .StartsWith("_Z3tan", glsl::ExtInst::ExtInstTan)
5364 .StartsWith("_Z4tanh", glsl::ExtInst::ExtInstTanh)
5365 .StartsWith("_Z8half_tan", glsl::ExtInst::ExtInstTan)
5366 .StartsWith("_Z10native_tan", glsl::ExtInst::ExtInstTan)
5367 .StartsWith("_Z3exp", glsl::ExtInst::ExtInstExp)
5368 .StartsWith("_Z8half_exp", glsl::ExtInst::ExtInstExp)
5369 .StartsWith("_Z10native_exp", glsl::ExtInst::ExtInstExp)
5370 .StartsWith("_Z4exp2", glsl::ExtInst::ExtInstExp2)
5371 .StartsWith("_Z9half_exp2", glsl::ExtInst::ExtInstExp2)
5372 .StartsWith("_Z11native_exp2", glsl::ExtInst::ExtInstExp2)
5373 .StartsWith("_Z3log", glsl::ExtInst::ExtInstLog)
5374 .StartsWith("_Z8half_log", glsl::ExtInst::ExtInstLog)
5375 .StartsWith("_Z10native_log", glsl::ExtInst::ExtInstLog)
5376 .StartsWith("_Z4log2", glsl::ExtInst::ExtInstLog2)
5377 .StartsWith("_Z9half_log2", glsl::ExtInst::ExtInstLog2)
5378 .StartsWith("_Z11native_log2", glsl::ExtInst::ExtInstLog2)
5379 .StartsWith("_Z4fabs", glsl::ExtInst::ExtInstFAbs)
kpet3458e942018-10-03 14:35:21 +01005380 .StartsWith("_Z3fma", glsl::ExtInst::ExtInstFma)
David Neto22f144c2017-06-12 14:26:21 -04005381 .StartsWith("_Z5floor", glsl::ExtInst::ExtInstFloor)
5382 .StartsWith("_Z5ldexp", glsl::ExtInst::ExtInstLdexp)
5383 .StartsWith("_Z3pow", glsl::ExtInst::ExtInstPow)
5384 .StartsWith("_Z4powr", glsl::ExtInst::ExtInstPow)
5385 .StartsWith("_Z9half_powr", glsl::ExtInst::ExtInstPow)
5386 .StartsWith("_Z11native_powr", glsl::ExtInst::ExtInstPow)
5387 .StartsWith("_Z5round", glsl::ExtInst::ExtInstRound)
5388 .StartsWith("_Z4sqrt", glsl::ExtInst::ExtInstSqrt)
5389 .StartsWith("_Z9half_sqrt", glsl::ExtInst::ExtInstSqrt)
5390 .StartsWith("_Z11native_sqrt", glsl::ExtInst::ExtInstSqrt)
5391 .StartsWith("_Z5rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5392 .StartsWith("_Z10half_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5393 .StartsWith("_Z12native_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5394 .StartsWith("_Z5trunc", glsl::ExtInst::ExtInstTrunc)
5395 .StartsWith("_Z5frexp", glsl::ExtInst::ExtInstFrexp)
5396 .StartsWith("_Z4sign", glsl::ExtInst::ExtInstFSign)
5397 .StartsWith("_Z6length", glsl::ExtInst::ExtInstLength)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005398 .StartsWith("_Z11fast_length", glsl::ExtInst::ExtInstLength)
David Neto22f144c2017-06-12 14:26:21 -04005399 .StartsWith("_Z8distance", glsl::ExtInst::ExtInstDistance)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005400 .StartsWith("_Z13fast_distance", glsl::ExtInst::ExtInstDistance)
David Netoe9a03512017-10-16 10:08:27 -04005401 .StartsWith("_Z4step", glsl::ExtInst::ExtInstStep)
kpet6fd2a262018-10-03 14:48:01 +01005402 .StartsWith("_Z10smoothstep", glsl::ExtInst::ExtInstSmoothStep)
David Neto22f144c2017-06-12 14:26:21 -04005403 .Case("_Z5crossDv3_fS_", glsl::ExtInst::ExtInstCross)
5404 .StartsWith("_Z9normalize", glsl::ExtInst::ExtInstNormalize)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005405 .StartsWith("_Z14fast_normalize", glsl::ExtInst::ExtInstNormalize)
David Neto22f144c2017-06-12 14:26:21 -04005406 .StartsWith("llvm.fmuladd.", glsl::ExtInst::ExtInstFma)
5407 .Case("spirv.unpack.v2f16", glsl::ExtInst::ExtInstUnpackHalf2x16)
5408 .Case("spirv.pack.v2f16", glsl::ExtInst::ExtInstPackHalf2x16)
David Neto62653202017-10-16 19:05:18 -04005409 .Case("clspv.fract.f", glsl::ExtInst::ExtInstFract)
5410 .Case("clspv.fract.v2f", glsl::ExtInst::ExtInstFract)
5411 .Case("clspv.fract.v3f", glsl::ExtInst::ExtInstFract)
5412 .Case("clspv.fract.v4f", glsl::ExtInst::ExtInstFract)
David Neto3fbb4072017-10-16 11:28:14 -04005413 .Default(kGlslExtInstBad);
5414}
5415
5416glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(StringRef Name) {
5417 // Check indirect cases.
5418 return StringSwitch<glsl::ExtInst>(Name)
5419 .StartsWith("_Z3clz", glsl::ExtInst::ExtInstFindUMsb)
5420 // Use exact match on float arg because these need a multiply
5421 // of a constant of the right floating point type.
5422 .Case("_Z6acospif", glsl::ExtInst::ExtInstAcos)
5423 .Case("_Z6acospiDv2_f", glsl::ExtInst::ExtInstAcos)
5424 .Case("_Z6acospiDv3_f", glsl::ExtInst::ExtInstAcos)
5425 .Case("_Z6acospiDv4_f", glsl::ExtInst::ExtInstAcos)
5426 .Case("_Z6asinpif", glsl::ExtInst::ExtInstAsin)
5427 .Case("_Z6asinpiDv2_f", glsl::ExtInst::ExtInstAsin)
5428 .Case("_Z6asinpiDv3_f", glsl::ExtInst::ExtInstAsin)
5429 .Case("_Z6asinpiDv4_f", glsl::ExtInst::ExtInstAsin)
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005430 .Case("_Z6atanpif", glsl::ExtInst::ExtInstAtan)
5431 .Case("_Z6atanpiDv2_f", glsl::ExtInst::ExtInstAtan)
5432 .Case("_Z6atanpiDv3_f", glsl::ExtInst::ExtInstAtan)
5433 .Case("_Z6atanpiDv4_f", glsl::ExtInst::ExtInstAtan)
David Neto3fbb4072017-10-16 11:28:14 -04005434 .Case("_Z7atan2piff", glsl::ExtInst::ExtInstAtan2)
5435 .Case("_Z7atan2piDv2_fS_", glsl::ExtInst::ExtInstAtan2)
5436 .Case("_Z7atan2piDv3_fS_", glsl::ExtInst::ExtInstAtan2)
5437 .Case("_Z7atan2piDv4_fS_", glsl::ExtInst::ExtInstAtan2)
5438 .Default(kGlslExtInstBad);
5439}
5440
alan-bakerb6b09dc2018-11-08 16:59:28 -05005441glsl::ExtInst
5442SPIRVProducerPass::getDirectOrIndirectExtInstEnum(StringRef Name) {
David Neto3fbb4072017-10-16 11:28:14 -04005443 auto direct = getExtInstEnum(Name);
5444 if (direct != kGlslExtInstBad)
5445 return direct;
5446 return getIndirectExtInstEnum(Name);
David Neto22f144c2017-06-12 14:26:21 -04005447}
5448
5449void SPIRVProducerPass::PrintResID(SPIRVInstruction *Inst) {
5450 out << "%" << Inst->getResultID();
5451}
5452
5453void SPIRVProducerPass::PrintOpcode(SPIRVInstruction *Inst) {
5454 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5455 out << "\t" << spv::getOpName(Opcode);
5456}
5457
5458void SPIRVProducerPass::PrintOperand(SPIRVOperand *Op) {
5459 SPIRVOperandType OpTy = Op->getType();
5460 switch (OpTy) {
5461 default: {
5462 llvm_unreachable("Unsupported SPIRV Operand Type???");
5463 break;
5464 }
5465 case SPIRVOperandType::NUMBERID: {
5466 out << "%" << Op->getNumID();
5467 break;
5468 }
5469 case SPIRVOperandType::LITERAL_STRING: {
5470 out << "\"" << Op->getLiteralStr() << "\"";
5471 break;
5472 }
5473 case SPIRVOperandType::LITERAL_INTEGER: {
5474 // TODO: Handle LiteralNum carefully.
Kévin Petite7d0cce2018-10-31 12:38:56 +00005475 auto Words = Op->getLiteralNum();
5476 auto NumWords = Words.size();
5477
5478 if (NumWords == 1) {
5479 out << Words[0];
5480 } else if (NumWords == 2) {
5481 uint64_t Val = (static_cast<uint64_t>(Words[1]) << 32) | Words[0];
5482 out << Val;
5483 } else {
5484 llvm_unreachable("Handle printing arbitrary precision integer literals.");
David Neto22f144c2017-06-12 14:26:21 -04005485 }
5486 break;
5487 }
5488 case SPIRVOperandType::LITERAL_FLOAT: {
5489 // TODO: Handle LiteralNum carefully.
5490 for (auto Word : Op->getLiteralNum()) {
5491 APFloat APF = APFloat(APFloat::IEEEsingle(), APInt(32, Word));
5492 SmallString<8> Str;
5493 APF.toString(Str, 6, 2);
5494 out << Str;
5495 }
5496 break;
5497 }
5498 }
5499}
5500
5501void SPIRVProducerPass::PrintCapability(SPIRVOperand *Op) {
5502 spv::Capability Cap = static_cast<spv::Capability>(Op->getNumID());
5503 out << spv::getCapabilityName(Cap);
5504}
5505
5506void SPIRVProducerPass::PrintExtInst(SPIRVOperand *Op) {
5507 auto LiteralNum = Op->getLiteralNum();
5508 glsl::ExtInst Ext = static_cast<glsl::ExtInst>(LiteralNum[0]);
5509 out << glsl::getExtInstName(Ext);
5510}
5511
5512void SPIRVProducerPass::PrintAddrModel(SPIRVOperand *Op) {
5513 spv::AddressingModel AddrModel =
5514 static_cast<spv::AddressingModel>(Op->getNumID());
5515 out << spv::getAddressingModelName(AddrModel);
5516}
5517
5518void SPIRVProducerPass::PrintMemModel(SPIRVOperand *Op) {
5519 spv::MemoryModel MemModel = static_cast<spv::MemoryModel>(Op->getNumID());
5520 out << spv::getMemoryModelName(MemModel);
5521}
5522
5523void SPIRVProducerPass::PrintExecModel(SPIRVOperand *Op) {
5524 spv::ExecutionModel ExecModel =
5525 static_cast<spv::ExecutionModel>(Op->getNumID());
5526 out << spv::getExecutionModelName(ExecModel);
5527}
5528
5529void SPIRVProducerPass::PrintExecMode(SPIRVOperand *Op) {
5530 spv::ExecutionMode ExecMode = static_cast<spv::ExecutionMode>(Op->getNumID());
5531 out << spv::getExecutionModeName(ExecMode);
5532}
5533
5534void SPIRVProducerPass::PrintSourceLanguage(SPIRVOperand *Op) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005535 spv::SourceLanguage SourceLang =
5536 static_cast<spv::SourceLanguage>(Op->getNumID());
David Neto22f144c2017-06-12 14:26:21 -04005537 out << spv::getSourceLanguageName(SourceLang);
5538}
5539
5540void SPIRVProducerPass::PrintFuncCtrl(SPIRVOperand *Op) {
5541 spv::FunctionControlMask FuncCtrl =
5542 static_cast<spv::FunctionControlMask>(Op->getNumID());
5543 out << spv::getFunctionControlName(FuncCtrl);
5544}
5545
5546void SPIRVProducerPass::PrintStorageClass(SPIRVOperand *Op) {
5547 spv::StorageClass StClass = static_cast<spv::StorageClass>(Op->getNumID());
5548 out << getStorageClassName(StClass);
5549}
5550
5551void SPIRVProducerPass::PrintDecoration(SPIRVOperand *Op) {
5552 spv::Decoration Deco = static_cast<spv::Decoration>(Op->getNumID());
5553 out << getDecorationName(Deco);
5554}
5555
5556void SPIRVProducerPass::PrintBuiltIn(SPIRVOperand *Op) {
5557 spv::BuiltIn BIn = static_cast<spv::BuiltIn>(Op->getNumID());
5558 out << getBuiltInName(BIn);
5559}
5560
5561void SPIRVProducerPass::PrintSelectionControl(SPIRVOperand *Op) {
5562 spv::SelectionControlMask BIn =
5563 static_cast<spv::SelectionControlMask>(Op->getNumID());
5564 out << getSelectionControlName(BIn);
5565}
5566
5567void SPIRVProducerPass::PrintLoopControl(SPIRVOperand *Op) {
5568 spv::LoopControlMask BIn = static_cast<spv::LoopControlMask>(Op->getNumID());
5569 out << getLoopControlName(BIn);
5570}
5571
5572void SPIRVProducerPass::PrintDimensionality(SPIRVOperand *Op) {
5573 spv::Dim DIM = static_cast<spv::Dim>(Op->getNumID());
5574 out << getDimName(DIM);
5575}
5576
5577void SPIRVProducerPass::PrintImageFormat(SPIRVOperand *Op) {
5578 spv::ImageFormat Format = static_cast<spv::ImageFormat>(Op->getNumID());
5579 out << getImageFormatName(Format);
5580}
5581
5582void SPIRVProducerPass::PrintMemoryAccess(SPIRVOperand *Op) {
5583 out << spv::getMemoryAccessName(
5584 static_cast<spv::MemoryAccessMask>(Op->getNumID()));
5585}
5586
5587void SPIRVProducerPass::PrintImageOperandsType(SPIRVOperand *Op) {
5588 auto LiteralNum = Op->getLiteralNum();
5589 spv::ImageOperandsMask Type =
5590 static_cast<spv::ImageOperandsMask>(LiteralNum[0]);
5591 out << getImageOperandsName(Type);
5592}
5593
5594void SPIRVProducerPass::WriteSPIRVAssembly() {
5595 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5596
5597 for (auto Inst : SPIRVInstList) {
5598 SPIRVOperandList Ops = Inst->getOperands();
5599 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5600
5601 switch (Opcode) {
5602 default: {
5603 llvm_unreachable("Unsupported SPIRV instruction");
5604 break;
5605 }
5606 case spv::OpCapability: {
5607 // Ops[0] = Capability
5608 PrintOpcode(Inst);
5609 out << " ";
5610 PrintCapability(Ops[0]);
5611 out << "\n";
5612 break;
5613 }
5614 case spv::OpMemoryModel: {
5615 // Ops[0] = Addressing Model
5616 // Ops[1] = Memory Model
5617 PrintOpcode(Inst);
5618 out << " ";
5619 PrintAddrModel(Ops[0]);
5620 out << " ";
5621 PrintMemModel(Ops[1]);
5622 out << "\n";
5623 break;
5624 }
5625 case spv::OpEntryPoint: {
5626 // Ops[0] = Execution Model
5627 // Ops[1] = EntryPoint ID
5628 // Ops[2] = Name (Literal String)
5629 // Ops[3] ... Ops[n] = Interface ID
5630 PrintOpcode(Inst);
5631 out << " ";
5632 PrintExecModel(Ops[0]);
5633 for (uint32_t i = 1; i < Ops.size(); i++) {
5634 out << " ";
5635 PrintOperand(Ops[i]);
5636 }
5637 out << "\n";
5638 break;
5639 }
5640 case spv::OpExecutionMode: {
5641 // Ops[0] = Entry Point ID
5642 // Ops[1] = Execution Mode
5643 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
5644 PrintOpcode(Inst);
5645 out << " ";
5646 PrintOperand(Ops[0]);
5647 out << " ";
5648 PrintExecMode(Ops[1]);
5649 for (uint32_t i = 2; i < Ops.size(); i++) {
5650 out << " ";
5651 PrintOperand(Ops[i]);
5652 }
5653 out << "\n";
5654 break;
5655 }
5656 case spv::OpSource: {
5657 // Ops[0] = SourceLanguage ID
5658 // Ops[1] = Version (LiteralNum)
5659 PrintOpcode(Inst);
5660 out << " ";
5661 PrintSourceLanguage(Ops[0]);
5662 out << " ";
5663 PrintOperand(Ops[1]);
5664 out << "\n";
5665 break;
5666 }
5667 case spv::OpDecorate: {
5668 // Ops[0] = Target ID
5669 // Ops[1] = Decoration (Block or BufferBlock)
5670 // Ops[2] ... Ops[n] = Optional literals according to Decoration
5671 PrintOpcode(Inst);
5672 out << " ";
5673 PrintOperand(Ops[0]);
5674 out << " ";
5675 PrintDecoration(Ops[1]);
5676 // Handle BuiltIn OpDecorate specially.
5677 if (Ops[1]->getNumID() == spv::DecorationBuiltIn) {
5678 out << " ";
5679 PrintBuiltIn(Ops[2]);
5680 } else {
5681 for (uint32_t i = 2; i < Ops.size(); i++) {
5682 out << " ";
5683 PrintOperand(Ops[i]);
5684 }
5685 }
5686 out << "\n";
5687 break;
5688 }
5689 case spv::OpMemberDecorate: {
5690 // Ops[0] = Structure Type ID
5691 // Ops[1] = Member Index(Literal Number)
5692 // Ops[2] = Decoration
5693 // Ops[3] ... Ops[n] = Optional literals according to Decoration
5694 PrintOpcode(Inst);
5695 out << " ";
5696 PrintOperand(Ops[0]);
5697 out << " ";
5698 PrintOperand(Ops[1]);
5699 out << " ";
5700 PrintDecoration(Ops[2]);
5701 for (uint32_t i = 3; i < Ops.size(); i++) {
5702 out << " ";
5703 PrintOperand(Ops[i]);
5704 }
5705 out << "\n";
5706 break;
5707 }
5708 case spv::OpTypePointer: {
5709 // Ops[0] = Storage Class
5710 // Ops[1] = Element Type ID
5711 PrintResID(Inst);
5712 out << " = ";
5713 PrintOpcode(Inst);
5714 out << " ";
5715 PrintStorageClass(Ops[0]);
5716 out << " ";
5717 PrintOperand(Ops[1]);
5718 out << "\n";
5719 break;
5720 }
5721 case spv::OpTypeImage: {
5722 // Ops[0] = Sampled Type ID
5723 // Ops[1] = Dim ID
5724 // Ops[2] = Depth (Literal Number)
5725 // Ops[3] = Arrayed (Literal Number)
5726 // Ops[4] = MS (Literal Number)
5727 // Ops[5] = Sampled (Literal Number)
5728 // Ops[6] = Image Format ID
5729 PrintResID(Inst);
5730 out << " = ";
5731 PrintOpcode(Inst);
5732 out << " ";
5733 PrintOperand(Ops[0]);
5734 out << " ";
5735 PrintDimensionality(Ops[1]);
5736 out << " ";
5737 PrintOperand(Ops[2]);
5738 out << " ";
5739 PrintOperand(Ops[3]);
5740 out << " ";
5741 PrintOperand(Ops[4]);
5742 out << " ";
5743 PrintOperand(Ops[5]);
5744 out << " ";
5745 PrintImageFormat(Ops[6]);
5746 out << "\n";
5747 break;
5748 }
5749 case spv::OpFunction: {
5750 // Ops[0] : Result Type ID
5751 // Ops[1] : Function Control
5752 // Ops[2] : Function Type ID
5753 PrintResID(Inst);
5754 out << " = ";
5755 PrintOpcode(Inst);
5756 out << " ";
5757 PrintOperand(Ops[0]);
5758 out << " ";
5759 PrintFuncCtrl(Ops[1]);
5760 out << " ";
5761 PrintOperand(Ops[2]);
5762 out << "\n";
5763 break;
5764 }
5765 case spv::OpSelectionMerge: {
5766 // Ops[0] = Merge Block ID
5767 // Ops[1] = Selection Control
5768 PrintOpcode(Inst);
5769 out << " ";
5770 PrintOperand(Ops[0]);
5771 out << " ";
5772 PrintSelectionControl(Ops[1]);
5773 out << "\n";
5774 break;
5775 }
5776 case spv::OpLoopMerge: {
5777 // Ops[0] = Merge Block ID
5778 // Ops[1] = Continue Target ID
5779 // Ops[2] = Selection Control
5780 PrintOpcode(Inst);
5781 out << " ";
5782 PrintOperand(Ops[0]);
5783 out << " ";
5784 PrintOperand(Ops[1]);
5785 out << " ";
5786 PrintLoopControl(Ops[2]);
5787 out << "\n";
5788 break;
5789 }
5790 case spv::OpImageSampleExplicitLod: {
5791 // Ops[0] = Result Type ID
5792 // Ops[1] = Sampled Image ID
5793 // Ops[2] = Coordinate ID
5794 // Ops[3] = Image Operands Type ID
5795 // Ops[4] ... Ops[n] = Operands ID
5796 PrintResID(Inst);
5797 out << " = ";
5798 PrintOpcode(Inst);
5799 for (uint32_t i = 0; i < 3; i++) {
5800 out << " ";
5801 PrintOperand(Ops[i]);
5802 }
5803 out << " ";
5804 PrintImageOperandsType(Ops[3]);
5805 for (uint32_t i = 4; i < Ops.size(); i++) {
5806 out << " ";
5807 PrintOperand(Ops[i]);
5808 }
5809 out << "\n";
5810 break;
5811 }
5812 case spv::OpVariable: {
5813 // Ops[0] : Result Type ID
5814 // Ops[1] : Storage Class
5815 // Ops[2] ... Ops[n] = Initializer IDs
5816 PrintResID(Inst);
5817 out << " = ";
5818 PrintOpcode(Inst);
5819 out << " ";
5820 PrintOperand(Ops[0]);
5821 out << " ";
5822 PrintStorageClass(Ops[1]);
5823 for (uint32_t i = 2; i < Ops.size(); i++) {
5824 out << " ";
5825 PrintOperand(Ops[i]);
5826 }
5827 out << "\n";
5828 break;
5829 }
5830 case spv::OpExtInst: {
5831 // Ops[0] = Result Type ID
5832 // Ops[1] = Set ID (OpExtInstImport ID)
5833 // Ops[2] = Instruction Number (Literal Number)
5834 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5835 PrintResID(Inst);
5836 out << " = ";
5837 PrintOpcode(Inst);
5838 out << " ";
5839 PrintOperand(Ops[0]);
5840 out << " ";
5841 PrintOperand(Ops[1]);
5842 out << " ";
5843 PrintExtInst(Ops[2]);
5844 for (uint32_t i = 3; i < Ops.size(); i++) {
5845 out << " ";
5846 PrintOperand(Ops[i]);
5847 }
5848 out << "\n";
5849 break;
5850 }
5851 case spv::OpCopyMemory: {
5852 // Ops[0] = Addressing Model
5853 // Ops[1] = Memory Model
5854 PrintOpcode(Inst);
5855 out << " ";
5856 PrintOperand(Ops[0]);
5857 out << " ";
5858 PrintOperand(Ops[1]);
5859 out << " ";
5860 PrintMemoryAccess(Ops[2]);
5861 out << " ";
5862 PrintOperand(Ops[3]);
5863 out << "\n";
5864 break;
5865 }
5866 case spv::OpExtension:
5867 case spv::OpControlBarrier:
5868 case spv::OpMemoryBarrier:
5869 case spv::OpBranch:
5870 case spv::OpBranchConditional:
5871 case spv::OpStore:
5872 case spv::OpImageWrite:
5873 case spv::OpReturnValue:
5874 case spv::OpReturn:
5875 case spv::OpFunctionEnd: {
5876 PrintOpcode(Inst);
5877 for (uint32_t i = 0; i < Ops.size(); i++) {
5878 out << " ";
5879 PrintOperand(Ops[i]);
5880 }
5881 out << "\n";
5882 break;
5883 }
5884 case spv::OpExtInstImport:
5885 case spv::OpTypeRuntimeArray:
5886 case spv::OpTypeStruct:
5887 case spv::OpTypeSampler:
5888 case spv::OpTypeSampledImage:
5889 case spv::OpTypeInt:
5890 case spv::OpTypeFloat:
5891 case spv::OpTypeArray:
5892 case spv::OpTypeVector:
5893 case spv::OpTypeBool:
5894 case spv::OpTypeVoid:
5895 case spv::OpTypeFunction:
5896 case spv::OpFunctionParameter:
5897 case spv::OpLabel:
5898 case spv::OpPhi:
5899 case spv::OpLoad:
5900 case spv::OpSelect:
5901 case spv::OpAccessChain:
5902 case spv::OpPtrAccessChain:
5903 case spv::OpInBoundsAccessChain:
5904 case spv::OpUConvert:
5905 case spv::OpSConvert:
5906 case spv::OpConvertFToU:
5907 case spv::OpConvertFToS:
5908 case spv::OpConvertUToF:
5909 case spv::OpConvertSToF:
5910 case spv::OpFConvert:
5911 case spv::OpConvertPtrToU:
5912 case spv::OpConvertUToPtr:
5913 case spv::OpBitcast:
5914 case spv::OpIAdd:
5915 case spv::OpFAdd:
5916 case spv::OpISub:
5917 case spv::OpFSub:
5918 case spv::OpIMul:
5919 case spv::OpFMul:
5920 case spv::OpUDiv:
5921 case spv::OpSDiv:
5922 case spv::OpFDiv:
5923 case spv::OpUMod:
5924 case spv::OpSRem:
5925 case spv::OpFRem:
Kévin Petit8a560882019-03-21 15:24:34 +00005926 case spv::OpUMulExtended:
5927 case spv::OpSMulExtended:
David Neto22f144c2017-06-12 14:26:21 -04005928 case spv::OpBitwiseOr:
5929 case spv::OpBitwiseXor:
5930 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005931 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005932 case spv::OpShiftLeftLogical:
5933 case spv::OpShiftRightLogical:
5934 case spv::OpShiftRightArithmetic:
5935 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04005936 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04005937 case spv::OpCompositeExtract:
5938 case spv::OpVectorExtractDynamic:
5939 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04005940 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04005941 case spv::OpVectorInsertDynamic:
5942 case spv::OpVectorShuffle:
5943 case spv::OpIEqual:
5944 case spv::OpINotEqual:
5945 case spv::OpUGreaterThan:
5946 case spv::OpUGreaterThanEqual:
5947 case spv::OpULessThan:
5948 case spv::OpULessThanEqual:
5949 case spv::OpSGreaterThan:
5950 case spv::OpSGreaterThanEqual:
5951 case spv::OpSLessThan:
5952 case spv::OpSLessThanEqual:
5953 case spv::OpFOrdEqual:
5954 case spv::OpFOrdGreaterThan:
5955 case spv::OpFOrdGreaterThanEqual:
5956 case spv::OpFOrdLessThan:
5957 case spv::OpFOrdLessThanEqual:
5958 case spv::OpFOrdNotEqual:
5959 case spv::OpFUnordEqual:
5960 case spv::OpFUnordGreaterThan:
5961 case spv::OpFUnordGreaterThanEqual:
5962 case spv::OpFUnordLessThan:
5963 case spv::OpFUnordLessThanEqual:
5964 case spv::OpFUnordNotEqual:
5965 case spv::OpSampledImage:
5966 case spv::OpFunctionCall:
5967 case spv::OpConstantTrue:
5968 case spv::OpConstantFalse:
5969 case spv::OpConstant:
5970 case spv::OpSpecConstant:
5971 case spv::OpConstantComposite:
5972 case spv::OpSpecConstantComposite:
5973 case spv::OpConstantNull:
5974 case spv::OpLogicalOr:
5975 case spv::OpLogicalAnd:
5976 case spv::OpLogicalNot:
5977 case spv::OpLogicalNotEqual:
5978 case spv::OpUndef:
5979 case spv::OpIsInf:
5980 case spv::OpIsNan:
5981 case spv::OpAny:
5982 case spv::OpAll:
David Neto5c22a252018-03-15 16:07:41 -04005983 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04005984 case spv::OpAtomicIAdd:
5985 case spv::OpAtomicISub:
5986 case spv::OpAtomicExchange:
5987 case spv::OpAtomicIIncrement:
5988 case spv::OpAtomicIDecrement:
5989 case spv::OpAtomicCompareExchange:
5990 case spv::OpAtomicUMin:
5991 case spv::OpAtomicSMin:
5992 case spv::OpAtomicUMax:
5993 case spv::OpAtomicSMax:
5994 case spv::OpAtomicAnd:
5995 case spv::OpAtomicOr:
5996 case spv::OpAtomicXor:
5997 case spv::OpDot: {
5998 PrintResID(Inst);
5999 out << " = ";
6000 PrintOpcode(Inst);
6001 for (uint32_t i = 0; i < Ops.size(); i++) {
6002 out << " ";
6003 PrintOperand(Ops[i]);
6004 }
6005 out << "\n";
6006 break;
6007 }
6008 }
6009 }
6010}
6011
6012void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04006013 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04006014}
6015
6016void SPIRVProducerPass::WriteResultID(SPIRVInstruction *Inst) {
6017 WriteOneWord(Inst->getResultID());
6018}
6019
6020void SPIRVProducerPass::WriteWordCountAndOpcode(SPIRVInstruction *Inst) {
6021 // High 16 bit : Word Count
6022 // Low 16 bit : Opcode
6023 uint32_t Word = Inst->getOpcode();
David Netoee2660d2018-06-28 16:31:29 -04006024 const uint32_t count = Inst->getWordCount();
6025 if (count > 65535) {
6026 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
6027 llvm_unreachable("Word count too high");
6028 }
David Neto22f144c2017-06-12 14:26:21 -04006029 Word |= Inst->getWordCount() << 16;
6030 WriteOneWord(Word);
6031}
6032
6033void SPIRVProducerPass::WriteOperand(SPIRVOperand *Op) {
6034 SPIRVOperandType OpTy = Op->getType();
6035 switch (OpTy) {
6036 default: {
6037 llvm_unreachable("Unsupported SPIRV Operand Type???");
6038 break;
6039 }
6040 case SPIRVOperandType::NUMBERID: {
6041 WriteOneWord(Op->getNumID());
6042 break;
6043 }
6044 case SPIRVOperandType::LITERAL_STRING: {
6045 std::string Str = Op->getLiteralStr();
6046 const char *Data = Str.c_str();
6047 size_t WordSize = Str.size() / 4;
6048 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
6049 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
6050 }
6051
6052 uint32_t Remainder = Str.size() % 4;
6053 uint32_t LastWord = 0;
6054 if (Remainder) {
6055 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
6056 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
6057 }
6058 }
6059
6060 WriteOneWord(LastWord);
6061 break;
6062 }
6063 case SPIRVOperandType::LITERAL_INTEGER:
6064 case SPIRVOperandType::LITERAL_FLOAT: {
6065 auto LiteralNum = Op->getLiteralNum();
6066 // TODO: Handle LiteranNum carefully.
6067 for (auto Word : LiteralNum) {
6068 WriteOneWord(Word);
6069 }
6070 break;
6071 }
6072 }
6073}
6074
6075void SPIRVProducerPass::WriteSPIRVBinary() {
6076 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
6077
6078 for (auto Inst : SPIRVInstList) {
David Netoc6f3ab22018-04-06 18:02:31 -04006079 SPIRVOperandList Ops{Inst->getOperands()};
David Neto22f144c2017-06-12 14:26:21 -04006080 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
6081
6082 switch (Opcode) {
6083 default: {
David Neto5c22a252018-03-15 16:07:41 -04006084 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04006085 llvm_unreachable("Unsupported SPIRV instruction");
6086 break;
6087 }
6088 case spv::OpCapability:
6089 case spv::OpExtension:
6090 case spv::OpMemoryModel:
6091 case spv::OpEntryPoint:
6092 case spv::OpExecutionMode:
6093 case spv::OpSource:
6094 case spv::OpDecorate:
6095 case spv::OpMemberDecorate:
6096 case spv::OpBranch:
6097 case spv::OpBranchConditional:
6098 case spv::OpSelectionMerge:
6099 case spv::OpLoopMerge:
6100 case spv::OpStore:
6101 case spv::OpImageWrite:
6102 case spv::OpReturnValue:
6103 case spv::OpControlBarrier:
6104 case spv::OpMemoryBarrier:
6105 case spv::OpReturn:
6106 case spv::OpFunctionEnd:
6107 case spv::OpCopyMemory: {
6108 WriteWordCountAndOpcode(Inst);
6109 for (uint32_t i = 0; i < Ops.size(); i++) {
6110 WriteOperand(Ops[i]);
6111 }
6112 break;
6113 }
6114 case spv::OpTypeBool:
6115 case spv::OpTypeVoid:
6116 case spv::OpTypeSampler:
6117 case spv::OpLabel:
6118 case spv::OpExtInstImport:
6119 case spv::OpTypePointer:
6120 case spv::OpTypeRuntimeArray:
6121 case spv::OpTypeStruct:
6122 case spv::OpTypeImage:
6123 case spv::OpTypeSampledImage:
6124 case spv::OpTypeInt:
6125 case spv::OpTypeFloat:
6126 case spv::OpTypeArray:
6127 case spv::OpTypeVector:
6128 case spv::OpTypeFunction: {
6129 WriteWordCountAndOpcode(Inst);
6130 WriteResultID(Inst);
6131 for (uint32_t i = 0; i < Ops.size(); i++) {
6132 WriteOperand(Ops[i]);
6133 }
6134 break;
6135 }
6136 case spv::OpFunction:
6137 case spv::OpFunctionParameter:
6138 case spv::OpAccessChain:
6139 case spv::OpPtrAccessChain:
6140 case spv::OpInBoundsAccessChain:
6141 case spv::OpUConvert:
6142 case spv::OpSConvert:
6143 case spv::OpConvertFToU:
6144 case spv::OpConvertFToS:
6145 case spv::OpConvertUToF:
6146 case spv::OpConvertSToF:
6147 case spv::OpFConvert:
6148 case spv::OpConvertPtrToU:
6149 case spv::OpConvertUToPtr:
6150 case spv::OpBitcast:
6151 case spv::OpIAdd:
6152 case spv::OpFAdd:
6153 case spv::OpISub:
6154 case spv::OpFSub:
6155 case spv::OpIMul:
6156 case spv::OpFMul:
6157 case spv::OpUDiv:
6158 case spv::OpSDiv:
6159 case spv::OpFDiv:
6160 case spv::OpUMod:
6161 case spv::OpSRem:
6162 case spv::OpFRem:
Kévin Petit8a560882019-03-21 15:24:34 +00006163 case spv::OpUMulExtended:
6164 case spv::OpSMulExtended:
David Neto22f144c2017-06-12 14:26:21 -04006165 case spv::OpBitwiseOr:
6166 case spv::OpBitwiseXor:
6167 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04006168 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04006169 case spv::OpShiftLeftLogical:
6170 case spv::OpShiftRightLogical:
6171 case spv::OpShiftRightArithmetic:
6172 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04006173 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04006174 case spv::OpCompositeExtract:
6175 case spv::OpVectorExtractDynamic:
6176 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04006177 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04006178 case spv::OpVectorInsertDynamic:
6179 case spv::OpVectorShuffle:
6180 case spv::OpIEqual:
6181 case spv::OpINotEqual:
6182 case spv::OpUGreaterThan:
6183 case spv::OpUGreaterThanEqual:
6184 case spv::OpULessThan:
6185 case spv::OpULessThanEqual:
6186 case spv::OpSGreaterThan:
6187 case spv::OpSGreaterThanEqual:
6188 case spv::OpSLessThan:
6189 case spv::OpSLessThanEqual:
6190 case spv::OpFOrdEqual:
6191 case spv::OpFOrdGreaterThan:
6192 case spv::OpFOrdGreaterThanEqual:
6193 case spv::OpFOrdLessThan:
6194 case spv::OpFOrdLessThanEqual:
6195 case spv::OpFOrdNotEqual:
6196 case spv::OpFUnordEqual:
6197 case spv::OpFUnordGreaterThan:
6198 case spv::OpFUnordGreaterThanEqual:
6199 case spv::OpFUnordLessThan:
6200 case spv::OpFUnordLessThanEqual:
6201 case spv::OpFUnordNotEqual:
6202 case spv::OpExtInst:
6203 case spv::OpIsInf:
6204 case spv::OpIsNan:
6205 case spv::OpAny:
6206 case spv::OpAll:
6207 case spv::OpUndef:
6208 case spv::OpConstantNull:
6209 case spv::OpLogicalOr:
6210 case spv::OpLogicalAnd:
6211 case spv::OpLogicalNot:
6212 case spv::OpLogicalNotEqual:
6213 case spv::OpConstantComposite:
6214 case spv::OpSpecConstantComposite:
6215 case spv::OpConstantTrue:
6216 case spv::OpConstantFalse:
6217 case spv::OpConstant:
6218 case spv::OpSpecConstant:
6219 case spv::OpVariable:
6220 case spv::OpFunctionCall:
6221 case spv::OpSampledImage:
6222 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04006223 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04006224 case spv::OpSelect:
6225 case spv::OpPhi:
6226 case spv::OpLoad:
6227 case spv::OpAtomicIAdd:
6228 case spv::OpAtomicISub:
6229 case spv::OpAtomicExchange:
6230 case spv::OpAtomicIIncrement:
6231 case spv::OpAtomicIDecrement:
6232 case spv::OpAtomicCompareExchange:
6233 case spv::OpAtomicUMin:
6234 case spv::OpAtomicSMin:
6235 case spv::OpAtomicUMax:
6236 case spv::OpAtomicSMax:
6237 case spv::OpAtomicAnd:
6238 case spv::OpAtomicOr:
6239 case spv::OpAtomicXor:
6240 case spv::OpDot: {
6241 WriteWordCountAndOpcode(Inst);
6242 WriteOperand(Ops[0]);
6243 WriteResultID(Inst);
6244 for (uint32_t i = 1; i < Ops.size(); i++) {
6245 WriteOperand(Ops[i]);
6246 }
6247 break;
6248 }
6249 }
6250 }
6251}
Alan Baker9bf93fb2018-08-28 16:59:26 -04006252
alan-bakerb6b09dc2018-11-08 16:59:28 -05006253bool SPIRVProducerPass::IsTypeNullable(const Type *type) const {
Alan Baker9bf93fb2018-08-28 16:59:26 -04006254 switch (type->getTypeID()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05006255 case Type::HalfTyID:
6256 case Type::FloatTyID:
6257 case Type::DoubleTyID:
6258 case Type::IntegerTyID:
6259 case Type::VectorTyID:
6260 return true;
6261 case Type::PointerTyID: {
6262 const PointerType *pointer_type = cast<PointerType>(type);
6263 if (pointer_type->getPointerAddressSpace() !=
6264 AddressSpace::UniformConstant) {
6265 auto pointee_type = pointer_type->getPointerElementType();
6266 if (pointee_type->isStructTy() &&
6267 cast<StructType>(pointee_type)->isOpaque()) {
6268 // Images and samplers are not nullable.
6269 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04006270 }
Alan Baker9bf93fb2018-08-28 16:59:26 -04006271 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05006272 return true;
6273 }
6274 case Type::ArrayTyID:
6275 return IsTypeNullable(cast<CompositeType>(type)->getTypeAtIndex(0u));
6276 case Type::StructTyID: {
6277 const StructType *struct_type = cast<StructType>(type);
6278 // Images and samplers are not nullable.
6279 if (struct_type->isOpaque())
Alan Baker9bf93fb2018-08-28 16:59:26 -04006280 return false;
alan-bakerb6b09dc2018-11-08 16:59:28 -05006281 for (const auto element : struct_type->elements()) {
6282 if (!IsTypeNullable(element))
6283 return false;
6284 }
6285 return true;
6286 }
6287 default:
6288 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04006289 }
6290}
Alan Bakerfcda9482018-10-02 17:09:59 -04006291
6292void SPIRVProducerPass::PopulateUBOTypeMaps(Module &module) {
6293 if (auto *offsets_md =
6294 module.getNamedMetadata(clspv::RemappedTypeOffsetMetadataName())) {
6295 // Metdata is stored as key-value pair operands. The first element of each
6296 // operand is the type and the second is a vector of offsets.
6297 for (const auto *operand : offsets_md->operands()) {
6298 const auto *pair = cast<MDTuple>(operand);
6299 auto *type =
6300 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
6301 const auto *offset_vector = cast<MDTuple>(pair->getOperand(1));
6302 std::vector<uint32_t> offsets;
6303 for (const Metadata *offset_md : offset_vector->operands()) {
6304 const auto *constant_md = cast<ConstantAsMetadata>(offset_md);
alan-bakerb6b09dc2018-11-08 16:59:28 -05006305 offsets.push_back(static_cast<uint32_t>(
6306 cast<ConstantInt>(constant_md->getValue())->getZExtValue()));
Alan Bakerfcda9482018-10-02 17:09:59 -04006307 }
6308 RemappedUBOTypeOffsets.insert(std::make_pair(type, offsets));
6309 }
6310 }
6311
6312 if (auto *sizes_md =
6313 module.getNamedMetadata(clspv::RemappedTypeSizesMetadataName())) {
6314 // Metadata is stored as key-value pair operands. The first element of each
6315 // operand is the type and the second is a triple of sizes: type size in
6316 // bits, store size and alloc size.
6317 for (const auto *operand : sizes_md->operands()) {
6318 const auto *pair = cast<MDTuple>(operand);
6319 auto *type =
6320 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
6321 const auto *size_triple = cast<MDTuple>(pair->getOperand(1));
6322 uint64_t type_size_in_bits =
6323 cast<ConstantInt>(
6324 cast<ConstantAsMetadata>(size_triple->getOperand(0))->getValue())
6325 ->getZExtValue();
6326 uint64_t type_store_size =
6327 cast<ConstantInt>(
6328 cast<ConstantAsMetadata>(size_triple->getOperand(1))->getValue())
6329 ->getZExtValue();
6330 uint64_t type_alloc_size =
6331 cast<ConstantInt>(
6332 cast<ConstantAsMetadata>(size_triple->getOperand(2))->getValue())
6333 ->getZExtValue();
6334 RemappedUBOTypeSizes.insert(std::make_pair(
6335 type, std::make_tuple(type_size_in_bits, type_store_size,
6336 type_alloc_size)));
6337 }
6338 }
6339}
6340
6341uint64_t SPIRVProducerPass::GetTypeSizeInBits(Type *type,
6342 const DataLayout &DL) {
6343 auto iter = RemappedUBOTypeSizes.find(type);
6344 if (iter != RemappedUBOTypeSizes.end()) {
6345 return std::get<0>(iter->second);
6346 }
6347
6348 return DL.getTypeSizeInBits(type);
6349}
6350
6351uint64_t SPIRVProducerPass::GetTypeStoreSize(Type *type, const DataLayout &DL) {
6352 auto iter = RemappedUBOTypeSizes.find(type);
6353 if (iter != RemappedUBOTypeSizes.end()) {
6354 return std::get<1>(iter->second);
6355 }
6356
6357 return DL.getTypeStoreSize(type);
6358}
6359
6360uint64_t SPIRVProducerPass::GetTypeAllocSize(Type *type, const DataLayout &DL) {
6361 auto iter = RemappedUBOTypeSizes.find(type);
6362 if (iter != RemappedUBOTypeSizes.end()) {
6363 return std::get<2>(iter->second);
6364 }
6365
6366 return DL.getTypeAllocSize(type);
6367}
alan-baker5b86ed72019-02-15 08:26:50 -05006368
6369void SPIRVProducerPass::setVariablePointersCapabilities(unsigned address_space) {
6370 if (GetStorageClass(address_space) == spv::StorageClassStorageBuffer) {
6371 setVariablePointersStorageBuffer(true);
6372 } else {
6373 setVariablePointers(true);
6374 }
6375}
6376
6377Value *SPIRVProducerPass::GetBasePointer(Value* v) {
6378 if (auto *gep = dyn_cast<GetElementPtrInst>(v)) {
6379 return GetBasePointer(gep->getPointerOperand());
6380 }
6381
6382 // Conservatively return |v|.
6383 return v;
6384}
6385
6386bool SPIRVProducerPass::sameResource(Value *lhs, Value *rhs) const {
6387 if (auto *lhs_call = dyn_cast<CallInst>(lhs)) {
6388 if (auto *rhs_call = dyn_cast<CallInst>(rhs)) {
6389 if (lhs_call->getCalledFunction()->getName().startswith(
6390 clspv::ResourceAccessorFunction()) &&
6391 rhs_call->getCalledFunction()->getName().startswith(
6392 clspv::ResourceAccessorFunction())) {
6393 // For resource accessors, match descriptor set and binding.
6394 if (lhs_call->getOperand(0) == rhs_call->getOperand(0) &&
6395 lhs_call->getOperand(1) == rhs_call->getOperand(1))
6396 return true;
6397 } else if (lhs_call->getCalledFunction()->getName().startswith(
6398 clspv::WorkgroupAccessorFunction()) &&
6399 rhs_call->getCalledFunction()->getName().startswith(
6400 clspv::WorkgroupAccessorFunction())) {
6401 // For workgroup resources, match spec id.
6402 if (lhs_call->getOperand(0) == rhs_call->getOperand(0))
6403 return true;
6404 }
6405 }
6406 }
6407
6408 return false;
6409}
6410
6411bool SPIRVProducerPass::selectFromSameObject(Instruction *inst) {
6412 assert(inst->getType()->isPointerTy());
6413 assert(GetStorageClass(inst->getType()->getPointerAddressSpace()) ==
6414 spv::StorageClassStorageBuffer);
6415 const bool hack_undef = clspv::Option::HackUndef();
6416 if (auto *select = dyn_cast<SelectInst>(inst)) {
6417 auto *true_base = GetBasePointer(select->getTrueValue());
6418 auto *false_base = GetBasePointer(select->getFalseValue());
6419
6420 if (true_base == false_base)
6421 return true;
6422
6423 // If either the true or false operand is a null, then we satisfy the same
6424 // object constraint.
6425 if (auto *true_cst = dyn_cast<Constant>(true_base)) {
6426 if (true_cst->isNullValue() || (hack_undef && isa<UndefValue>(true_base)))
6427 return true;
6428 }
6429
6430 if (auto *false_cst = dyn_cast<Constant>(false_base)) {
6431 if (false_cst->isNullValue() ||
6432 (hack_undef && isa<UndefValue>(false_base)))
6433 return true;
6434 }
6435
6436 if (sameResource(true_base, false_base))
6437 return true;
6438 } else if (auto *phi = dyn_cast<PHINode>(inst)) {
6439 Value *value = nullptr;
6440 bool ok = true;
6441 for (unsigned i = 0; ok && i != phi->getNumIncomingValues(); ++i) {
6442 auto *base = GetBasePointer(phi->getIncomingValue(i));
6443 // Null values satisfy the constraint of selecting of selecting from the
6444 // same object.
6445 if (!value) {
6446 if (auto *cst = dyn_cast<Constant>(base)) {
6447 if (!cst->isNullValue() && !(hack_undef && isa<UndefValue>(base)))
6448 value = base;
6449 } else {
6450 value = base;
6451 }
6452 } else if (base != value) {
6453 if (auto *base_cst = dyn_cast<Constant>(base)) {
6454 if (base_cst->isNullValue() || (hack_undef && isa<UndefValue>(base)))
6455 continue;
6456 }
6457
6458 if (sameResource(value, base))
6459 continue;
6460
6461 // Values don't represent the same base.
6462 ok = false;
6463 }
6464 }
6465
6466 return ok;
6467 }
6468
6469 // Conservatively return false.
6470 return false;
6471}
alan-bakere9308012019-03-15 10:25:13 -04006472
6473bool SPIRVProducerPass::CalledWithCoherentResource(Argument &Arg) {
6474 if (!Arg.getType()->isPointerTy() ||
6475 Arg.getType()->getPointerAddressSpace() != clspv::AddressSpace::Global) {
6476 // Only SSBOs need to be annotated as coherent.
6477 return false;
6478 }
6479
6480 DenseSet<Value *> visited;
6481 std::vector<Value *> stack;
6482 for (auto *U : Arg.getParent()->users()) {
6483 if (auto *call = dyn_cast<CallInst>(U)) {
6484 stack.push_back(call->getOperand(Arg.getArgNo()));
6485 }
6486 }
6487
6488 while (!stack.empty()) {
6489 Value *v = stack.back();
6490 stack.pop_back();
6491
6492 if (!visited.insert(v).second)
6493 continue;
6494
6495 auto *resource_call = dyn_cast<CallInst>(v);
6496 if (resource_call &&
6497 resource_call->getCalledFunction()->getName().startswith(
6498 clspv::ResourceAccessorFunction())) {
6499 // If this is a resource accessor function, check if the coherent operand
6500 // is set.
6501 const auto coherent =
6502 unsigned(dyn_cast<ConstantInt>(resource_call->getArgOperand(5))
6503 ->getZExtValue());
6504 if (coherent == 1)
6505 return true;
6506 } else if (auto *arg = dyn_cast<Argument>(v)) {
6507 // If this is a function argument, trace through its callers.
6508 for (auto U : arg->users()) {
6509 if (auto *call = dyn_cast<CallInst>(U)) {
6510 stack.push_back(call->getOperand(arg->getArgNo()));
6511 }
6512 }
6513 } else if (auto *user = dyn_cast<User>(v)) {
6514 // If this is a user, traverse all operands that could lead to resource
6515 // variables.
6516 for (unsigned i = 0; i != user->getNumOperands(); ++i) {
6517 Value *operand = user->getOperand(i);
6518 if (operand->getType()->isPointerTy() &&
6519 operand->getType()->getPointerAddressSpace() ==
6520 clspv::AddressSpace::Global) {
6521 stack.push_back(operand);
6522 }
6523 }
6524 }
6525 }
6526
6527 // No coherent resource variables encountered.
6528 return false;
6529}