blob: ea74e4e53cebca2c1f3c4d228f81f5a4c350488f [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);
2322 } else {
2323 CFPTy->print(errs());
2324 llvm_unreachable("Implement this ConstantFP Type");
2325 }
2326
2327 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002328
David Neto257c3892018-04-11 13:19:45 -04002329 Ops << MkFloat(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002330 } else if (isa<ConstantDataSequential>(Cst) &&
2331 cast<ConstantDataSequential>(Cst)->isString()) {
2332 Cst->print(errs());
2333 llvm_unreachable("Implement this Constant");
2334
2335 } else if (const ConstantDataSequential *CDS =
2336 dyn_cast<ConstantDataSequential>(Cst)) {
David Neto49351ac2017-08-26 17:32:20 -04002337 // Let's convert <4 x i8> constant to int constant specially.
2338 // This case occurs when all the values are specified as constant
2339 // ints.
2340 Type *CstTy = Cst->getType();
2341 if (is4xi8vec(CstTy)) {
2342 LLVMContext &Context = CstTy->getContext();
2343
2344 //
2345 // Generate OpConstant with OpTypeInt 32 0.
2346 //
Neil Henning39672102017-09-29 14:33:13 +01002347 uint32_t IntValue = 0;
2348 for (unsigned k = 0; k < 4; k++) {
2349 const uint64_t Val = CDS->getElementAsInteger(k);
David Neto49351ac2017-08-26 17:32:20 -04002350 IntValue = (IntValue << 8) | (Val & 0xffu);
2351 }
2352
2353 Type *i32 = Type::getInt32Ty(Context);
2354 Constant *CstInt = ConstantInt::get(i32, IntValue);
2355 // If this constant is already registered on VMap, use it.
2356 if (VMap.count(CstInt)) {
2357 uint32_t CstID = VMap[CstInt];
2358 VMap[Cst] = CstID;
2359 continue;
2360 }
2361
David Neto257c3892018-04-11 13:19:45 -04002362 Ops << MkNum(IntValue);
David Neto49351ac2017-08-26 17:32:20 -04002363
David Neto87846742018-04-11 17:36:22 -04002364 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto49351ac2017-08-26 17:32:20 -04002365 SPIRVInstList.push_back(CstInst);
2366
2367 continue;
2368 }
2369
2370 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002371 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
2372 Constant *EleCst = CDS->getElementAsConstant(k);
2373 uint32_t EleCstID = VMap[EleCst];
David Neto257c3892018-04-11 13:19:45 -04002374 Ops << MkId(EleCstID);
David Neto22f144c2017-06-12 14:26:21 -04002375 }
2376
2377 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002378 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2379 // Let's convert <4 x i8> constant to int constant specially.
David Neto49351ac2017-08-26 17:32:20 -04002380 // This case occurs when at least one of the values is an undef.
David Neto22f144c2017-06-12 14:26:21 -04002381 Type *CstTy = Cst->getType();
2382 if (is4xi8vec(CstTy)) {
2383 LLVMContext &Context = CstTy->getContext();
2384
2385 //
2386 // Generate OpConstant with OpTypeInt 32 0.
2387 //
Neil Henning39672102017-09-29 14:33:13 +01002388 uint32_t IntValue = 0;
David Neto22f144c2017-06-12 14:26:21 -04002389 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2390 I != E; ++I) {
2391 uint64_t Val = 0;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002392 const Value *CV = *I;
Neil Henning39672102017-09-29 14:33:13 +01002393 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2394 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002395 }
David Neto49351ac2017-08-26 17:32:20 -04002396 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002397 }
2398
David Neto49351ac2017-08-26 17:32:20 -04002399 Type *i32 = Type::getInt32Ty(Context);
2400 Constant *CstInt = ConstantInt::get(i32, IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002401 // If this constant is already registered on VMap, use it.
2402 if (VMap.count(CstInt)) {
2403 uint32_t CstID = VMap[CstInt];
2404 VMap[Cst] = CstID;
David Neto19a1bad2017-08-25 15:01:41 -04002405 continue;
David Neto22f144c2017-06-12 14:26:21 -04002406 }
2407
David Neto257c3892018-04-11 13:19:45 -04002408 Ops << MkNum(IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002409
David Neto87846742018-04-11 17:36:22 -04002410 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002411 SPIRVInstList.push_back(CstInst);
2412
David Neto19a1bad2017-08-25 15:01:41 -04002413 continue;
David Neto22f144c2017-06-12 14:26:21 -04002414 }
2415
2416 // We use a constant composite in SPIR-V for our constant aggregate in
2417 // LLVM.
2418 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002419
2420 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
2421 // Look up the ID of the element of this aggregate (which we will
2422 // previously have created a constant for).
2423 uint32_t ElementConstantID = VMap[CA->getAggregateElement(k)];
2424
2425 // And add an operand to the composite we are constructing
David Neto257c3892018-04-11 13:19:45 -04002426 Ops << MkId(ElementConstantID);
David Neto22f144c2017-06-12 14:26:21 -04002427 }
2428 } else if (Cst->isNullValue()) {
2429 Opcode = spv::OpConstantNull;
David Neto22f144c2017-06-12 14:26:21 -04002430 } else {
2431 Cst->print(errs());
2432 llvm_unreachable("Unsupported Constant???");
2433 }
2434
alan-baker5b86ed72019-02-15 08:26:50 -05002435 if (Opcode == spv::OpConstantNull && Cst->getType()->isPointerTy()) {
2436 // Null pointer requires variable pointers.
2437 setVariablePointersCapabilities(Cst->getType()->getPointerAddressSpace());
2438 }
2439
David Neto87846742018-04-11 17:36:22 -04002440 auto *CstInst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002441 SPIRVInstList.push_back(CstInst);
2442 }
2443}
2444
2445void SPIRVProducerPass::GenerateSamplers(Module &M) {
2446 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto22f144c2017-06-12 14:26:21 -04002447
alan-bakerb6b09dc2018-11-08 16:59:28 -05002448 auto &sampler_map = getSamplerMap();
David Neto862b7d82018-06-14 18:48:37 -04002449 SamplerMapIndexToIDMap.clear();
David Neto22f144c2017-06-12 14:26:21 -04002450 DenseMap<unsigned, unsigned> SamplerLiteralToIDMap;
David Neto862b7d82018-06-14 18:48:37 -04002451 DenseMap<unsigned, unsigned> SamplerLiteralToDescriptorSetMap;
2452 DenseMap<unsigned, unsigned> SamplerLiteralToBindingMap;
David Neto22f144c2017-06-12 14:26:21 -04002453
David Neto862b7d82018-06-14 18:48:37 -04002454 // We might have samplers in the sampler map that are not used
2455 // in the translation unit. We need to allocate variables
2456 // for them and bindings too.
2457 DenseSet<unsigned> used_bindings;
David Neto22f144c2017-06-12 14:26:21 -04002458
alan-bakerb6b09dc2018-11-08 16:59:28 -05002459 auto *var_fn = M.getFunction("clspv.sampler.var.literal");
2460 if (!var_fn)
2461 return;
David Neto862b7d82018-06-14 18:48:37 -04002462 for (auto user : var_fn->users()) {
2463 // Populate SamplerLiteralToDescriptorSetMap and
2464 // SamplerLiteralToBindingMap.
2465 //
2466 // Look for calls like
2467 // call %opencl.sampler_t addrspace(2)*
2468 // @clspv.sampler.var.literal(
2469 // i32 descriptor,
2470 // i32 binding,
2471 // i32 index-into-sampler-map)
alan-bakerb6b09dc2018-11-08 16:59:28 -05002472 if (auto *call = dyn_cast<CallInst>(user)) {
2473 const size_t index_into_sampler_map = static_cast<size_t>(
2474 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04002475 if (index_into_sampler_map >= sampler_map.size()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002476 errs() << "Out of bounds index to sampler map: "
2477 << index_into_sampler_map;
David Neto862b7d82018-06-14 18:48:37 -04002478 llvm_unreachable("bad sampler init: out of bounds");
2479 }
2480
2481 auto sampler_value = sampler_map[index_into_sampler_map].first;
2482 const auto descriptor_set = static_cast<unsigned>(
2483 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
2484 const auto binding = static_cast<unsigned>(
2485 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
2486
2487 SamplerLiteralToDescriptorSetMap[sampler_value] = descriptor_set;
2488 SamplerLiteralToBindingMap[sampler_value] = binding;
2489 used_bindings.insert(binding);
2490 }
2491 }
2492
2493 unsigned index = 0;
2494 for (auto SamplerLiteral : sampler_map) {
David Neto22f144c2017-06-12 14:26:21 -04002495 // Generate OpVariable.
2496 //
2497 // GIDOps[0] : Result Type ID
2498 // GIDOps[1] : Storage Class
2499 SPIRVOperandList Ops;
2500
David Neto257c3892018-04-11 13:19:45 -04002501 Ops << MkId(lookupType(SamplerTy))
2502 << MkNum(spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002503
David Neto862b7d82018-06-14 18:48:37 -04002504 auto sampler_var_id = nextID++;
2505 auto *Inst = new SPIRVInstruction(spv::OpVariable, sampler_var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002506 SPIRVInstList.push_back(Inst);
2507
David Neto862b7d82018-06-14 18:48:37 -04002508 SamplerMapIndexToIDMap[index] = sampler_var_id;
2509 SamplerLiteralToIDMap[SamplerLiteral.first] = sampler_var_id;
David Neto22f144c2017-06-12 14:26:21 -04002510
2511 // Find Insert Point for OpDecorate.
2512 auto DecoInsertPoint =
2513 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2514 [](SPIRVInstruction *Inst) -> bool {
2515 return Inst->getOpcode() != spv::OpDecorate &&
2516 Inst->getOpcode() != spv::OpMemberDecorate &&
2517 Inst->getOpcode() != spv::OpExtInstImport;
2518 });
2519
2520 // Ops[0] = Target ID
2521 // Ops[1] = Decoration (DescriptorSet)
2522 // Ops[2] = LiteralNumber according to Decoration
2523 Ops.clear();
2524
David Neto862b7d82018-06-14 18:48:37 -04002525 unsigned descriptor_set;
2526 unsigned binding;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002527 if (SamplerLiteralToBindingMap.find(SamplerLiteral.first) ==
2528 SamplerLiteralToBindingMap.end()) {
David Neto862b7d82018-06-14 18:48:37 -04002529 // This sampler is not actually used. Find the next one.
2530 for (binding = 0; used_bindings.count(binding); binding++)
2531 ;
2532 descriptor_set = 0; // Literal samplers always use descriptor set 0.
2533 used_bindings.insert(binding);
2534 } else {
2535 descriptor_set = SamplerLiteralToDescriptorSetMap[SamplerLiteral.first];
2536 binding = SamplerLiteralToBindingMap[SamplerLiteral.first];
2537 }
2538
2539 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationDescriptorSet)
2540 << MkNum(descriptor_set);
David Neto22f144c2017-06-12 14:26:21 -04002541
alan-bakerf5e5f692018-11-27 08:33:24 -05002542 version0::DescriptorMapEntry::SamplerData sampler_data = {SamplerLiteral.first};
2543 descriptorMapEntries->emplace_back(std::move(sampler_data), descriptor_set, binding);
David Neto22f144c2017-06-12 14:26:21 -04002544
David Neto87846742018-04-11 17:36:22 -04002545 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002546 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2547
2548 // Ops[0] = Target ID
2549 // Ops[1] = Decoration (Binding)
2550 // Ops[2] = LiteralNumber according to Decoration
2551 Ops.clear();
David Neto862b7d82018-06-14 18:48:37 -04002552 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationBinding)
2553 << MkNum(binding);
David Neto22f144c2017-06-12 14:26:21 -04002554
David Neto87846742018-04-11 17:36:22 -04002555 auto *BindDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002556 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
David Neto862b7d82018-06-14 18:48:37 -04002557
2558 index++;
David Neto22f144c2017-06-12 14:26:21 -04002559 }
David Neto862b7d82018-06-14 18:48:37 -04002560}
David Neto22f144c2017-06-12 14:26:21 -04002561
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01002562void SPIRVProducerPass::GenerateResourceVars(Module &) {
David Neto862b7d82018-06-14 18:48:37 -04002563 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2564 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04002565
David Neto862b7d82018-06-14 18:48:37 -04002566 // Generate variables. Make one for each of resource var info object.
2567 for (auto *info : ModuleOrderedResourceVars) {
2568 Type *type = info->var_fn->getReturnType();
2569 // Remap the address space for opaque types.
2570 switch (info->arg_kind) {
2571 case clspv::ArgKind::Sampler:
2572 case clspv::ArgKind::ReadOnlyImage:
2573 case clspv::ArgKind::WriteOnlyImage:
2574 type = PointerType::get(type->getPointerElementType(),
2575 clspv::AddressSpace::UniformConstant);
2576 break;
2577 default:
2578 break;
2579 }
David Neto22f144c2017-06-12 14:26:21 -04002580
David Neto862b7d82018-06-14 18:48:37 -04002581 info->var_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04002582
David Neto862b7d82018-06-14 18:48:37 -04002583 const auto type_id = lookupType(type);
2584 const auto sc = GetStorageClassForArgKind(info->arg_kind);
2585 SPIRVOperandList Ops;
2586 Ops << MkId(type_id) << MkNum(sc);
David Neto22f144c2017-06-12 14:26:21 -04002587
David Neto862b7d82018-06-14 18:48:37 -04002588 auto *Inst = new SPIRVInstruction(spv::OpVariable, info->var_id, Ops);
2589 SPIRVInstList.push_back(Inst);
2590
2591 // Map calls to the variable-builtin-function.
2592 for (auto &U : info->var_fn->uses()) {
2593 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
2594 const auto set = unsigned(
2595 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
2596 const auto binding = unsigned(
2597 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
2598 if (set == info->descriptor_set && binding == info->binding) {
2599 switch (info->arg_kind) {
2600 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002601 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002602 case clspv::ArgKind::Pod:
2603 // The call maps to the variable directly.
2604 VMap[call] = info->var_id;
2605 break;
2606 case clspv::ArgKind::Sampler:
2607 case clspv::ArgKind::ReadOnlyImage:
2608 case clspv::ArgKind::WriteOnlyImage:
2609 // The call maps to a load we generate later.
2610 ResourceVarDeferredLoadCalls[call] = info->var_id;
2611 break;
2612 default:
2613 llvm_unreachable("Unhandled arg kind");
2614 }
2615 }
David Neto22f144c2017-06-12 14:26:21 -04002616 }
David Neto862b7d82018-06-14 18:48:37 -04002617 }
2618 }
David Neto22f144c2017-06-12 14:26:21 -04002619
David Neto862b7d82018-06-14 18:48:37 -04002620 // Generate associated decorations.
David Neto22f144c2017-06-12 14:26:21 -04002621
David Neto862b7d82018-06-14 18:48:37 -04002622 // Find Insert Point for OpDecorate.
2623 auto DecoInsertPoint =
2624 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2625 [](SPIRVInstruction *Inst) -> bool {
2626 return Inst->getOpcode() != spv::OpDecorate &&
2627 Inst->getOpcode() != spv::OpMemberDecorate &&
2628 Inst->getOpcode() != spv::OpExtInstImport;
2629 });
2630
2631 SPIRVOperandList Ops;
2632 for (auto *info : ModuleOrderedResourceVars) {
2633 // Decorate with DescriptorSet and Binding.
2634 Ops.clear();
2635 Ops << MkId(info->var_id) << MkNum(spv::DecorationDescriptorSet)
2636 << MkNum(info->descriptor_set);
2637 SPIRVInstList.insert(DecoInsertPoint,
2638 new SPIRVInstruction(spv::OpDecorate, Ops));
2639
2640 Ops.clear();
2641 Ops << MkId(info->var_id) << MkNum(spv::DecorationBinding)
2642 << MkNum(info->binding);
2643 SPIRVInstList.insert(DecoInsertPoint,
2644 new SPIRVInstruction(spv::OpDecorate, Ops));
2645
alan-bakere9308012019-03-15 10:25:13 -04002646 if (info->coherent) {
2647 // Decorate with Coherent if required for the variable.
2648 Ops.clear();
2649 Ops << MkId(info->var_id) << MkNum(spv::DecorationCoherent);
2650 SPIRVInstList.insert(DecoInsertPoint,
2651 new SPIRVInstruction(spv::OpDecorate, Ops));
2652 }
2653
David Neto862b7d82018-06-14 18:48:37 -04002654 // Generate NonWritable and NonReadable
2655 switch (info->arg_kind) {
2656 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002657 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002658 if (info->var_fn->getReturnType()->getPointerAddressSpace() ==
2659 clspv::AddressSpace::Constant) {
2660 Ops.clear();
2661 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
2662 SPIRVInstList.insert(DecoInsertPoint,
2663 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002664 }
David Neto862b7d82018-06-14 18:48:37 -04002665 break;
David Neto862b7d82018-06-14 18:48:37 -04002666 case clspv::ArgKind::WriteOnlyImage:
2667 Ops.clear();
2668 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonReadable);
2669 SPIRVInstList.insert(DecoInsertPoint,
2670 new SPIRVInstruction(spv::OpDecorate, Ops));
2671 break;
2672 default:
2673 break;
David Neto22f144c2017-06-12 14:26:21 -04002674 }
2675 }
2676}
2677
2678void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002679 Module &M = *GV.getParent();
David Neto22f144c2017-06-12 14:26:21 -04002680 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2681 ValueMapType &VMap = getValueMap();
2682 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07002683 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002684
2685 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2686 Type *Ty = GV.getType();
2687 PointerType *PTy = cast<PointerType>(Ty);
2688
2689 uint32_t InitializerID = 0;
2690
2691 // Workgroup size is handled differently (it goes into a constant)
2692 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2693 std::vector<bool> HasMDVec;
2694 uint32_t PrevXDimCst = 0xFFFFFFFF;
2695 uint32_t PrevYDimCst = 0xFFFFFFFF;
2696 uint32_t PrevZDimCst = 0xFFFFFFFF;
2697 for (Function &Func : *GV.getParent()) {
2698 if (Func.isDeclaration()) {
2699 continue;
2700 }
2701
2702 // We only need to check kernels.
2703 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2704 continue;
2705 }
2706
2707 if (const MDNode *MD =
2708 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2709 uint32_t CurXDimCst = static_cast<uint32_t>(
2710 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2711 uint32_t CurYDimCst = static_cast<uint32_t>(
2712 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2713 uint32_t CurZDimCst = static_cast<uint32_t>(
2714 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2715
2716 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2717 PrevZDimCst == 0xFFFFFFFF) {
2718 PrevXDimCst = CurXDimCst;
2719 PrevYDimCst = CurYDimCst;
2720 PrevZDimCst = CurZDimCst;
2721 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2722 CurZDimCst != PrevZDimCst) {
2723 llvm_unreachable(
2724 "reqd_work_group_size must be the same across all kernels");
2725 } else {
2726 continue;
2727 }
2728
2729 //
2730 // Generate OpConstantComposite.
2731 //
2732 // Ops[0] : Result Type ID
2733 // Ops[1] : Constant size for x dimension.
2734 // Ops[2] : Constant size for y dimension.
2735 // Ops[3] : Constant size for z dimension.
2736 SPIRVOperandList Ops;
2737
2738 uint32_t XDimCstID =
2739 VMap[mdconst::extract<ConstantInt>(MD->getOperand(0))];
2740 uint32_t YDimCstID =
2741 VMap[mdconst::extract<ConstantInt>(MD->getOperand(1))];
2742 uint32_t ZDimCstID =
2743 VMap[mdconst::extract<ConstantInt>(MD->getOperand(2))];
2744
2745 InitializerID = nextID;
2746
David Neto257c3892018-04-11 13:19:45 -04002747 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2748 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002749
David Neto87846742018-04-11 17:36:22 -04002750 auto *Inst =
2751 new SPIRVInstruction(spv::OpConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002752 SPIRVInstList.push_back(Inst);
2753
2754 HasMDVec.push_back(true);
2755 } else {
2756 HasMDVec.push_back(false);
2757 }
2758 }
2759
2760 // Check all kernels have same definitions for work_group_size.
2761 bool HasMD = false;
2762 if (!HasMDVec.empty()) {
2763 HasMD = HasMDVec[0];
2764 for (uint32_t i = 1; i < HasMDVec.size(); i++) {
2765 if (HasMD != HasMDVec[i]) {
2766 llvm_unreachable(
2767 "Kernels should have consistent work group size definition");
2768 }
2769 }
2770 }
2771
2772 // If all kernels do not have metadata for reqd_work_group_size, generate
2773 // OpSpecConstants for x/y/z dimension.
2774 if (!HasMD) {
2775 //
2776 // Generate OpSpecConstants for x/y/z dimension.
2777 //
2778 // Ops[0] : Result Type ID
2779 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
2780 uint32_t XDimCstID = 0;
2781 uint32_t YDimCstID = 0;
2782 uint32_t ZDimCstID = 0;
2783
David Neto22f144c2017-06-12 14:26:21 -04002784 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04002785 uint32_t result_type_id =
2786 lookupType(Ty->getPointerElementType()->getSequentialElementType());
David Neto22f144c2017-06-12 14:26:21 -04002787
David Neto257c3892018-04-11 13:19:45 -04002788 // X Dimension
2789 Ops << MkId(result_type_id) << MkNum(1);
2790 XDimCstID = nextID++;
2791 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002792 new SPIRVInstruction(spv::OpSpecConstant, XDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002793
2794 // Y Dimension
2795 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002796 Ops << MkId(result_type_id) << MkNum(1);
2797 YDimCstID = nextID++;
2798 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002799 new SPIRVInstruction(spv::OpSpecConstant, YDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002800
2801 // Z Dimension
2802 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002803 Ops << MkId(result_type_id) << MkNum(1);
2804 ZDimCstID = nextID++;
2805 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002806 new SPIRVInstruction(spv::OpSpecConstant, ZDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002807
David Neto257c3892018-04-11 13:19:45 -04002808 BuiltinDimVec.push_back(XDimCstID);
2809 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002810 BuiltinDimVec.push_back(ZDimCstID);
2811
David Neto22f144c2017-06-12 14:26:21 -04002812 //
2813 // Generate OpSpecConstantComposite.
2814 //
2815 // Ops[0] : Result Type ID
2816 // Ops[1] : Constant size for x dimension.
2817 // Ops[2] : Constant size for y dimension.
2818 // Ops[3] : Constant size for z dimension.
2819 InitializerID = nextID;
2820
2821 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002822 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2823 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002824
David Neto87846742018-04-11 17:36:22 -04002825 auto *Inst =
2826 new SPIRVInstruction(spv::OpSpecConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002827 SPIRVInstList.push_back(Inst);
2828 }
2829 }
2830
David Neto22f144c2017-06-12 14:26:21 -04002831 VMap[&GV] = nextID;
2832
2833 //
2834 // Generate OpVariable.
2835 //
2836 // GIDOps[0] : Result Type ID
2837 // GIDOps[1] : Storage Class
2838 SPIRVOperandList Ops;
2839
David Neto85082642018-03-24 06:55:20 -07002840 const auto AS = PTy->getAddressSpace();
David Netoc6f3ab22018-04-06 18:02:31 -04002841 Ops << MkId(lookupType(Ty)) << MkNum(GetStorageClass(AS));
David Neto22f144c2017-06-12 14:26:21 -04002842
David Neto85082642018-03-24 06:55:20 -07002843 if (GV.hasInitializer()) {
2844 InitializerID = VMap[GV.getInitializer()];
David Neto22f144c2017-06-12 14:26:21 -04002845 }
2846
David Neto85082642018-03-24 06:55:20 -07002847 const bool module_scope_constant_external_init =
David Neto862b7d82018-06-14 18:48:37 -04002848 (AS == AddressSpace::Constant) && GV.hasInitializer() &&
David Neto85082642018-03-24 06:55:20 -07002849 clspv::Option::ModuleConstantsInStorageBuffer();
2850
2851 if (0 != InitializerID) {
2852 if (!module_scope_constant_external_init) {
2853 // Emit the ID of the intiializer as part of the variable definition.
David Netoc6f3ab22018-04-06 18:02:31 -04002854 Ops << MkId(InitializerID);
David Neto85082642018-03-24 06:55:20 -07002855 }
2856 }
2857 const uint32_t var_id = nextID++;
2858
David Neto87846742018-04-11 17:36:22 -04002859 auto *Inst = new SPIRVInstruction(spv::OpVariable, var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002860 SPIRVInstList.push_back(Inst);
2861
2862 // If we have a builtin.
2863 if (spv::BuiltInMax != BuiltinType) {
2864 // Find Insert Point for OpDecorate.
2865 auto DecoInsertPoint =
2866 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2867 [](SPIRVInstruction *Inst) -> bool {
2868 return Inst->getOpcode() != spv::OpDecorate &&
2869 Inst->getOpcode() != spv::OpMemberDecorate &&
2870 Inst->getOpcode() != spv::OpExtInstImport;
2871 });
2872 //
2873 // Generate OpDecorate.
2874 //
2875 // DOps[0] = Target ID
2876 // DOps[1] = Decoration (Builtin)
2877 // DOps[2] = BuiltIn ID
2878 uint32_t ResultID;
2879
2880 // WorkgroupSize is different, we decorate the constant composite that has
2881 // its value, rather than the variable that we use to access the value.
2882 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2883 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04002884 // Save both the value and variable IDs for later.
2885 WorkgroupSizeValueID = InitializerID;
2886 WorkgroupSizeVarID = VMap[&GV];
David Neto22f144c2017-06-12 14:26:21 -04002887 } else {
2888 ResultID = VMap[&GV];
2889 }
2890
2891 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002892 DOps << MkId(ResultID) << MkNum(spv::DecorationBuiltIn)
2893 << MkNum(BuiltinType);
David Neto22f144c2017-06-12 14:26:21 -04002894
David Neto87846742018-04-11 17:36:22 -04002895 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, DOps);
David Neto22f144c2017-06-12 14:26:21 -04002896 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
David Neto85082642018-03-24 06:55:20 -07002897 } else if (module_scope_constant_external_init) {
2898 // This module scope constant is initialized from a storage buffer with data
2899 // provided by the host at binding 0 of the next descriptor set.
David Neto78383442018-06-15 20:31:56 -04002900 const uint32_t descriptor_set = TakeDescriptorIndex(&M);
David Neto85082642018-03-24 06:55:20 -07002901
David Neto862b7d82018-06-14 18:48:37 -04002902 // Emit the intializer to the descriptor map file.
David Neto85082642018-03-24 06:55:20 -07002903 // Use "kind,buffer" to indicate storage buffer. We might want to expand
2904 // that later to other types, like uniform buffer.
alan-bakerf5e5f692018-11-27 08:33:24 -05002905 std::string hexbytes;
2906 llvm::raw_string_ostream str(hexbytes);
2907 clspv::ConstantEmitter(DL, str).Emit(GV.getInitializer());
2908 version0::DescriptorMapEntry::ConstantData constant_data = {ArgKind::Buffer, str.str()};
2909 descriptorMapEntries->emplace_back(std::move(constant_data), descriptor_set, 0);
David Neto85082642018-03-24 06:55:20 -07002910
2911 // Find Insert Point for OpDecorate.
2912 auto DecoInsertPoint =
2913 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2914 [](SPIRVInstruction *Inst) -> bool {
2915 return Inst->getOpcode() != spv::OpDecorate &&
2916 Inst->getOpcode() != spv::OpMemberDecorate &&
2917 Inst->getOpcode() != spv::OpExtInstImport;
2918 });
2919
David Neto257c3892018-04-11 13:19:45 -04002920 // OpDecorate %var Binding <binding>
David Neto85082642018-03-24 06:55:20 -07002921 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002922 DOps << MkId(var_id) << MkNum(spv::DecorationBinding) << MkNum(0);
2923 DecoInsertPoint = SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04002924 DecoInsertPoint, new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto85082642018-03-24 06:55:20 -07002925
2926 // OpDecorate %var DescriptorSet <descriptor_set>
2927 DOps.clear();
David Neto257c3892018-04-11 13:19:45 -04002928 DOps << MkId(var_id) << MkNum(spv::DecorationDescriptorSet)
2929 << MkNum(descriptor_set);
David Netoc6f3ab22018-04-06 18:02:31 -04002930 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04002931 new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto22f144c2017-06-12 14:26:21 -04002932 }
2933}
2934
David Netoc6f3ab22018-04-06 18:02:31 -04002935void SPIRVProducerPass::GenerateWorkgroupVars() {
2936 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
Alan Baker202c8c72018-08-13 13:47:44 -04002937 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2938 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002939 LocalArgInfo &info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002940
2941 // Generate OpVariable.
2942 //
2943 // GIDOps[0] : Result Type ID
2944 // GIDOps[1] : Storage Class
2945 SPIRVOperandList Ops;
2946 Ops << MkId(info.ptr_array_type_id) << MkNum(spv::StorageClassWorkgroup);
2947
2948 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002949 new SPIRVInstruction(spv::OpVariable, info.variable_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002950 }
2951}
2952
David Neto862b7d82018-06-14 18:48:37 -04002953void SPIRVProducerPass::GenerateDescriptorMapInfo(const DataLayout &DL,
2954 Function &F) {
David Netoc5fb5242018-07-30 13:28:31 -04002955 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2956 return;
2957 }
David Neto862b7d82018-06-14 18:48:37 -04002958 // Gather the list of resources that are used by this function's arguments.
2959 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
2960
alan-bakerf5e5f692018-11-27 08:33:24 -05002961 // TODO(alan-baker): This should become unnecessary by fixing the rest of the
2962 // flow to generate pod_ubo arguments earlier.
David Neto862b7d82018-06-14 18:48:37 -04002963 auto remap_arg_kind = [](StringRef argKind) {
alan-bakerf5e5f692018-11-27 08:33:24 -05002964 std::string kind =
2965 clspv::Option::PodArgsInUniformBuffer() && argKind.equals("pod")
2966 ? "pod_ubo"
2967 : argKind;
2968 return GetArgKindFromName(kind);
David Neto862b7d82018-06-14 18:48:37 -04002969 };
2970
2971 auto *fty = F.getType()->getPointerElementType();
2972 auto *func_ty = dyn_cast<FunctionType>(fty);
2973
2974 // If we've clustereed POD arguments, then argument details are in metadata.
2975 // If an argument maps to a resource variable, then get descriptor set and
2976 // binding from the resoure variable. Other info comes from the metadata.
2977 const auto *arg_map = F.getMetadata("kernel_arg_map");
2978 if (arg_map) {
2979 for (const auto &arg : arg_map->operands()) {
2980 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
Kévin PETITa353c832018-03-20 23:21:21 +00002981 assert(arg_node->getNumOperands() == 7);
David Neto862b7d82018-06-14 18:48:37 -04002982 const auto name =
2983 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
2984 const auto old_index =
2985 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
2986 // Remapped argument index
alan-bakerb6b09dc2018-11-08 16:59:28 -05002987 const size_t new_index = static_cast<size_t>(
2988 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04002989 const auto offset =
2990 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
Kévin PETITa353c832018-03-20 23:21:21 +00002991 const auto arg_size =
2992 dyn_extract<ConstantInt>(arg_node->getOperand(4))->getZExtValue();
David Neto862b7d82018-06-14 18:48:37 -04002993 const auto argKind = remap_arg_kind(
Kévin PETITa353c832018-03-20 23:21:21 +00002994 dyn_cast<MDString>(arg_node->getOperand(5))->getString());
David Neto862b7d82018-06-14 18:48:37 -04002995 const auto spec_id =
Kévin PETITa353c832018-03-20 23:21:21 +00002996 dyn_extract<ConstantInt>(arg_node->getOperand(6))->getSExtValue();
alan-bakerf5e5f692018-11-27 08:33:24 -05002997
2998 uint32_t descriptor_set = 0;
2999 uint32_t binding = 0;
3000 version0::DescriptorMapEntry::KernelArgData kernel_data = {
3001 F.getName(),
3002 name,
3003 static_cast<uint32_t>(old_index),
3004 argKind,
3005 static_cast<uint32_t>(spec_id),
3006 // This will be set below for pointer-to-local args.
3007 0,
3008 static_cast<uint32_t>(offset),
3009 static_cast<uint32_t>(arg_size)};
David Neto862b7d82018-06-14 18:48:37 -04003010 if (spec_id > 0) {
alan-bakerf5e5f692018-11-27 08:33:24 -05003011 kernel_data.local_element_size = static_cast<uint32_t>(GetTypeAllocSize(
3012 func_ty->getParamType(unsigned(new_index))->getPointerElementType(),
3013 DL));
David Neto862b7d82018-06-14 18:48:37 -04003014 } else {
3015 auto *info = resource_var_at_index[new_index];
3016 assert(info);
alan-bakerf5e5f692018-11-27 08:33:24 -05003017 descriptor_set = info->descriptor_set;
3018 binding = info->binding;
David Neto862b7d82018-06-14 18:48:37 -04003019 }
alan-bakerf5e5f692018-11-27 08:33:24 -05003020 descriptorMapEntries->emplace_back(std::move(kernel_data), descriptor_set, binding);
David Neto862b7d82018-06-14 18:48:37 -04003021 }
3022 } else {
3023 // There is no argument map.
3024 // Take descriptor info from the resource variable calls.
Kévin PETITa353c832018-03-20 23:21:21 +00003025 // Take argument name and size from the arguments list.
David Neto862b7d82018-06-14 18:48:37 -04003026
3027 SmallVector<Argument *, 4> arguments;
3028 for (auto &arg : F.args()) {
3029 arguments.push_back(&arg);
3030 }
3031
3032 unsigned arg_index = 0;
3033 for (auto *info : resource_var_at_index) {
3034 if (info) {
Kévin PETITa353c832018-03-20 23:21:21 +00003035 auto arg = arguments[arg_index];
alan-bakerb6b09dc2018-11-08 16:59:28 -05003036 unsigned arg_size = 0;
Kévin PETITa353c832018-03-20 23:21:21 +00003037 if (info->arg_kind == clspv::ArgKind::Pod) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05003038 arg_size = static_cast<uint32_t>(DL.getTypeStoreSize(arg->getType()));
Kévin PETITa353c832018-03-20 23:21:21 +00003039 }
3040
alan-bakerf5e5f692018-11-27 08:33:24 -05003041 // Local pointer arguments are unused in this case. Offset is always zero.
3042 version0::DescriptorMapEntry::KernelArgData kernel_data = {
3043 F.getName(), arg->getName(),
3044 arg_index, remap_arg_kind(clspv::GetArgKindName(info->arg_kind)),
3045 0, 0,
3046 0, arg_size};
3047 descriptorMapEntries->emplace_back(std::move(kernel_data),
3048 info->descriptor_set, info->binding);
David Neto862b7d82018-06-14 18:48:37 -04003049 }
3050 arg_index++;
3051 }
3052 // Generate mappings for pointer-to-local arguments.
3053 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
3054 Argument *arg = arguments[arg_index];
Alan Baker202c8c72018-08-13 13:47:44 -04003055 auto where = LocalArgSpecIds.find(arg);
3056 if (where != LocalArgSpecIds.end()) {
3057 auto &local_arg_info = LocalSpecIdInfoMap[where->second];
alan-bakerf5e5f692018-11-27 08:33:24 -05003058 // Pod arguments members are unused in this case.
3059 version0::DescriptorMapEntry::KernelArgData kernel_data = {
3060 F.getName(),
3061 arg->getName(),
3062 arg_index,
3063 ArgKind::Local,
3064 static_cast<uint32_t>(local_arg_info.spec_id),
3065 static_cast<uint32_t>(GetTypeAllocSize(local_arg_info.elem_type, DL)),
3066 0,
3067 0};
3068 // Pointer-to-local arguments do not utilize descriptor set and binding.
3069 descriptorMapEntries->emplace_back(std::move(kernel_data), 0, 0);
David Neto862b7d82018-06-14 18:48:37 -04003070 }
3071 }
3072 }
3073}
3074
David Neto22f144c2017-06-12 14:26:21 -04003075void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
3076 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3077 ValueMapType &VMap = getValueMap();
3078 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04003079 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
3080 auto &GlobalConstArgSet = getGlobalConstArgSet();
3081
3082 FunctionType *FTy = F.getFunctionType();
3083
3084 //
David Neto22f144c2017-06-12 14:26:21 -04003085 // Generate OPFunction.
3086 //
3087
3088 // FOps[0] : Result Type ID
3089 // FOps[1] : Function Control
3090 // FOps[2] : Function Type ID
3091 SPIRVOperandList FOps;
3092
3093 // Find SPIRV instruction for return type.
David Neto257c3892018-04-11 13:19:45 -04003094 FOps << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04003095
3096 // Check function attributes for SPIRV Function Control.
3097 uint32_t FuncControl = spv::FunctionControlMaskNone;
3098 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
3099 FuncControl |= spv::FunctionControlInlineMask;
3100 }
3101 if (F.hasFnAttribute(Attribute::NoInline)) {
3102 FuncControl |= spv::FunctionControlDontInlineMask;
3103 }
3104 // TODO: Check llvm attribute for Function Control Pure.
3105 if (F.hasFnAttribute(Attribute::ReadOnly)) {
3106 FuncControl |= spv::FunctionControlPureMask;
3107 }
3108 // TODO: Check llvm attribute for Function Control Const.
3109 if (F.hasFnAttribute(Attribute::ReadNone)) {
3110 FuncControl |= spv::FunctionControlConstMask;
3111 }
3112
David Neto257c3892018-04-11 13:19:45 -04003113 FOps << MkNum(FuncControl);
David Neto22f144c2017-06-12 14:26:21 -04003114
3115 uint32_t FTyID;
3116 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3117 SmallVector<Type *, 4> NewFuncParamTys;
3118 FunctionType *NewFTy =
3119 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
3120 FTyID = lookupType(NewFTy);
3121 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07003122 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04003123 if (GlobalConstFuncTyMap.count(FTy)) {
3124 FTyID = lookupType(GlobalConstFuncTyMap[FTy].first);
3125 } else {
3126 FTyID = lookupType(FTy);
3127 }
3128 }
3129
David Neto257c3892018-04-11 13:19:45 -04003130 FOps << MkId(FTyID);
David Neto22f144c2017-06-12 14:26:21 -04003131
3132 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3133 EntryPoints.push_back(std::make_pair(&F, nextID));
3134 }
3135
3136 VMap[&F] = nextID;
3137
David Neto482550a2018-03-24 05:21:07 -07003138 if (clspv::Option::ShowIDs()) {
David Netob05675d2018-02-16 12:37:49 -05003139 errs() << "Function " << F.getName() << " is " << nextID << "\n";
3140 }
David Neto22f144c2017-06-12 14:26:21 -04003141 // Generate SPIRV instruction for function.
David Neto87846742018-04-11 17:36:22 -04003142 auto *FuncInst = new SPIRVInstruction(spv::OpFunction, nextID++, FOps);
David Neto22f144c2017-06-12 14:26:21 -04003143 SPIRVInstList.push_back(FuncInst);
3144
3145 //
3146 // Generate OpFunctionParameter for Normal function.
3147 //
3148
3149 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
alan-bakere9308012019-03-15 10:25:13 -04003150
3151 // Find Insert Point for OpDecorate.
3152 auto DecoInsertPoint =
3153 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
3154 [](SPIRVInstruction *Inst) -> bool {
3155 return Inst->getOpcode() != spv::OpDecorate &&
3156 Inst->getOpcode() != spv::OpMemberDecorate &&
3157 Inst->getOpcode() != spv::OpExtInstImport;
3158 });
3159
David Neto22f144c2017-06-12 14:26:21 -04003160 // Iterate Argument for name instead of param type from function type.
3161 unsigned ArgIdx = 0;
3162 for (Argument &Arg : F.args()) {
alan-bakere9308012019-03-15 10:25:13 -04003163 uint32_t param_id = nextID++;
3164 VMap[&Arg] = param_id;
3165
3166 if (CalledWithCoherentResource(Arg)) {
3167 // If the arg is passed a coherent resource ever, then decorate this
3168 // parameter with Coherent too.
3169 SPIRVOperandList decoration_ops;
3170 decoration_ops << MkId(param_id) << MkNum(spv::DecorationCoherent);
3171 SPIRVInstList.insert(DecoInsertPoint,
3172 new SPIRVInstruction(spv::OpDecorate, decoration_ops));
3173 }
David Neto22f144c2017-06-12 14:26:21 -04003174
3175 // ParamOps[0] : Result Type ID
3176 SPIRVOperandList ParamOps;
3177
3178 // Find SPIRV instruction for parameter type.
3179 uint32_t ParamTyID = lookupType(Arg.getType());
3180 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
3181 if (GlobalConstFuncTyMap.count(FTy)) {
3182 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
3183 Type *EleTy = PTy->getPointerElementType();
3184 Type *ArgTy =
3185 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
3186 ParamTyID = lookupType(ArgTy);
3187 GlobalConstArgSet.insert(&Arg);
3188 }
3189 }
3190 }
David Neto257c3892018-04-11 13:19:45 -04003191 ParamOps << MkId(ParamTyID);
David Neto22f144c2017-06-12 14:26:21 -04003192
3193 // Generate SPIRV instruction for parameter.
David Neto87846742018-04-11 17:36:22 -04003194 auto *ParamInst =
alan-bakere9308012019-03-15 10:25:13 -04003195 new SPIRVInstruction(spv::OpFunctionParameter, param_id, ParamOps);
David Neto22f144c2017-06-12 14:26:21 -04003196 SPIRVInstList.push_back(ParamInst);
3197
3198 ArgIdx++;
3199 }
3200 }
3201}
3202
alan-bakerb6b09dc2018-11-08 16:59:28 -05003203void SPIRVProducerPass::GenerateModuleInfo(Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04003204 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3205 EntryPointVecType &EntryPoints = getEntryPointVec();
3206 ValueMapType &VMap = getValueMap();
3207 ValueList &EntryPointInterfaces = getEntryPointInterfacesVec();
3208 uint32_t &ExtInstImportID = getOpExtInstImportID();
3209 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
3210
3211 // Set up insert point.
3212 auto InsertPoint = SPIRVInstList.begin();
3213
3214 //
3215 // Generate OpCapability
3216 //
3217 // TODO: Which llvm information is mapped to SPIRV Capapbility?
3218
3219 // Ops[0] = Capability
3220 SPIRVOperandList Ops;
3221
David Neto87846742018-04-11 17:36:22 -04003222 auto *CapInst =
3223 new SPIRVInstruction(spv::OpCapability, {MkNum(spv::CapabilityShader)});
David Neto22f144c2017-06-12 14:26:21 -04003224 SPIRVInstList.insert(InsertPoint, CapInst);
3225
3226 for (Type *Ty : getTypeList()) {
alan-bakerb39c8262019-03-08 14:03:37 -05003227 if (clspv::Option::Int8Support() && Ty->isIntegerTy(8)) {
3228 // Generate OpCapability for i8 type.
3229 SPIRVInstList.insert(InsertPoint,
3230 new SPIRVInstruction(spv::OpCapability,
3231 {MkNum(spv::CapabilityInt8)}));
3232 } else if (Ty->isIntegerTy(16)) {
David Neto22f144c2017-06-12 14:26:21 -04003233 // Generate OpCapability for i16 type.
David Neto87846742018-04-11 17:36:22 -04003234 SPIRVInstList.insert(InsertPoint,
3235 new SPIRVInstruction(spv::OpCapability,
3236 {MkNum(spv::CapabilityInt16)}));
David Neto22f144c2017-06-12 14:26:21 -04003237 } else if (Ty->isIntegerTy(64)) {
3238 // Generate OpCapability for i64 type.
David Neto87846742018-04-11 17:36:22 -04003239 SPIRVInstList.insert(InsertPoint,
3240 new SPIRVInstruction(spv::OpCapability,
3241 {MkNum(spv::CapabilityInt64)}));
David Neto22f144c2017-06-12 14:26:21 -04003242 } else if (Ty->isHalfTy()) {
3243 // Generate OpCapability for half type.
3244 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003245 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3246 {MkNum(spv::CapabilityFloat16)}));
David Neto22f144c2017-06-12 14:26:21 -04003247 } else if (Ty->isDoubleTy()) {
3248 // Generate OpCapability for double type.
3249 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003250 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3251 {MkNum(spv::CapabilityFloat64)}));
David Neto22f144c2017-06-12 14:26:21 -04003252 } else if (auto *STy = dyn_cast<StructType>(Ty)) {
3253 if (STy->isOpaque()) {
David Neto565571c2017-08-21 12:00:05 -04003254 if (STy->getName().equals("opencl.image2d_wo_t") ||
3255 STy->getName().equals("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04003256 // Generate OpCapability for write only image type.
3257 SPIRVInstList.insert(
3258 InsertPoint,
3259 new SPIRVInstruction(
David Neto87846742018-04-11 17:36:22 -04003260 spv::OpCapability,
3261 {MkNum(spv::CapabilityStorageImageWriteWithoutFormat)}));
David Neto22f144c2017-06-12 14:26:21 -04003262 }
3263 }
3264 }
3265 }
3266
David Neto5c22a252018-03-15 16:07:41 -04003267 { // OpCapability ImageQuery
3268 bool hasImageQuery = false;
3269 for (const char *imageQuery : {
3270 "_Z15get_image_width14ocl_image2d_ro",
3271 "_Z15get_image_width14ocl_image2d_wo",
3272 "_Z16get_image_height14ocl_image2d_ro",
3273 "_Z16get_image_height14ocl_image2d_wo",
3274 }) {
3275 if (module.getFunction(imageQuery)) {
3276 hasImageQuery = true;
3277 break;
3278 }
3279 }
3280 if (hasImageQuery) {
David Neto87846742018-04-11 17:36:22 -04003281 auto *ImageQueryCapInst = new SPIRVInstruction(
3282 spv::OpCapability, {MkNum(spv::CapabilityImageQuery)});
David Neto5c22a252018-03-15 16:07:41 -04003283 SPIRVInstList.insert(InsertPoint, ImageQueryCapInst);
3284 }
3285 }
3286
David Neto22f144c2017-06-12 14:26:21 -04003287 if (hasVariablePointers()) {
3288 //
David Neto22f144c2017-06-12 14:26:21 -04003289 // Generate OpCapability.
3290 //
3291 // Ops[0] = Capability
3292 //
3293 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003294 Ops << MkNum(spv::CapabilityVariablePointers);
David Neto22f144c2017-06-12 14:26:21 -04003295
David Neto87846742018-04-11 17:36:22 -04003296 SPIRVInstList.insert(InsertPoint,
3297 new SPIRVInstruction(spv::OpCapability, Ops));
alan-baker5b86ed72019-02-15 08:26:50 -05003298 } else if (hasVariablePointersStorageBuffer()) {
3299 //
3300 // Generate OpCapability.
3301 //
3302 // Ops[0] = Capability
3303 //
3304 Ops.clear();
3305 Ops << MkNum(spv::CapabilityVariablePointersStorageBuffer);
David Neto22f144c2017-06-12 14:26:21 -04003306
alan-baker5b86ed72019-02-15 08:26:50 -05003307 SPIRVInstList.insert(InsertPoint,
3308 new SPIRVInstruction(spv::OpCapability, Ops));
3309 }
3310
3311 // Always add the storage buffer extension
3312 {
David Neto22f144c2017-06-12 14:26:21 -04003313 //
3314 // Generate OpExtension.
3315 //
3316 // Ops[0] = Name (Literal String)
3317 //
alan-baker5b86ed72019-02-15 08:26:50 -05003318 auto *ExtensionInst = new SPIRVInstruction(
3319 spv::OpExtension, {MkString("SPV_KHR_storage_buffer_storage_class")});
3320 SPIRVInstList.insert(InsertPoint, ExtensionInst);
3321 }
David Neto22f144c2017-06-12 14:26:21 -04003322
alan-baker5b86ed72019-02-15 08:26:50 -05003323 if (hasVariablePointers() || hasVariablePointersStorageBuffer()) {
3324 //
3325 // Generate OpExtension.
3326 //
3327 // Ops[0] = Name (Literal String)
3328 //
3329 auto *ExtensionInst = new SPIRVInstruction(
3330 spv::OpExtension, {MkString("SPV_KHR_variable_pointers")});
3331 SPIRVInstList.insert(InsertPoint, ExtensionInst);
David Neto22f144c2017-06-12 14:26:21 -04003332 }
3333
3334 if (ExtInstImportID) {
3335 ++InsertPoint;
3336 }
3337
3338 //
3339 // Generate OpMemoryModel
3340 //
3341 // Memory model for Vulkan will always be GLSL450.
3342
3343 // Ops[0] = Addressing Model
3344 // Ops[1] = Memory Model
3345 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003346 Ops << MkNum(spv::AddressingModelLogical) << MkNum(spv::MemoryModelGLSL450);
David Neto22f144c2017-06-12 14:26:21 -04003347
David Neto87846742018-04-11 17:36:22 -04003348 auto *MemModelInst = new SPIRVInstruction(spv::OpMemoryModel, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003349 SPIRVInstList.insert(InsertPoint, MemModelInst);
3350
3351 //
3352 // Generate OpEntryPoint
3353 //
3354 for (auto EntryPoint : EntryPoints) {
3355 // Ops[0] = Execution Model
3356 // Ops[1] = EntryPoint ID
3357 // Ops[2] = Name (Literal String)
3358 // ...
3359 //
3360 // TODO: Do we need to consider Interface ID for forward references???
3361 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003362 const StringRef &name = EntryPoint.first->getName();
David Neto257c3892018-04-11 13:19:45 -04003363 Ops << MkNum(spv::ExecutionModelGLCompute) << MkId(EntryPoint.second)
3364 << MkString(name);
David Neto22f144c2017-06-12 14:26:21 -04003365
David Neto22f144c2017-06-12 14:26:21 -04003366 for (Value *Interface : EntryPointInterfaces) {
David Neto257c3892018-04-11 13:19:45 -04003367 Ops << MkId(VMap[Interface]);
David Neto22f144c2017-06-12 14:26:21 -04003368 }
3369
David Neto87846742018-04-11 17:36:22 -04003370 auto *EntryPointInst = new SPIRVInstruction(spv::OpEntryPoint, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003371 SPIRVInstList.insert(InsertPoint, EntryPointInst);
3372 }
3373
3374 for (auto EntryPoint : EntryPoints) {
3375 if (const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
3376 ->getMetadata("reqd_work_group_size")) {
3377
3378 if (!BuiltinDimVec.empty()) {
3379 llvm_unreachable(
3380 "Kernels should have consistent work group size definition");
3381 }
3382
3383 //
3384 // Generate OpExecutionMode
3385 //
3386
3387 // Ops[0] = Entry Point ID
3388 // Ops[1] = Execution Mode
3389 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
3390 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003391 Ops << MkId(EntryPoint.second) << MkNum(spv::ExecutionModeLocalSize);
David Neto22f144c2017-06-12 14:26:21 -04003392
3393 uint32_t XDim = static_cast<uint32_t>(
3394 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3395 uint32_t YDim = static_cast<uint32_t>(
3396 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3397 uint32_t ZDim = static_cast<uint32_t>(
3398 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3399
David Neto257c3892018-04-11 13:19:45 -04003400 Ops << MkNum(XDim) << MkNum(YDim) << MkNum(ZDim);
David Neto22f144c2017-06-12 14:26:21 -04003401
David Neto87846742018-04-11 17:36:22 -04003402 auto *ExecModeInst = new SPIRVInstruction(spv::OpExecutionMode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003403 SPIRVInstList.insert(InsertPoint, ExecModeInst);
3404 }
3405 }
3406
3407 //
3408 // Generate OpSource.
3409 //
3410 // Ops[0] = SourceLanguage ID
3411 // Ops[1] = Version (LiteralNum)
3412 //
3413 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003414 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(120);
David Neto22f144c2017-06-12 14:26:21 -04003415
David Neto87846742018-04-11 17:36:22 -04003416 auto *OpenSourceInst = new SPIRVInstruction(spv::OpSource, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003417 SPIRVInstList.insert(InsertPoint, OpenSourceInst);
3418
3419 if (!BuiltinDimVec.empty()) {
3420 //
3421 // Generate OpDecorates for x/y/z dimension.
3422 //
3423 // Ops[0] = Target ID
3424 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04003425 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04003426
3427 // X Dimension
3428 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003429 Ops << MkId(BuiltinDimVec[0]) << MkNum(spv::DecorationSpecId) << MkNum(0);
David Neto87846742018-04-11 17:36:22 -04003430 SPIRVInstList.insert(InsertPoint,
3431 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003432
3433 // Y Dimension
3434 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003435 Ops << MkId(BuiltinDimVec[1]) << MkNum(spv::DecorationSpecId) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04003436 SPIRVInstList.insert(InsertPoint,
3437 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003438
3439 // Z Dimension
3440 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003441 Ops << MkId(BuiltinDimVec[2]) << MkNum(spv::DecorationSpecId) << MkNum(2);
David Neto87846742018-04-11 17:36:22 -04003442 SPIRVInstList.insert(InsertPoint,
3443 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003444 }
3445}
3446
David Netob6e2e062018-04-25 10:32:06 -04003447void SPIRVProducerPass::GenerateEntryPointInitialStores() {
3448 // Work around a driver bug. Initializers on Private variables might not
3449 // work. So the start of the kernel should store the initializer value to the
3450 // variables. Yes, *every* entry point pays this cost if *any* entry point
3451 // uses this builtin. At this point I judge this to be an acceptable tradeoff
3452 // of complexity vs. runtime, for a broken driver.
alan-bakerb6b09dc2018-11-08 16:59:28 -05003453 // TODO(dneto): Remove this at some point once fixed drivers are widely
3454 // available.
David Netob6e2e062018-04-25 10:32:06 -04003455 if (WorkgroupSizeVarID) {
3456 assert(WorkgroupSizeValueID);
3457
3458 SPIRVOperandList Ops;
3459 Ops << MkId(WorkgroupSizeVarID) << MkId(WorkgroupSizeValueID);
3460
3461 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
3462 getSPIRVInstList().push_back(Inst);
3463 }
3464}
3465
David Neto22f144c2017-06-12 14:26:21 -04003466void SPIRVProducerPass::GenerateFuncBody(Function &F) {
3467 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3468 ValueMapType &VMap = getValueMap();
3469
David Netob6e2e062018-04-25 10:32:06 -04003470 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04003471
3472 for (BasicBlock &BB : F) {
3473 // Register BasicBlock to ValueMap.
3474 VMap[&BB] = nextID;
3475
3476 //
3477 // Generate OpLabel for Basic Block.
3478 //
3479 SPIRVOperandList Ops;
David Neto87846742018-04-11 17:36:22 -04003480 auto *Inst = new SPIRVInstruction(spv::OpLabel, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003481 SPIRVInstList.push_back(Inst);
3482
David Neto6dcd4712017-06-23 11:06:47 -04003483 // OpVariable instructions must come first.
3484 for (Instruction &I : BB) {
alan-baker5b86ed72019-02-15 08:26:50 -05003485 if (auto *alloca = dyn_cast<AllocaInst>(&I)) {
3486 // Allocating a pointer requires variable pointers.
3487 if (alloca->getAllocatedType()->isPointerTy()) {
3488 setVariablePointersCapabilities(alloca->getAllocatedType()->getPointerAddressSpace());
3489 }
David Neto6dcd4712017-06-23 11:06:47 -04003490 GenerateInstruction(I);
3491 }
3492 }
3493
David Neto22f144c2017-06-12 14:26:21 -04003494 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04003495 if (clspv::Option::HackInitializers()) {
3496 GenerateEntryPointInitialStores();
3497 }
David Neto22f144c2017-06-12 14:26:21 -04003498 }
3499
3500 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003501 if (!isa<AllocaInst>(I)) {
3502 GenerateInstruction(I);
3503 }
David Neto22f144c2017-06-12 14:26:21 -04003504 }
3505 }
3506}
3507
3508spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3509 const std::map<CmpInst::Predicate, spv::Op> Map = {
3510 {CmpInst::ICMP_EQ, spv::OpIEqual},
3511 {CmpInst::ICMP_NE, spv::OpINotEqual},
3512 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3513 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3514 {CmpInst::ICMP_ULT, spv::OpULessThan},
3515 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3516 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3517 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3518 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3519 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3520 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3521 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3522 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3523 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3524 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3525 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3526 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3527 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3528 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3529 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3530 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3531 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3532
3533 assert(0 != Map.count(I->getPredicate()));
3534
3535 return Map.at(I->getPredicate());
3536}
3537
3538spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3539 const std::map<unsigned, spv::Op> Map{
3540 {Instruction::Trunc, spv::OpUConvert},
3541 {Instruction::ZExt, spv::OpUConvert},
3542 {Instruction::SExt, spv::OpSConvert},
3543 {Instruction::FPToUI, spv::OpConvertFToU},
3544 {Instruction::FPToSI, spv::OpConvertFToS},
3545 {Instruction::UIToFP, spv::OpConvertUToF},
3546 {Instruction::SIToFP, spv::OpConvertSToF},
3547 {Instruction::FPTrunc, spv::OpFConvert},
3548 {Instruction::FPExt, spv::OpFConvert},
3549 {Instruction::BitCast, spv::OpBitcast}};
3550
3551 assert(0 != Map.count(I.getOpcode()));
3552
3553 return Map.at(I.getOpcode());
3554}
3555
3556spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
Kévin Petit24272b62018-10-18 19:16:12 +00003557 if (I.getType()->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003558 switch (I.getOpcode()) {
3559 default:
3560 break;
3561 case Instruction::Or:
3562 return spv::OpLogicalOr;
3563 case Instruction::And:
3564 return spv::OpLogicalAnd;
3565 case Instruction::Xor:
3566 return spv::OpLogicalNotEqual;
3567 }
3568 }
3569
alan-bakerb6b09dc2018-11-08 16:59:28 -05003570 const std::map<unsigned, spv::Op> Map{
David Neto22f144c2017-06-12 14:26:21 -04003571 {Instruction::Add, spv::OpIAdd},
3572 {Instruction::FAdd, spv::OpFAdd},
3573 {Instruction::Sub, spv::OpISub},
3574 {Instruction::FSub, spv::OpFSub},
3575 {Instruction::Mul, spv::OpIMul},
3576 {Instruction::FMul, spv::OpFMul},
3577 {Instruction::UDiv, spv::OpUDiv},
3578 {Instruction::SDiv, spv::OpSDiv},
3579 {Instruction::FDiv, spv::OpFDiv},
3580 {Instruction::URem, spv::OpUMod},
3581 {Instruction::SRem, spv::OpSRem},
3582 {Instruction::FRem, spv::OpFRem},
3583 {Instruction::Or, spv::OpBitwiseOr},
3584 {Instruction::Xor, spv::OpBitwiseXor},
3585 {Instruction::And, spv::OpBitwiseAnd},
3586 {Instruction::Shl, spv::OpShiftLeftLogical},
3587 {Instruction::LShr, spv::OpShiftRightLogical},
3588 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3589
3590 assert(0 != Map.count(I.getOpcode()));
3591
3592 return Map.at(I.getOpcode());
3593}
3594
3595void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
3596 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3597 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04003598 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
3599 LLVMContext &Context = I.getParent()->getParent()->getParent()->getContext();
3600
3601 // Register Instruction to ValueMap.
3602 if (0 == VMap[&I]) {
3603 VMap[&I] = nextID;
3604 }
3605
3606 switch (I.getOpcode()) {
3607 default: {
3608 if (Instruction::isCast(I.getOpcode())) {
3609 //
3610 // Generate SPIRV instructions for cast operators.
3611 //
3612
David Netod2de94a2017-08-28 17:27:47 -04003613 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003614 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003615 auto toI8 = Ty == Type::getInt8Ty(Context);
3616 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003617 // Handle zext, sext and uitofp with i1 type specially.
3618 if ((I.getOpcode() == Instruction::ZExt ||
3619 I.getOpcode() == Instruction::SExt ||
3620 I.getOpcode() == Instruction::UIToFP) &&
alan-bakerb6b09dc2018-11-08 16:59:28 -05003621 OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003622 //
3623 // Generate OpSelect.
3624 //
3625
3626 // Ops[0] = Result Type ID
3627 // Ops[1] = Condition ID
3628 // Ops[2] = True Constant ID
3629 // Ops[3] = False Constant ID
3630 SPIRVOperandList Ops;
3631
David Neto257c3892018-04-11 13:19:45 -04003632 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003633
David Neto22f144c2017-06-12 14:26:21 -04003634 uint32_t CondID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003635 Ops << MkId(CondID);
David Neto22f144c2017-06-12 14:26:21 -04003636
3637 uint32_t TrueID = 0;
3638 if (I.getOpcode() == Instruction::ZExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00003639 TrueID = VMap[ConstantInt::get(I.getType(), 1)];
David Neto22f144c2017-06-12 14:26:21 -04003640 } else if (I.getOpcode() == Instruction::SExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00003641 TrueID = VMap[ConstantInt::getSigned(I.getType(), -1)];
David Neto22f144c2017-06-12 14:26:21 -04003642 } else {
3643 TrueID = VMap[ConstantFP::get(Context, APFloat(1.0f))];
3644 }
David Neto257c3892018-04-11 13:19:45 -04003645 Ops << MkId(TrueID);
David Neto22f144c2017-06-12 14:26:21 -04003646
3647 uint32_t FalseID = 0;
3648 if (I.getOpcode() == Instruction::ZExt) {
3649 FalseID = VMap[Constant::getNullValue(I.getType())];
3650 } else if (I.getOpcode() == Instruction::SExt) {
3651 FalseID = VMap[Constant::getNullValue(I.getType())];
3652 } else {
3653 FalseID = VMap[ConstantFP::get(Context, APFloat(0.0f))];
3654 }
David Neto257c3892018-04-11 13:19:45 -04003655 Ops << MkId(FalseID);
David Neto22f144c2017-06-12 14:26:21 -04003656
David Neto87846742018-04-11 17:36:22 -04003657 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003658 SPIRVInstList.push_back(Inst);
alan-bakerb39c8262019-03-08 14:03:37 -05003659 } else if (!clspv::Option::Int8Support() &&
3660 I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
David Netod2de94a2017-08-28 17:27:47 -04003661 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3662 // 8 bits.
3663 // Before:
3664 // %result = trunc i32 %a to i8
3665 // After
3666 // %result = OpBitwiseAnd %uint %a %uint_255
3667
3668 SPIRVOperandList Ops;
3669
David Neto257c3892018-04-11 13:19:45 -04003670 Ops << MkId(lookupType(OpTy)) << MkId(VMap[I.getOperand(0)]);
David Netod2de94a2017-08-28 17:27:47 -04003671
3672 Type *UintTy = Type::getInt32Ty(Context);
3673 uint32_t MaskID = VMap[ConstantInt::get(UintTy, 255)];
David Neto257c3892018-04-11 13:19:45 -04003674 Ops << MkId(MaskID);
David Netod2de94a2017-08-28 17:27:47 -04003675
David Neto87846742018-04-11 17:36:22 -04003676 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Netod2de94a2017-08-28 17:27:47 -04003677 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003678 } else {
3679 // Ops[0] = Result Type ID
3680 // Ops[1] = Source Value ID
3681 SPIRVOperandList Ops;
3682
David Neto257c3892018-04-11 13:19:45 -04003683 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003684
David Neto87846742018-04-11 17:36:22 -04003685 auto *Inst = new SPIRVInstruction(GetSPIRVCastOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003686 SPIRVInstList.push_back(Inst);
3687 }
3688 } else if (isa<BinaryOperator>(I)) {
3689 //
3690 // Generate SPIRV instructions for binary operators.
3691 //
3692
3693 // Handle xor with i1 type specially.
3694 if (I.getOpcode() == Instruction::Xor &&
3695 I.getType() == Type::getInt1Ty(Context) &&
Kévin Petit24272b62018-10-18 19:16:12 +00003696 ((isa<ConstantInt>(I.getOperand(0)) &&
3697 !cast<ConstantInt>(I.getOperand(0))->isZero()) ||
3698 (isa<ConstantInt>(I.getOperand(1)) &&
3699 !cast<ConstantInt>(I.getOperand(1))->isZero()))) {
David Neto22f144c2017-06-12 14:26:21 -04003700 //
3701 // Generate OpLogicalNot.
3702 //
3703 // Ops[0] = Result Type ID
3704 // Ops[1] = Operand
3705 SPIRVOperandList Ops;
3706
David Neto257c3892018-04-11 13:19:45 -04003707 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003708
3709 Value *CondV = I.getOperand(0);
3710 if (isa<Constant>(I.getOperand(0))) {
3711 CondV = I.getOperand(1);
3712 }
David Neto257c3892018-04-11 13:19:45 -04003713 Ops << MkId(VMap[CondV]);
David Neto22f144c2017-06-12 14:26:21 -04003714
David Neto87846742018-04-11 17:36:22 -04003715 auto *Inst = new SPIRVInstruction(spv::OpLogicalNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003716 SPIRVInstList.push_back(Inst);
3717 } else {
3718 // Ops[0] = Result Type ID
3719 // Ops[1] = Operand 0
3720 // Ops[2] = Operand 1
3721 SPIRVOperandList Ops;
3722
David Neto257c3892018-04-11 13:19:45 -04003723 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
3724 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003725
David Neto87846742018-04-11 17:36:22 -04003726 auto *Inst =
3727 new SPIRVInstruction(GetSPIRVBinaryOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003728 SPIRVInstList.push_back(Inst);
3729 }
3730 } else {
3731 I.print(errs());
3732 llvm_unreachable("Unsupported instruction???");
3733 }
3734 break;
3735 }
3736 case Instruction::GetElementPtr: {
3737 auto &GlobalConstArgSet = getGlobalConstArgSet();
3738
3739 //
3740 // Generate OpAccessChain.
3741 //
3742 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
3743
3744 //
3745 // Generate OpAccessChain.
3746 //
3747
3748 // Ops[0] = Result Type ID
3749 // Ops[1] = Base ID
3750 // Ops[2] ... Ops[n] = Indexes ID
3751 SPIRVOperandList Ops;
3752
alan-bakerb6b09dc2018-11-08 16:59:28 -05003753 PointerType *ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04003754 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
3755 GlobalConstArgSet.count(GEP->getPointerOperand())) {
3756 // Use pointer type with private address space for global constant.
3757 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04003758 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04003759 }
David Neto257c3892018-04-11 13:19:45 -04003760
3761 Ops << MkId(lookupType(ResultType));
David Neto22f144c2017-06-12 14:26:21 -04003762
David Neto862b7d82018-06-14 18:48:37 -04003763 // Generate the base pointer.
3764 Ops << MkId(VMap[GEP->getPointerOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04003765
David Neto862b7d82018-06-14 18:48:37 -04003766 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04003767
3768 //
3769 // Follows below rules for gep.
3770 //
David Neto862b7d82018-06-14 18:48:37 -04003771 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
3772 // first index.
David Neto22f144c2017-06-12 14:26:21 -04003773 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
3774 // first index.
3775 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
3776 // use gep's first index.
3777 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
3778 // gep's first index.
3779 //
3780 spv::Op Opcode = spv::OpAccessChain;
3781 unsigned offset = 0;
3782 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04003783 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04003784 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04003785 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04003786 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04003787 }
David Neto862b7d82018-06-14 18:48:37 -04003788 } else {
David Neto22f144c2017-06-12 14:26:21 -04003789 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04003790 }
3791
3792 if (Opcode == spv::OpPtrAccessChain) {
David Neto1a1a0582017-07-07 12:01:44 -04003793 // Do we need to generate ArrayStride? Check against the GEP result type
3794 // rather than the pointer type of the base because when indexing into
3795 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
3796 // for something else in the SPIR-V.
3797 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
alan-baker5b86ed72019-02-15 08:26:50 -05003798 auto address_space = ResultType->getAddressSpace();
3799 setVariablePointersCapabilities(address_space);
3800 switch (GetStorageClass(address_space)) {
Alan Bakerfcda9482018-10-02 17:09:59 -04003801 case spv::StorageClassStorageBuffer:
3802 case spv::StorageClassUniform:
David Neto1a1a0582017-07-07 12:01:44 -04003803 // Save the need to generate an ArrayStride decoration. But defer
3804 // generation until later, so we only make one decoration.
David Neto85082642018-03-24 06:55:20 -07003805 getTypesNeedingArrayStride().insert(ResultType);
Alan Bakerfcda9482018-10-02 17:09:59 -04003806 break;
3807 default:
3808 break;
David Neto1a1a0582017-07-07 12:01:44 -04003809 }
David Neto22f144c2017-06-12 14:26:21 -04003810 }
3811
3812 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
David Neto257c3892018-04-11 13:19:45 -04003813 Ops << MkId(VMap[*II]);
David Neto22f144c2017-06-12 14:26:21 -04003814 }
3815
David Neto87846742018-04-11 17:36:22 -04003816 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003817 SPIRVInstList.push_back(Inst);
3818 break;
3819 }
3820 case Instruction::ExtractValue: {
3821 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3822 // Ops[0] = Result Type ID
3823 // Ops[1] = Composite ID
3824 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3825 SPIRVOperandList Ops;
3826
David Neto257c3892018-04-11 13:19:45 -04003827 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003828
3829 uint32_t CompositeID = VMap[EVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003830 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003831
3832 for (auto &Index : EVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003833 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003834 }
3835
David Neto87846742018-04-11 17:36:22 -04003836 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003837 SPIRVInstList.push_back(Inst);
3838 break;
3839 }
3840 case Instruction::InsertValue: {
3841 InsertValueInst *IVI = cast<InsertValueInst>(&I);
3842 // Ops[0] = Result Type ID
3843 // Ops[1] = Object ID
3844 // Ops[2] = Composite ID
3845 // Ops[3] ... Ops[n] = Indexes (Literal Number)
3846 SPIRVOperandList Ops;
3847
3848 uint32_t ResTyID = lookupType(I.getType());
David Neto257c3892018-04-11 13:19:45 -04003849 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04003850
3851 uint32_t ObjectID = VMap[IVI->getInsertedValueOperand()];
David Neto257c3892018-04-11 13:19:45 -04003852 Ops << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04003853
3854 uint32_t CompositeID = VMap[IVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003855 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003856
3857 for (auto &Index : IVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003858 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003859 }
3860
David Neto87846742018-04-11 17:36:22 -04003861 auto *Inst = new SPIRVInstruction(spv::OpCompositeInsert, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003862 SPIRVInstList.push_back(Inst);
3863 break;
3864 }
3865 case Instruction::Select: {
3866 //
3867 // Generate OpSelect.
3868 //
3869
3870 // Ops[0] = Result Type ID
3871 // Ops[1] = Condition ID
3872 // Ops[2] = True Constant ID
3873 // Ops[3] = False Constant ID
3874 SPIRVOperandList Ops;
3875
3876 // Find SPIRV instruction for parameter type.
3877 auto Ty = I.getType();
3878 if (Ty->isPointerTy()) {
3879 auto PointeeTy = Ty->getPointerElementType();
3880 if (PointeeTy->isStructTy() &&
3881 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
3882 Ty = PointeeTy;
alan-baker5b86ed72019-02-15 08:26:50 -05003883 } else {
3884 // Selecting between pointers requires variable pointers.
3885 setVariablePointersCapabilities(Ty->getPointerAddressSpace());
3886 if (!hasVariablePointers() && !selectFromSameObject(&I)) {
3887 setVariablePointers(true);
3888 }
David Neto22f144c2017-06-12 14:26:21 -04003889 }
3890 }
3891
David Neto257c3892018-04-11 13:19:45 -04003892 Ops << MkId(lookupType(Ty)) << MkId(VMap[I.getOperand(0)])
3893 << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003894
David Neto87846742018-04-11 17:36:22 -04003895 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003896 SPIRVInstList.push_back(Inst);
3897 break;
3898 }
3899 case Instruction::ExtractElement: {
3900 // Handle <4 x i8> type manually.
3901 Type *CompositeTy = I.getOperand(0)->getType();
3902 if (is4xi8vec(CompositeTy)) {
3903 //
3904 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
3905 // <4 x i8>.
3906 //
3907
3908 //
3909 // Generate OpShiftRightLogical
3910 //
3911 // Ops[0] = Result Type ID
3912 // Ops[1] = Operand 0
3913 // Ops[2] = Operand 1
3914 //
3915 SPIRVOperandList Ops;
3916
David Neto257c3892018-04-11 13:19:45 -04003917 Ops << MkId(lookupType(CompositeTy));
David Neto22f144c2017-06-12 14:26:21 -04003918
3919 uint32_t Op0ID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003920 Ops << MkId(Op0ID);
David Neto22f144c2017-06-12 14:26:21 -04003921
3922 uint32_t Op1ID = 0;
3923 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
3924 // Handle constant index.
3925 uint64_t Idx = CI->getZExtValue();
3926 Value *ShiftAmount =
3927 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3928 Op1ID = VMap[ShiftAmount];
3929 } else {
3930 // Handle variable index.
3931 SPIRVOperandList TmpOps;
3932
David Neto257c3892018-04-11 13:19:45 -04003933 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3934 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003935
3936 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003937 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003938
3939 Op1ID = nextID;
3940
David Neto87846742018-04-11 17:36:22 -04003941 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003942 SPIRVInstList.push_back(TmpInst);
3943 }
David Neto257c3892018-04-11 13:19:45 -04003944 Ops << MkId(Op1ID);
David Neto22f144c2017-06-12 14:26:21 -04003945
3946 uint32_t ShiftID = nextID;
3947
David Neto87846742018-04-11 17:36:22 -04003948 auto *Inst =
3949 new SPIRVInstruction(spv::OpShiftRightLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003950 SPIRVInstList.push_back(Inst);
3951
3952 //
3953 // Generate OpBitwiseAnd
3954 //
3955 // Ops[0] = Result Type ID
3956 // Ops[1] = Operand 0
3957 // Ops[2] = Operand 1
3958 //
3959 Ops.clear();
3960
David Neto257c3892018-04-11 13:19:45 -04003961 Ops << MkId(lookupType(CompositeTy)) << MkId(ShiftID);
David Neto22f144c2017-06-12 14:26:21 -04003962
3963 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
David Neto257c3892018-04-11 13:19:45 -04003964 Ops << MkId(VMap[CstFF]);
David Neto22f144c2017-06-12 14:26:21 -04003965
David Neto9b2d6252017-09-06 15:47:37 -04003966 // Reset mapping for this value to the result of the bitwise and.
3967 VMap[&I] = nextID;
3968
David Neto87846742018-04-11 17:36:22 -04003969 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003970 SPIRVInstList.push_back(Inst);
3971 break;
3972 }
3973
3974 // Ops[0] = Result Type ID
3975 // Ops[1] = Composite ID
3976 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3977 SPIRVOperandList Ops;
3978
David Neto257c3892018-04-11 13:19:45 -04003979 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003980
3981 spv::Op Opcode = spv::OpCompositeExtract;
3982 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
David Neto257c3892018-04-11 13:19:45 -04003983 Ops << MkNum(static_cast<uint32_t>(CI->getZExtValue()));
David Neto22f144c2017-06-12 14:26:21 -04003984 } else {
David Neto257c3892018-04-11 13:19:45 -04003985 Ops << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003986 Opcode = spv::OpVectorExtractDynamic;
3987 }
3988
David Neto87846742018-04-11 17:36:22 -04003989 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003990 SPIRVInstList.push_back(Inst);
3991 break;
3992 }
3993 case Instruction::InsertElement: {
3994 // Handle <4 x i8> type manually.
3995 Type *CompositeTy = I.getOperand(0)->getType();
3996 if (is4xi8vec(CompositeTy)) {
3997 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
3998 uint32_t CstFFID = VMap[CstFF];
3999
4000 uint32_t ShiftAmountID = 0;
4001 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
4002 // Handle constant index.
4003 uint64_t Idx = CI->getZExtValue();
4004 Value *ShiftAmount =
4005 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
4006 ShiftAmountID = VMap[ShiftAmount];
4007 } else {
4008 // Handle variable index.
4009 SPIRVOperandList TmpOps;
4010
David Neto257c3892018-04-11 13:19:45 -04004011 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
4012 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004013
4014 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04004015 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04004016
4017 ShiftAmountID = nextID;
4018
David Neto87846742018-04-11 17:36:22 -04004019 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004020 SPIRVInstList.push_back(TmpInst);
4021 }
4022
4023 //
4024 // Generate mask operations.
4025 //
4026
4027 // ShiftLeft mask according to index of insertelement.
4028 SPIRVOperandList Ops;
4029
David Neto257c3892018-04-11 13:19:45 -04004030 const uint32_t ResTyID = lookupType(CompositeTy);
4031 Ops << MkId(ResTyID) << MkId(CstFFID) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004032
4033 uint32_t MaskID = nextID;
4034
David Neto87846742018-04-11 17:36:22 -04004035 auto *Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004036 SPIRVInstList.push_back(Inst);
4037
4038 // Inverse mask.
4039 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004040 Ops << MkId(ResTyID) << MkId(MaskID);
David Neto22f144c2017-06-12 14:26:21 -04004041
4042 uint32_t InvMaskID = nextID;
4043
David Neto87846742018-04-11 17:36:22 -04004044 Inst = new SPIRVInstruction(spv::OpNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004045 SPIRVInstList.push_back(Inst);
4046
4047 // Apply mask.
4048 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004049 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(0)]) << MkId(InvMaskID);
David Neto22f144c2017-06-12 14:26:21 -04004050
4051 uint32_t OrgValID = nextID;
4052
David Neto87846742018-04-11 17:36:22 -04004053 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004054 SPIRVInstList.push_back(Inst);
4055
4056 // Create correct value according to index of insertelement.
4057 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05004058 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(1)])
4059 << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004060
4061 uint32_t InsertValID = nextID;
4062
David Neto87846742018-04-11 17:36:22 -04004063 Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004064 SPIRVInstList.push_back(Inst);
4065
4066 // Insert value to original value.
4067 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004068 Ops << MkId(ResTyID) << MkId(OrgValID) << MkId(InsertValID);
David Neto22f144c2017-06-12 14:26:21 -04004069
David Netoa394f392017-08-26 20:45:29 -04004070 VMap[&I] = nextID;
4071
David Neto87846742018-04-11 17:36:22 -04004072 Inst = new SPIRVInstruction(spv::OpBitwiseOr, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004073 SPIRVInstList.push_back(Inst);
4074
4075 break;
4076 }
4077
David Neto22f144c2017-06-12 14:26:21 -04004078 SPIRVOperandList Ops;
4079
James Priced26efea2018-06-09 23:28:32 +01004080 // Ops[0] = Result Type ID
4081 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004082
4083 spv::Op Opcode = spv::OpCompositeInsert;
4084 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04004085 const auto value = CI->getZExtValue();
4086 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01004087 // Ops[1] = Object ID
4088 // Ops[2] = Composite ID
4089 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004090 Ops << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(0)])
James Priced26efea2018-06-09 23:28:32 +01004091 << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004092 } else {
James Priced26efea2018-06-09 23:28:32 +01004093 // Ops[1] = Composite ID
4094 // Ops[2] = Object ID
4095 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004096 Ops << MkId(VMap[I.getOperand(0)]) << MkId(VMap[I.getOperand(1)])
James Priced26efea2018-06-09 23:28:32 +01004097 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004098 Opcode = spv::OpVectorInsertDynamic;
4099 }
4100
David Neto87846742018-04-11 17:36:22 -04004101 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004102 SPIRVInstList.push_back(Inst);
4103 break;
4104 }
4105 case Instruction::ShuffleVector: {
4106 // Ops[0] = Result Type ID
4107 // Ops[1] = Vector 1 ID
4108 // Ops[2] = Vector 2 ID
4109 // Ops[3] ... Ops[n] = Components (Literal Number)
4110 SPIRVOperandList Ops;
4111
David Neto257c3892018-04-11 13:19:45 -04004112 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4113 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004114
4115 uint64_t NumElements = 0;
4116 if (Constant *Cst = dyn_cast<Constant>(I.getOperand(2))) {
4117 NumElements = cast<VectorType>(Cst->getType())->getNumElements();
4118
4119 if (Cst->isNullValue()) {
4120 for (unsigned i = 0; i < NumElements; i++) {
David Neto257c3892018-04-11 13:19:45 -04004121 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04004122 }
4123 } else if (const ConstantDataSequential *CDS =
4124 dyn_cast<ConstantDataSequential>(Cst)) {
4125 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
4126 std::vector<uint32_t> LiteralNum;
David Neto257c3892018-04-11 13:19:45 -04004127 const auto value = CDS->getElementAsInteger(i);
4128 assert(value <= UINT32_MAX);
4129 Ops << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004130 }
4131 } else if (const ConstantVector *CV = dyn_cast<ConstantVector>(Cst)) {
4132 for (unsigned i = 0; i < CV->getNumOperands(); i++) {
4133 auto Op = CV->getOperand(i);
4134
4135 uint32_t literal = 0;
4136
4137 if (auto CI = dyn_cast<ConstantInt>(Op)) {
4138 literal = static_cast<uint32_t>(CI->getZExtValue());
4139 } else if (auto UI = dyn_cast<UndefValue>(Op)) {
4140 literal = 0xFFFFFFFFu;
4141 } else {
4142 Op->print(errs());
4143 llvm_unreachable("Unsupported element in ConstantVector!");
4144 }
4145
David Neto257c3892018-04-11 13:19:45 -04004146 Ops << MkNum(literal);
David Neto22f144c2017-06-12 14:26:21 -04004147 }
4148 } else {
4149 Cst->print(errs());
4150 llvm_unreachable("Unsupported constant mask in ShuffleVector!");
4151 }
4152 }
4153
David Neto87846742018-04-11 17:36:22 -04004154 auto *Inst = new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004155 SPIRVInstList.push_back(Inst);
4156 break;
4157 }
4158 case Instruction::ICmp:
4159 case Instruction::FCmp: {
4160 CmpInst *CmpI = cast<CmpInst>(&I);
4161
David Netod4ca2e62017-07-06 18:47:35 -04004162 // Pointer equality is invalid.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004163 Type *ArgTy = CmpI->getOperand(0)->getType();
David Netod4ca2e62017-07-06 18:47:35 -04004164 if (isa<PointerType>(ArgTy)) {
4165 CmpI->print(errs());
4166 std::string name = I.getParent()->getParent()->getName();
4167 errs()
4168 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4169 << "in function " << name << "\n";
4170 llvm_unreachable("Pointer equality check is invalid");
4171 break;
4172 }
4173
David Neto257c3892018-04-11 13:19:45 -04004174 // Ops[0] = Result Type ID
4175 // Ops[1] = Operand 1 ID
4176 // Ops[2] = Operand 2 ID
4177 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004178
David Neto257c3892018-04-11 13:19:45 -04004179 Ops << MkId(lookupType(CmpI->getType())) << MkId(VMap[CmpI->getOperand(0)])
4180 << MkId(VMap[CmpI->getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004181
4182 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
David Neto87846742018-04-11 17:36:22 -04004183 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004184 SPIRVInstList.push_back(Inst);
4185 break;
4186 }
4187 case Instruction::Br: {
4188 // Branch instrucion is deferred because it needs label's ID. Record slot's
4189 // location on SPIRVInstructionList.
4190 DeferredInsts.push_back(
4191 std::make_tuple(&I, --SPIRVInstList.end(), 0 /* No id */));
4192 break;
4193 }
4194 case Instruction::Switch: {
4195 I.print(errs());
4196 llvm_unreachable("Unsupported instruction???");
4197 break;
4198 }
4199 case Instruction::IndirectBr: {
4200 I.print(errs());
4201 llvm_unreachable("Unsupported instruction???");
4202 break;
4203 }
4204 case Instruction::PHI: {
4205 // Branch instrucion is deferred because it needs label's ID. Record slot's
4206 // location on SPIRVInstructionList.
4207 DeferredInsts.push_back(
4208 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4209 break;
4210 }
4211 case Instruction::Alloca: {
4212 //
4213 // Generate OpVariable.
4214 //
4215 // Ops[0] : Result Type ID
4216 // Ops[1] : Storage Class
4217 SPIRVOperandList Ops;
4218
David Neto257c3892018-04-11 13:19:45 -04004219 Ops << MkId(lookupType(I.getType())) << MkNum(spv::StorageClassFunction);
David Neto22f144c2017-06-12 14:26:21 -04004220
David Neto87846742018-04-11 17:36:22 -04004221 auto *Inst = new SPIRVInstruction(spv::OpVariable, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004222 SPIRVInstList.push_back(Inst);
4223 break;
4224 }
4225 case Instruction::Load: {
4226 LoadInst *LD = cast<LoadInst>(&I);
4227 //
4228 // Generate OpLoad.
4229 //
alan-baker5b86ed72019-02-15 08:26:50 -05004230
4231 if (LD->getType()->isPointerTy()) {
4232 // Loading a pointer requires variable pointers.
4233 setVariablePointersCapabilities(LD->getType()->getPointerAddressSpace());
4234 }
David Neto22f144c2017-06-12 14:26:21 -04004235
David Neto0a2f98d2017-09-15 19:38:40 -04004236 uint32_t ResTyID = lookupType(LD->getType());
David Netoa60b00b2017-09-15 16:34:09 -04004237 uint32_t PointerID = VMap[LD->getPointerOperand()];
4238
4239 // This is a hack to work around what looks like a driver bug.
4240 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004241 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4242 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004243 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004244 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004245 // Generate a bitwise-and of the original value with itself.
4246 // We should have been able to get away with just an OpCopyObject,
4247 // but we need something more complex to get past certain driver bugs.
4248 // This is ridiculous, but necessary.
4249 // TODO(dneto): Revisit this once drivers fix their bugs.
4250
4251 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004252 Ops << MkId(ResTyID) << MkId(WorkgroupSizeValueID)
4253 << MkId(WorkgroupSizeValueID);
David Neto0a2f98d2017-09-15 19:38:40 -04004254
David Neto87846742018-04-11 17:36:22 -04004255 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto0a2f98d2017-09-15 19:38:40 -04004256 SPIRVInstList.push_back(Inst);
David Netoa60b00b2017-09-15 16:34:09 -04004257 break;
4258 }
4259
4260 // This is the normal path. Generate a load.
4261
David Neto22f144c2017-06-12 14:26:21 -04004262 // Ops[0] = Result Type ID
4263 // Ops[1] = Pointer ID
4264 // Ops[2] ... Ops[n] = Optional Memory Access
4265 //
4266 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004267
David Neto22f144c2017-06-12 14:26:21 -04004268 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004269 Ops << MkId(ResTyID) << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04004270
David Neto87846742018-04-11 17:36:22 -04004271 auto *Inst = new SPIRVInstruction(spv::OpLoad, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004272 SPIRVInstList.push_back(Inst);
4273 break;
4274 }
4275 case Instruction::Store: {
4276 StoreInst *ST = cast<StoreInst>(&I);
4277 //
4278 // Generate OpStore.
4279 //
4280
alan-baker5b86ed72019-02-15 08:26:50 -05004281 if (ST->getValueOperand()->getType()->isPointerTy()) {
4282 // Storing a pointer requires variable pointers.
4283 setVariablePointersCapabilities(
4284 ST->getValueOperand()->getType()->getPointerAddressSpace());
4285 }
4286
David Neto22f144c2017-06-12 14:26:21 -04004287 // Ops[0] = Pointer ID
4288 // Ops[1] = Object ID
4289 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4290 //
4291 // TODO: Do we need to implement Optional Memory Access???
David Neto257c3892018-04-11 13:19:45 -04004292 SPIRVOperandList Ops;
4293 Ops << MkId(VMap[ST->getPointerOperand()])
4294 << MkId(VMap[ST->getValueOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004295
David Neto87846742018-04-11 17:36:22 -04004296 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004297 SPIRVInstList.push_back(Inst);
4298 break;
4299 }
4300 case Instruction::AtomicCmpXchg: {
4301 I.print(errs());
4302 llvm_unreachable("Unsupported instruction???");
4303 break;
4304 }
4305 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004306 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4307
4308 spv::Op opcode;
4309
4310 switch (AtomicRMW->getOperation()) {
4311 default:
4312 I.print(errs());
4313 llvm_unreachable("Unsupported instruction???");
4314 case llvm::AtomicRMWInst::Add:
4315 opcode = spv::OpAtomicIAdd;
4316 break;
4317 case llvm::AtomicRMWInst::Sub:
4318 opcode = spv::OpAtomicISub;
4319 break;
4320 case llvm::AtomicRMWInst::Xchg:
4321 opcode = spv::OpAtomicExchange;
4322 break;
4323 case llvm::AtomicRMWInst::Min:
4324 opcode = spv::OpAtomicSMin;
4325 break;
4326 case llvm::AtomicRMWInst::Max:
4327 opcode = spv::OpAtomicSMax;
4328 break;
4329 case llvm::AtomicRMWInst::UMin:
4330 opcode = spv::OpAtomicUMin;
4331 break;
4332 case llvm::AtomicRMWInst::UMax:
4333 opcode = spv::OpAtomicUMax;
4334 break;
4335 case llvm::AtomicRMWInst::And:
4336 opcode = spv::OpAtomicAnd;
4337 break;
4338 case llvm::AtomicRMWInst::Or:
4339 opcode = spv::OpAtomicOr;
4340 break;
4341 case llvm::AtomicRMWInst::Xor:
4342 opcode = spv::OpAtomicXor;
4343 break;
4344 }
4345
4346 //
4347 // Generate OpAtomic*.
4348 //
4349 SPIRVOperandList Ops;
4350
David Neto257c3892018-04-11 13:19:45 -04004351 Ops << MkId(lookupType(I.getType()))
4352 << MkId(VMap[AtomicRMW->getPointerOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004353
4354 auto IntTy = Type::getInt32Ty(I.getContext());
Neil Henning39672102017-09-29 14:33:13 +01004355 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
David Neto257c3892018-04-11 13:19:45 -04004356 Ops << MkId(VMap[ConstantScopeDevice]);
Neil Henning39672102017-09-29 14:33:13 +01004357
4358 const auto ConstantMemorySemantics = ConstantInt::get(
4359 IntTy, spv::MemorySemanticsUniformMemoryMask |
4360 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto257c3892018-04-11 13:19:45 -04004361 Ops << MkId(VMap[ConstantMemorySemantics]);
Neil Henning39672102017-09-29 14:33:13 +01004362
David Neto257c3892018-04-11 13:19:45 -04004363 Ops << MkId(VMap[AtomicRMW->getValOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004364
4365 VMap[&I] = nextID;
4366
David Neto87846742018-04-11 17:36:22 -04004367 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
Neil Henning39672102017-09-29 14:33:13 +01004368 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004369 break;
4370 }
4371 case Instruction::Fence: {
4372 I.print(errs());
4373 llvm_unreachable("Unsupported instruction???");
4374 break;
4375 }
4376 case Instruction::Call: {
4377 CallInst *Call = dyn_cast<CallInst>(&I);
4378 Function *Callee = Call->getCalledFunction();
4379
Alan Baker202c8c72018-08-13 13:47:44 -04004380 if (Callee->getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004381 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
4382 // Generate an OpLoad
4383 SPIRVOperandList Ops;
4384 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004385
David Neto862b7d82018-06-14 18:48:37 -04004386 Ops << MkId(lookupType(Call->getType()->getPointerElementType()))
4387 << MkId(ResourceVarDeferredLoadCalls[Call]);
4388
4389 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
4390 SPIRVInstList.push_back(Inst);
4391 VMap[Call] = load_id;
4392 break;
4393
4394 } else {
4395 // This maps to an OpVariable we've already generated.
4396 // No code is generated for the call.
4397 }
4398 break;
alan-bakerb6b09dc2018-11-08 16:59:28 -05004399 } else if (Callee->getName().startswith(
4400 clspv::WorkgroupAccessorFunction())) {
Alan Baker202c8c72018-08-13 13:47:44 -04004401 // Don't codegen an instruction here, but instead map this call directly
4402 // to the workgroup variable id.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004403 int spec_id = static_cast<int>(
4404 cast<ConstantInt>(Call->getOperand(0))->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04004405 const auto &info = LocalSpecIdInfoMap[spec_id];
4406 VMap[Call] = info.variable_id;
4407 break;
David Neto862b7d82018-06-14 18:48:37 -04004408 }
4409
4410 // Sampler initializers become a load of the corresponding sampler.
4411
4412 if (Callee->getName().equals("clspv.sampler.var.literal")) {
4413 // Map this to a load from the variable.
4414 const auto index_into_sampler_map =
4415 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4416
4417 // Generate an OpLoad
David Neto22f144c2017-06-12 14:26:21 -04004418 SPIRVOperandList Ops;
David Neto862b7d82018-06-14 18:48:37 -04004419 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004420
David Neto257c3892018-04-11 13:19:45 -04004421 Ops << MkId(lookupType(SamplerTy->getPointerElementType()))
alan-bakerb6b09dc2018-11-08 16:59:28 -05004422 << MkId(SamplerMapIndexToIDMap[static_cast<unsigned>(
4423 index_into_sampler_map)]);
David Neto22f144c2017-06-12 14:26:21 -04004424
David Neto862b7d82018-06-14 18:48:37 -04004425 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004426 SPIRVInstList.push_back(Inst);
David Neto862b7d82018-06-14 18:48:37 -04004427 VMap[Call] = load_id;
David Neto22f144c2017-06-12 14:26:21 -04004428 break;
4429 }
4430
Kévin Petit349c9502019-03-28 17:24:14 +00004431 // Handle SPIR-V intrinsics
4432 spv::Op opcode = StringSwitch<spv::Op>(Callee->getName())
Kévin Petit349c9502019-03-28 17:24:14 +00004433 .Case("spirv.atomic_add", spv::OpAtomicIAdd)
4434 .Case("spirv.atomic_sub", spv::OpAtomicISub)
4435 .Case("spirv.atomic_exchange", spv::OpAtomicExchange)
4436 .Case("spirv.atomic_inc", spv::OpAtomicIIncrement)
4437 .Case("spirv.atomic_dec", spv::OpAtomicIDecrement)
4438 .Case("spirv.atomic_compare_exchange", spv::OpAtomicCompareExchange)
4439 .Case("spirv.atomic_umin", spv::OpAtomicUMin)
4440 .Case("spirv.atomic_smin", spv::OpAtomicSMin)
4441 .Case("spirv.atomic_umax", spv::OpAtomicUMax)
4442 .Case("spirv.atomic_smax", spv::OpAtomicSMax)
4443 .Case("spirv.atomic_and", spv::OpAtomicAnd)
4444 .Case("spirv.atomic_or", spv::OpAtomicOr)
4445 .Case("spirv.atomic_xor", spv::OpAtomicXor)
4446 .Case("__spirv_control_barrier", spv::OpControlBarrier)
4447 .Case("__spirv_memory_barrier", spv::OpMemoryBarrier)
Kévin Petitfd6c24f2019-04-03 15:30:59 +01004448 .StartsWith("spirv.store_null", spv::OpStore)
Kévin Petit349c9502019-03-28 17:24:14 +00004449 .StartsWith("__spirv_isinf", spv::OpIsInf)
4450 .StartsWith("__spirv_isnan", spv::OpIsNan)
4451 .StartsWith("__spirv_allDv", spv::OpAll)
4452 .StartsWith("__spirv_anyDv", spv::OpAny)
4453 .Default(spv::OpNop);
David Neto22f144c2017-06-12 14:26:21 -04004454
Kévin Petit617a76d2019-04-04 13:54:16 +01004455 // If the switch above didn't have an entry maybe the intrinsic
4456 // is using the name mangling logic.
4457 bool usesMangler = false;
4458 if (opcode == spv::OpNop) {
4459 if (Callee->getName().startswith(clspv::SPIRVOpIntrinsicFunction())) {
4460 auto OpCst = cast<ConstantInt>(Call->getOperand(0));
4461 opcode = static_cast<spv::Op>(OpCst->getZExtValue());
4462 usesMangler = true;
4463 }
4464 }
4465
Kévin Petit349c9502019-03-28 17:24:14 +00004466 if (opcode != spv::OpNop) {
4467
David Neto22f144c2017-06-12 14:26:21 -04004468 SPIRVOperandList Ops;
4469
Kévin Petit349c9502019-03-28 17:24:14 +00004470 if (!I.getType()->isVoidTy()) {
4471 Ops << MkId(lookupType(I.getType()));
4472 }
David Neto22f144c2017-06-12 14:26:21 -04004473
Kévin Petit617a76d2019-04-04 13:54:16 +01004474 unsigned firstOperand = usesMangler ? 1 : 0;
4475 for (unsigned i = firstOperand; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004476 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004477 }
4478
Kévin Petit349c9502019-03-28 17:24:14 +00004479 if (!I.getType()->isVoidTy()) {
4480 VMap[&I] = nextID;
Kévin Petit8a560882019-03-21 15:24:34 +00004481 }
4482
Kévin Petit349c9502019-03-28 17:24:14 +00004483 SPIRVInstruction *Inst;
4484 if (!I.getType()->isVoidTy()) {
4485 Inst = new SPIRVInstruction(opcode, nextID++, Ops);
4486 } else {
4487 Inst = new SPIRVInstruction(opcode, Ops);
4488 }
Kévin Petit8a560882019-03-21 15:24:34 +00004489 SPIRVInstList.push_back(Inst);
4490 break;
4491 }
4492
David Neto22f144c2017-06-12 14:26:21 -04004493 if (Callee->getName().startswith("_Z3dot")) {
4494 // If the argument is a vector type, generate OpDot
4495 if (Call->getArgOperand(0)->getType()->isVectorTy()) {
4496 //
4497 // Generate OpDot.
4498 //
4499 SPIRVOperandList Ops;
4500
David Neto257c3892018-04-11 13:19:45 -04004501 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004502
4503 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004504 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004505 }
4506
4507 VMap[&I] = nextID;
4508
David Neto87846742018-04-11 17:36:22 -04004509 auto *Inst = new SPIRVInstruction(spv::OpDot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004510 SPIRVInstList.push_back(Inst);
4511 } else {
4512 //
4513 // Generate OpFMul.
4514 //
4515 SPIRVOperandList Ops;
4516
David Neto257c3892018-04-11 13:19:45 -04004517 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004518
4519 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004520 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004521 }
4522
4523 VMap[&I] = nextID;
4524
David Neto87846742018-04-11 17:36:22 -04004525 auto *Inst = new SPIRVInstruction(spv::OpFMul, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004526 SPIRVInstList.push_back(Inst);
4527 }
4528 break;
4529 }
4530
David Neto8505ebf2017-10-13 18:50:50 -04004531 if (Callee->getName().startswith("_Z4fmod")) {
4532 // OpenCL fmod(x,y) is x - y * trunc(x/y)
4533 // The sign for a non-zero result is taken from x.
4534 // (Try an example.)
4535 // So translate to OpFRem
4536
4537 SPIRVOperandList Ops;
4538
David Neto257c3892018-04-11 13:19:45 -04004539 Ops << MkId(lookupType(I.getType()));
David Neto8505ebf2017-10-13 18:50:50 -04004540
4541 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004542 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto8505ebf2017-10-13 18:50:50 -04004543 }
4544
4545 VMap[&I] = nextID;
4546
David Neto87846742018-04-11 17:36:22 -04004547 auto *Inst = new SPIRVInstruction(spv::OpFRem, nextID++, Ops);
David Neto8505ebf2017-10-13 18:50:50 -04004548 SPIRVInstList.push_back(Inst);
4549 break;
4550 }
4551
David Neto22f144c2017-06-12 14:26:21 -04004552 // spirv.copy_memory.* intrinsics become OpMemoryMemory's.
4553 if (Callee->getName().startswith("spirv.copy_memory")) {
4554 //
4555 // Generate OpCopyMemory.
4556 //
4557
4558 // Ops[0] = Dst ID
4559 // Ops[1] = Src ID
4560 // Ops[2] = Memory Access
4561 // Ops[3] = Alignment
4562
4563 auto IsVolatile =
4564 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
4565
4566 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
4567 : spv::MemoryAccessMaskNone;
4568
4569 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
4570
4571 auto Alignment =
4572 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4573
David Neto257c3892018-04-11 13:19:45 -04004574 SPIRVOperandList Ops;
4575 Ops << MkId(VMap[Call->getArgOperand(0)])
4576 << MkId(VMap[Call->getArgOperand(1)]) << MkNum(MemoryAccess)
4577 << MkNum(static_cast<uint32_t>(Alignment));
David Neto22f144c2017-06-12 14:26:21 -04004578
David Neto87846742018-04-11 17:36:22 -04004579 auto *Inst = new SPIRVInstruction(spv::OpCopyMemory, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004580
4581 SPIRVInstList.push_back(Inst);
4582
4583 break;
4584 }
4585
David Neto22f144c2017-06-12 14:26:21 -04004586 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
4587 // Additionally, OpTypeSampledImage is generated.
4588 if (Callee->getName().equals(
4589 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
4590 Callee->getName().equals(
4591 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
4592 //
4593 // Generate OpSampledImage.
4594 //
4595 // Ops[0] = Result Type ID
4596 // Ops[1] = Image ID
4597 // Ops[2] = Sampler ID
4598 //
4599 SPIRVOperandList Ops;
4600
4601 Value *Image = Call->getArgOperand(0);
4602 Value *Sampler = Call->getArgOperand(1);
4603 Value *Coordinate = Call->getArgOperand(2);
4604
4605 TypeMapType &OpImageTypeMap = getImageTypeMap();
4606 Type *ImageTy = Image->getType()->getPointerElementType();
4607 uint32_t ImageTyID = OpImageTypeMap[ImageTy];
David Neto22f144c2017-06-12 14:26:21 -04004608 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004609 uint32_t SamplerID = VMap[Sampler];
David Neto257c3892018-04-11 13:19:45 -04004610
4611 Ops << MkId(ImageTyID) << MkId(ImageID) << MkId(SamplerID);
David Neto22f144c2017-06-12 14:26:21 -04004612
4613 uint32_t SampledImageID = nextID;
4614
David Neto87846742018-04-11 17:36:22 -04004615 auto *Inst = new SPIRVInstruction(spv::OpSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004616 SPIRVInstList.push_back(Inst);
4617
4618 //
4619 // Generate OpImageSampleExplicitLod.
4620 //
4621 // Ops[0] = Result Type ID
4622 // Ops[1] = Sampled Image ID
4623 // Ops[2] = Coordinate ID
4624 // Ops[3] = Image Operands Type ID
4625 // Ops[4] ... Ops[n] = Operands ID
4626 //
4627 Ops.clear();
4628
David Neto257c3892018-04-11 13:19:45 -04004629 Ops << MkId(lookupType(Call->getType())) << MkId(SampledImageID)
4630 << MkId(VMap[Coordinate]) << MkNum(spv::ImageOperandsLodMask);
David Neto22f144c2017-06-12 14:26:21 -04004631
4632 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
David Neto257c3892018-04-11 13:19:45 -04004633 Ops << MkId(VMap[CstFP0]);
David Neto22f144c2017-06-12 14:26:21 -04004634
4635 VMap[&I] = nextID;
4636
David Neto87846742018-04-11 17:36:22 -04004637 Inst = new SPIRVInstruction(spv::OpImageSampleExplicitLod, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004638 SPIRVInstList.push_back(Inst);
4639 break;
4640 }
4641
4642 // write_imagef is mapped to OpImageWrite.
4643 if (Callee->getName().equals(
4644 "_Z12write_imagef14ocl_image2d_woDv2_iDv4_f") ||
4645 Callee->getName().equals(
4646 "_Z12write_imagef14ocl_image3d_woDv4_iDv4_f")) {
4647 //
4648 // Generate OpImageWrite.
4649 //
4650 // Ops[0] = Image ID
4651 // Ops[1] = Coordinate ID
4652 // Ops[2] = Texel ID
4653 // Ops[3] = (Optional) Image Operands Type (Literal Number)
4654 // Ops[4] ... Ops[n] = (Optional) Operands ID
4655 //
4656 SPIRVOperandList Ops;
4657
4658 Value *Image = Call->getArgOperand(0);
4659 Value *Coordinate = Call->getArgOperand(1);
4660 Value *Texel = Call->getArgOperand(2);
4661
4662 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004663 uint32_t CoordinateID = VMap[Coordinate];
David Neto22f144c2017-06-12 14:26:21 -04004664 uint32_t TexelID = VMap[Texel];
David Neto257c3892018-04-11 13:19:45 -04004665 Ops << MkId(ImageID) << MkId(CoordinateID) << MkId(TexelID);
David Neto22f144c2017-06-12 14:26:21 -04004666
David Neto87846742018-04-11 17:36:22 -04004667 auto *Inst = new SPIRVInstruction(spv::OpImageWrite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004668 SPIRVInstList.push_back(Inst);
4669 break;
4670 }
4671
David Neto5c22a252018-03-15 16:07:41 -04004672 // get_image_width is mapped to OpImageQuerySize
4673 if (Callee->getName().equals("_Z15get_image_width14ocl_image2d_ro") ||
4674 Callee->getName().equals("_Z15get_image_width14ocl_image2d_wo") ||
4675 Callee->getName().equals("_Z16get_image_height14ocl_image2d_ro") ||
4676 Callee->getName().equals("_Z16get_image_height14ocl_image2d_wo")) {
4677 //
4678 // Generate OpImageQuerySize, then pull out the right component.
4679 // Assume 2D image for now.
4680 //
4681 // Ops[0] = Image ID
4682 //
4683 // %sizes = OpImageQuerySizes %uint2 %im
4684 // %result = OpCompositeExtract %uint %sizes 0-or-1
4685 SPIRVOperandList Ops;
4686
4687 // Implement:
4688 // %sizes = OpImageQuerySizes %uint2 %im
4689 uint32_t SizesTypeID =
4690 TypeMap[VectorType::get(Type::getInt32Ty(Context), 2)];
David Neto5c22a252018-03-15 16:07:41 -04004691 Value *Image = Call->getArgOperand(0);
4692 uint32_t ImageID = VMap[Image];
David Neto257c3892018-04-11 13:19:45 -04004693 Ops << MkId(SizesTypeID) << MkId(ImageID);
David Neto5c22a252018-03-15 16:07:41 -04004694
4695 uint32_t SizesID = nextID++;
David Neto87846742018-04-11 17:36:22 -04004696 auto *QueryInst =
4697 new SPIRVInstruction(spv::OpImageQuerySize, SizesID, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004698 SPIRVInstList.push_back(QueryInst);
4699
4700 // Reset value map entry since we generated an intermediate instruction.
4701 VMap[&I] = nextID;
4702
4703 // Implement:
4704 // %result = OpCompositeExtract %uint %sizes 0-or-1
4705 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004706 Ops << MkId(TypeMap[I.getType()]) << MkId(SizesID);
David Neto5c22a252018-03-15 16:07:41 -04004707
4708 uint32_t component = Callee->getName().contains("height") ? 1 : 0;
David Neto257c3892018-04-11 13:19:45 -04004709 Ops << MkNum(component);
David Neto5c22a252018-03-15 16:07:41 -04004710
David Neto87846742018-04-11 17:36:22 -04004711 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004712 SPIRVInstList.push_back(Inst);
4713 break;
4714 }
4715
David Neto22f144c2017-06-12 14:26:21 -04004716 // Call instrucion is deferred because it needs function's ID. Record
4717 // slot's location on SPIRVInstructionList.
4718 DeferredInsts.push_back(
4719 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4720
David Neto3fbb4072017-10-16 11:28:14 -04004721 // Check whether the implementation of this call uses an extended
4722 // instruction plus one more value-producing instruction. If so, then
4723 // reserve the id for the extra value-producing slot.
4724 glsl::ExtInst EInst = getIndirectExtInstEnum(Callee->getName());
4725 if (EInst != kGlslExtInstBad) {
4726 // Reserve a spot for the extra value.
David Neto4d02a532017-09-17 12:57:44 -04004727 // Increase nextID.
David Neto22f144c2017-06-12 14:26:21 -04004728 VMap[&I] = nextID;
4729 nextID++;
4730 }
4731 break;
4732 }
4733 case Instruction::Ret: {
4734 unsigned NumOps = I.getNumOperands();
4735 if (NumOps == 0) {
4736 //
4737 // Generate OpReturn.
4738 //
David Neto87846742018-04-11 17:36:22 -04004739 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpReturn, {}));
David Neto22f144c2017-06-12 14:26:21 -04004740 } else {
4741 //
4742 // Generate OpReturnValue.
4743 //
4744
4745 // Ops[0] = Return Value ID
4746 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004747
4748 Ops << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004749
David Neto87846742018-04-11 17:36:22 -04004750 auto *Inst = new SPIRVInstruction(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004751 SPIRVInstList.push_back(Inst);
4752 break;
4753 }
4754 break;
4755 }
4756 }
4757}
4758
4759void SPIRVProducerPass::GenerateFuncEpilogue() {
4760 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4761
4762 //
4763 // Generate OpFunctionEnd
4764 //
4765
David Neto87846742018-04-11 17:36:22 -04004766 auto *Inst = new SPIRVInstruction(spv::OpFunctionEnd, {});
David Neto22f144c2017-06-12 14:26:21 -04004767 SPIRVInstList.push_back(Inst);
4768}
4769
4770bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
alan-bakerb39c8262019-03-08 14:03:37 -05004771 // Don't specialize <4 x i8> if i8 is generally supported.
4772 if (clspv::Option::Int8Support())
4773 return false;
4774
David Neto22f144c2017-06-12 14:26:21 -04004775 LLVMContext &Context = Ty->getContext();
4776 if (Ty->isVectorTy()) {
4777 if (Ty->getVectorElementType() == Type::getInt8Ty(Context) &&
4778 Ty->getVectorNumElements() == 4) {
4779 return true;
4780 }
4781 }
4782
4783 return false;
4784}
4785
David Neto257c3892018-04-11 13:19:45 -04004786uint32_t SPIRVProducerPass::GetI32Zero() {
4787 if (0 == constant_i32_zero_id_) {
4788 llvm_unreachable("Requesting a 32-bit integer constant but it is not "
4789 "defined in the SPIR-V module");
4790 }
4791 return constant_i32_zero_id_;
4792}
4793
David Neto22f144c2017-06-12 14:26:21 -04004794void SPIRVProducerPass::HandleDeferredInstruction() {
4795 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4796 ValueMapType &VMap = getValueMap();
4797 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4798
4799 for (auto DeferredInst = DeferredInsts.rbegin();
4800 DeferredInst != DeferredInsts.rend(); ++DeferredInst) {
4801 Value *Inst = std::get<0>(*DeferredInst);
4802 SPIRVInstructionList::iterator InsertPoint = ++std::get<1>(*DeferredInst);
4803 if (InsertPoint != SPIRVInstList.end()) {
4804 while ((*InsertPoint)->getOpcode() == spv::OpPhi) {
4805 ++InsertPoint;
4806 }
4807 }
4808
4809 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
4810 // Check whether basic block, which has this branch instruction, is loop
4811 // header or not. If it is loop header, generate OpLoopMerge and
4812 // OpBranchConditional.
4813 Function *Func = Br->getParent()->getParent();
4814 DominatorTree &DT =
4815 getAnalysis<DominatorTreeWrapperPass>(*Func).getDomTree();
4816 const LoopInfo &LI =
4817 getAnalysis<LoopInfoWrapperPass>(*Func).getLoopInfo();
4818
4819 BasicBlock *BrBB = Br->getParent();
4820 if (LI.isLoopHeader(BrBB)) {
4821 Value *ContinueBB = nullptr;
4822 Value *MergeBB = nullptr;
4823
4824 Loop *L = LI.getLoopFor(BrBB);
4825 MergeBB = L->getExitBlock();
4826 if (!MergeBB) {
4827 // StructurizeCFG pass converts CFG into triangle shape and the cfg
4828 // has regions with single entry/exit. As a result, loop should not
4829 // have multiple exits.
4830 llvm_unreachable("Loop has multiple exits???");
4831 }
4832
4833 if (L->isLoopLatch(BrBB)) {
4834 ContinueBB = BrBB;
4835 } else {
4836 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
4837 // block.
4838 BasicBlock *Header = L->getHeader();
4839 BasicBlock *Latch = L->getLoopLatch();
4840 for (BasicBlock *BB : L->blocks()) {
4841 if (BB == Header) {
4842 continue;
4843 }
4844
4845 // Check whether block dominates block with back-edge.
4846 if (DT.dominates(BB, Latch)) {
4847 ContinueBB = BB;
4848 }
4849 }
4850
4851 if (!ContinueBB) {
4852 llvm_unreachable("Wrong continue block from loop");
4853 }
4854 }
4855
4856 //
4857 // Generate OpLoopMerge.
4858 //
4859 // Ops[0] = Merge Block ID
4860 // Ops[1] = Continue Target ID
4861 // Ops[2] = Selection Control
4862 SPIRVOperandList Ops;
4863
4864 // StructurizeCFG pass already manipulated CFG. Just use false block of
4865 // branch instruction as merge block.
4866 uint32_t MergeBBID = VMap[MergeBB];
David Neto22f144c2017-06-12 14:26:21 -04004867 uint32_t ContinueBBID = VMap[ContinueBB];
David Neto257c3892018-04-11 13:19:45 -04004868 Ops << MkId(MergeBBID) << MkId(ContinueBBID)
4869 << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004870
David Neto87846742018-04-11 17:36:22 -04004871 auto *MergeInst = new SPIRVInstruction(spv::OpLoopMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004872 SPIRVInstList.insert(InsertPoint, MergeInst);
4873
4874 } else if (Br->isConditional()) {
4875 bool HasBackEdge = false;
4876
4877 for (unsigned i = 0; i < Br->getNumSuccessors(); i++) {
4878 if (LI.isLoopHeader(Br->getSuccessor(i))) {
4879 HasBackEdge = true;
4880 }
4881 }
4882 if (!HasBackEdge) {
4883 //
4884 // Generate OpSelectionMerge.
4885 //
4886 // Ops[0] = Merge Block ID
4887 // Ops[1] = Selection Control
4888 SPIRVOperandList Ops;
4889
4890 // StructurizeCFG pass already manipulated CFG. Just use false block
4891 // of branch instruction as merge block.
4892 uint32_t MergeBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004893 Ops << MkId(MergeBBID) << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004894
David Neto87846742018-04-11 17:36:22 -04004895 auto *MergeInst = new SPIRVInstruction(spv::OpSelectionMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004896 SPIRVInstList.insert(InsertPoint, MergeInst);
4897 }
4898 }
4899
4900 if (Br->isConditional()) {
4901 //
4902 // Generate OpBranchConditional.
4903 //
4904 // Ops[0] = Condition ID
4905 // Ops[1] = True Label ID
4906 // Ops[2] = False Label ID
4907 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
4908 SPIRVOperandList Ops;
4909
4910 uint32_t CondID = VMap[Br->getCondition()];
David Neto22f144c2017-06-12 14:26:21 -04004911 uint32_t TrueBBID = VMap[Br->getSuccessor(0)];
David Neto22f144c2017-06-12 14:26:21 -04004912 uint32_t FalseBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004913
4914 Ops << MkId(CondID) << MkId(TrueBBID) << MkId(FalseBBID);
David Neto22f144c2017-06-12 14:26:21 -04004915
David Neto87846742018-04-11 17:36:22 -04004916 auto *BrInst = new SPIRVInstruction(spv::OpBranchConditional, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004917 SPIRVInstList.insert(InsertPoint, BrInst);
4918 } else {
4919 //
4920 // Generate OpBranch.
4921 //
4922 // Ops[0] = Target Label ID
4923 SPIRVOperandList Ops;
4924
4925 uint32_t TargetID = VMap[Br->getSuccessor(0)];
David Neto257c3892018-04-11 13:19:45 -04004926 Ops << MkId(TargetID);
David Neto22f144c2017-06-12 14:26:21 -04004927
David Neto87846742018-04-11 17:36:22 -04004928 SPIRVInstList.insert(InsertPoint,
4929 new SPIRVInstruction(spv::OpBranch, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004930 }
4931 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
alan-baker5b86ed72019-02-15 08:26:50 -05004932 if (PHI->getType()->isPointerTy()) {
4933 // OpPhi on pointers requires variable pointers.
4934 setVariablePointersCapabilities(
4935 PHI->getType()->getPointerAddressSpace());
4936 if (!hasVariablePointers() && !selectFromSameObject(PHI)) {
4937 setVariablePointers(true);
4938 }
4939 }
4940
David Neto22f144c2017-06-12 14:26:21 -04004941 //
4942 // Generate OpPhi.
4943 //
4944 // Ops[0] = Result Type ID
4945 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
4946 SPIRVOperandList Ops;
4947
David Neto257c3892018-04-11 13:19:45 -04004948 Ops << MkId(lookupType(PHI->getType()));
David Neto22f144c2017-06-12 14:26:21 -04004949
David Neto22f144c2017-06-12 14:26:21 -04004950 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
4951 uint32_t VarID = VMap[PHI->getIncomingValue(i)];
David Neto22f144c2017-06-12 14:26:21 -04004952 uint32_t ParentID = VMap[PHI->getIncomingBlock(i)];
David Neto257c3892018-04-11 13:19:45 -04004953 Ops << MkId(VarID) << MkId(ParentID);
David Neto22f144c2017-06-12 14:26:21 -04004954 }
4955
4956 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04004957 InsertPoint,
4958 new SPIRVInstruction(spv::OpPhi, std::get<2>(*DeferredInst), Ops));
David Neto22f144c2017-06-12 14:26:21 -04004959 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
4960 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04004961 auto callee_name = Callee->getName();
4962 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04004963
4964 if (EInst) {
4965 uint32_t &ExtInstImportID = getOpExtInstImportID();
4966
4967 //
4968 // Generate OpExtInst.
4969 //
4970
4971 // Ops[0] = Result Type ID
4972 // Ops[1] = Set ID (OpExtInstImport ID)
4973 // Ops[2] = Instruction Number (Literal Number)
4974 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
4975 SPIRVOperandList Ops;
4976
David Neto862b7d82018-06-14 18:48:37 -04004977 Ops << MkId(lookupType(Call->getType())) << MkId(ExtInstImportID)
4978 << MkNum(EInst);
David Neto22f144c2017-06-12 14:26:21 -04004979
David Neto22f144c2017-06-12 14:26:21 -04004980 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
4981 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004982 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004983 }
4984
David Neto87846742018-04-11 17:36:22 -04004985 auto *ExtInst = new SPIRVInstruction(spv::OpExtInst,
4986 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04004987 SPIRVInstList.insert(InsertPoint, ExtInst);
4988
David Neto3fbb4072017-10-16 11:28:14 -04004989 const auto IndirectExtInst = getIndirectExtInstEnum(callee_name);
4990 if (IndirectExtInst != kGlslExtInstBad) {
4991 // Generate one more instruction that uses the result of the extended
4992 // instruction. Its result id is one more than the id of the
4993 // extended instruction.
David Neto22f144c2017-06-12 14:26:21 -04004994 LLVMContext &Context =
4995 Call->getParent()->getParent()->getParent()->getContext();
David Neto22f144c2017-06-12 14:26:21 -04004996
David Neto3fbb4072017-10-16 11:28:14 -04004997 auto generate_extra_inst = [this, &Context, &Call, &DeferredInst,
4998 &VMap, &SPIRVInstList, &InsertPoint](
4999 spv::Op opcode, Constant *constant) {
5000 //
5001 // Generate instruction like:
5002 // result = opcode constant <extinst-result>
5003 //
5004 // Ops[0] = Result Type ID
5005 // Ops[1] = Operand 0 ;; the constant, suitably splatted
5006 // Ops[2] = Operand 1 ;; the result of the extended instruction
5007 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04005008
David Neto3fbb4072017-10-16 11:28:14 -04005009 Type *resultTy = Call->getType();
David Neto257c3892018-04-11 13:19:45 -04005010 Ops << MkId(lookupType(resultTy));
David Neto3fbb4072017-10-16 11:28:14 -04005011
5012 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
5013 constant = ConstantVector::getSplat(
5014 static_cast<unsigned>(vectorTy->getNumElements()), constant);
5015 }
David Neto257c3892018-04-11 13:19:45 -04005016 Ops << MkId(VMap[constant]) << MkId(std::get<2>(*DeferredInst));
David Neto3fbb4072017-10-16 11:28:14 -04005017
5018 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005019 InsertPoint, new SPIRVInstruction(
5020 opcode, std::get<2>(*DeferredInst) + 1, Ops));
David Neto3fbb4072017-10-16 11:28:14 -04005021 };
5022
5023 switch (IndirectExtInst) {
5024 case glsl::ExtInstFindUMsb: // Implementing clz
5025 generate_extra_inst(
5026 spv::OpISub, ConstantInt::get(Type::getInt32Ty(Context), 31));
5027 break;
5028 case glsl::ExtInstAcos: // Implementing acospi
5029 case glsl::ExtInstAsin: // Implementing asinpi
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005030 case glsl::ExtInstAtan: // Implementing atanpi
David Neto3fbb4072017-10-16 11:28:14 -04005031 case glsl::ExtInstAtan2: // Implementing atan2pi
5032 generate_extra_inst(
5033 spv::OpFMul,
5034 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
5035 break;
5036
5037 default:
5038 assert(false && "internally inconsistent");
David Neto4d02a532017-09-17 12:57:44 -04005039 }
David Neto22f144c2017-06-12 14:26:21 -04005040 }
David Neto3fbb4072017-10-16 11:28:14 -04005041
alan-bakerb39c8262019-03-08 14:03:37 -05005042 } else if (callee_name.startswith("_Z8popcount")) {
David Neto22f144c2017-06-12 14:26:21 -04005043 //
5044 // Generate OpBitCount
5045 //
5046 // Ops[0] = Result Type ID
5047 // Ops[1] = Base ID
David Neto257c3892018-04-11 13:19:45 -04005048 SPIRVOperandList Ops;
5049 Ops << MkId(lookupType(Call->getType()))
5050 << MkId(VMap[Call->getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04005051
5052 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005053 InsertPoint, new SPIRVInstruction(spv::OpBitCount,
David Neto22f144c2017-06-12 14:26:21 -04005054 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005055
David Neto862b7d82018-06-14 18:48:37 -04005056 } else if (callee_name.startswith(kCompositeConstructFunctionPrefix)) {
David Netoab03f432017-11-03 17:00:44 -04005057
5058 // Generate an OpCompositeConstruct
5059 SPIRVOperandList Ops;
5060
5061 // The result type.
David Neto257c3892018-04-11 13:19:45 -04005062 Ops << MkId(lookupType(Call->getType()));
David Netoab03f432017-11-03 17:00:44 -04005063
5064 for (Use &use : Call->arg_operands()) {
David Neto257c3892018-04-11 13:19:45 -04005065 Ops << MkId(VMap[use.get()]);
David Netoab03f432017-11-03 17:00:44 -04005066 }
5067
5068 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005069 InsertPoint, new SPIRVInstruction(spv::OpCompositeConstruct,
5070 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005071
Alan Baker202c8c72018-08-13 13:47:44 -04005072 } else if (callee_name.startswith(clspv::ResourceAccessorFunction())) {
5073
5074 // We have already mapped the call's result value to an ID.
5075 // Don't generate any code now.
5076
5077 } else if (callee_name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04005078
5079 // We have already mapped the call's result value to an ID.
5080 // Don't generate any code now.
5081
David Neto22f144c2017-06-12 14:26:21 -04005082 } else {
alan-baker5b86ed72019-02-15 08:26:50 -05005083 if (Call->getType()->isPointerTy()) {
5084 // Functions returning pointers require variable pointers.
5085 setVariablePointersCapabilities(
5086 Call->getType()->getPointerAddressSpace());
5087 }
5088
David Neto22f144c2017-06-12 14:26:21 -04005089 //
5090 // Generate OpFunctionCall.
5091 //
5092
5093 // Ops[0] = Result Type ID
5094 // Ops[1] = Callee Function ID
5095 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
5096 SPIRVOperandList Ops;
5097
David Neto862b7d82018-06-14 18:48:37 -04005098 Ops << MkId(lookupType(Call->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005099
5100 uint32_t CalleeID = VMap[Callee];
David Neto43568eb2017-10-13 18:25:25 -04005101 if (CalleeID == 0) {
5102 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04005103 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04005104 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
5105 // causes an infinite loop. Instead, go ahead and generate
5106 // the bad function call. A validator will catch the 0-Id.
5107 // llvm_unreachable("Can't translate function call");
5108 }
David Neto22f144c2017-06-12 14:26:21 -04005109
David Neto257c3892018-04-11 13:19:45 -04005110 Ops << MkId(CalleeID);
David Neto22f144c2017-06-12 14:26:21 -04005111
David Neto22f144c2017-06-12 14:26:21 -04005112 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5113 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
alan-baker5b86ed72019-02-15 08:26:50 -05005114 auto *operand = Call->getOperand(i);
5115 if (operand->getType()->isPointerTy()) {
5116 auto sc =
5117 GetStorageClass(operand->getType()->getPointerAddressSpace());
5118 if (sc == spv::StorageClassStorageBuffer) {
5119 // Passing SSBO by reference requires variable pointers storage
5120 // buffer.
5121 setVariablePointersStorageBuffer(true);
5122 } else if (sc == spv::StorageClassWorkgroup) {
5123 // Workgroup references require variable pointers if they are not
5124 // memory object declarations.
5125 if (auto *operand_call = dyn_cast<CallInst>(operand)) {
5126 // Workgroup accessor represents a variable reference.
5127 if (!operand_call->getCalledFunction()->getName().startswith(
5128 clspv::WorkgroupAccessorFunction()))
5129 setVariablePointers(true);
5130 } else {
5131 // Arguments are function parameters.
5132 if (!isa<Argument>(operand))
5133 setVariablePointers(true);
5134 }
5135 }
5136 }
5137 Ops << MkId(VMap[operand]);
David Neto22f144c2017-06-12 14:26:21 -04005138 }
5139
David Neto87846742018-04-11 17:36:22 -04005140 auto *CallInst = new SPIRVInstruction(spv::OpFunctionCall,
5141 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005142 SPIRVInstList.insert(InsertPoint, CallInst);
5143 }
5144 }
5145 }
5146}
5147
David Neto1a1a0582017-07-07 12:01:44 -04005148void SPIRVProducerPass::HandleDeferredDecorations(const DataLayout &DL) {
Alan Baker202c8c72018-08-13 13:47:44 -04005149 if (getTypesNeedingArrayStride().empty() && LocalArgSpecIds.empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04005150 return;
David Netoc6f3ab22018-04-06 18:02:31 -04005151 }
David Neto1a1a0582017-07-07 12:01:44 -04005152
5153 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto1a1a0582017-07-07 12:01:44 -04005154
5155 // Find an iterator pointing just past the last decoration.
5156 bool seen_decorations = false;
5157 auto DecoInsertPoint =
5158 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
5159 [&seen_decorations](SPIRVInstruction *Inst) -> bool {
5160 const bool is_decoration =
5161 Inst->getOpcode() == spv::OpDecorate ||
5162 Inst->getOpcode() == spv::OpMemberDecorate;
5163 if (is_decoration) {
5164 seen_decorations = true;
5165 return false;
5166 } else {
5167 return seen_decorations;
5168 }
5169 });
5170
David Netoc6f3ab22018-04-06 18:02:31 -04005171 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
5172 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07005173 for (auto *type : getTypesNeedingArrayStride()) {
5174 Type *elemTy = nullptr;
5175 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
5176 elemTy = ptrTy->getElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005177 } else if (auto *arrayTy = dyn_cast<ArrayType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005178 elemTy = arrayTy->getArrayElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005179 } else if (auto *seqTy = dyn_cast<SequentialType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005180 elemTy = seqTy->getSequentialElementType();
5181 } else {
5182 errs() << "Unhandled strided type " << *type << "\n";
5183 llvm_unreachable("Unhandled strided type");
5184 }
David Neto1a1a0582017-07-07 12:01:44 -04005185
5186 // Ops[0] = Target ID
5187 // Ops[1] = Decoration (ArrayStride)
5188 // Ops[2] = Stride number (Literal Number)
5189 SPIRVOperandList Ops;
5190
David Neto85082642018-03-24 06:55:20 -07005191 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Alan Bakerfcda9482018-10-02 17:09:59 -04005192 const uint32_t stride = static_cast<uint32_t>(GetTypeAllocSize(elemTy, DL));
David Neto257c3892018-04-11 13:19:45 -04005193
5194 Ops << MkId(lookupType(type)) << MkNum(spv::DecorationArrayStride)
5195 << MkNum(stride);
David Neto1a1a0582017-07-07 12:01:44 -04005196
David Neto87846742018-04-11 17:36:22 -04005197 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto1a1a0582017-07-07 12:01:44 -04005198 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
5199 }
David Netoc6f3ab22018-04-06 18:02:31 -04005200
5201 // Emit SpecId decorations targeting the array size value.
Alan Baker202c8c72018-08-13 13:47:44 -04005202 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
5203 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005204 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04005205 SPIRVOperandList Ops;
5206 Ops << MkId(arg_info.array_size_id) << MkNum(spv::DecorationSpecId)
5207 << MkNum(arg_info.spec_id);
5208 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04005209 new SPIRVInstruction(spv::OpDecorate, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04005210 }
David Neto1a1a0582017-07-07 12:01:44 -04005211}
5212
David Neto22f144c2017-06-12 14:26:21 -04005213glsl::ExtInst SPIRVProducerPass::getExtInstEnum(StringRef Name) {
5214 return StringSwitch<glsl::ExtInst>(Name)
alan-bakerb39c8262019-03-08 14:03:37 -05005215 .Case("_Z3absc", glsl::ExtInst::ExtInstSAbs)
5216 .Case("_Z3absDv2_c", glsl::ExtInst::ExtInstSAbs)
5217 .Case("_Z3absDv3_c", glsl::ExtInst::ExtInstSAbs)
5218 .Case("_Z3absDv4_c", glsl::ExtInst::ExtInstSAbs)
Kévin Petit2444e9b2018-11-09 14:14:37 +00005219 .Case("_Z3abss", glsl::ExtInst::ExtInstSAbs)
5220 .Case("_Z3absDv2_s", glsl::ExtInst::ExtInstSAbs)
5221 .Case("_Z3absDv3_s", glsl::ExtInst::ExtInstSAbs)
5222 .Case("_Z3absDv4_s", glsl::ExtInst::ExtInstSAbs)
David Neto22f144c2017-06-12 14:26:21 -04005223 .Case("_Z3absi", glsl::ExtInst::ExtInstSAbs)
5224 .Case("_Z3absDv2_i", glsl::ExtInst::ExtInstSAbs)
5225 .Case("_Z3absDv3_i", glsl::ExtInst::ExtInstSAbs)
5226 .Case("_Z3absDv4_i", glsl::ExtInst::ExtInstSAbs)
Kévin Petit2444e9b2018-11-09 14:14:37 +00005227 .Case("_Z3absl", glsl::ExtInst::ExtInstSAbs)
5228 .Case("_Z3absDv2_l", glsl::ExtInst::ExtInstSAbs)
5229 .Case("_Z3absDv3_l", glsl::ExtInst::ExtInstSAbs)
5230 .Case("_Z3absDv4_l", glsl::ExtInst::ExtInstSAbs)
alan-bakerb39c8262019-03-08 14:03:37 -05005231 .Case("_Z5clampccc", glsl::ExtInst::ExtInstSClamp)
5232 .Case("_Z5clampDv2_cS_S_", glsl::ExtInst::ExtInstSClamp)
5233 .Case("_Z5clampDv3_cS_S_", glsl::ExtInst::ExtInstSClamp)
5234 .Case("_Z5clampDv4_cS_S_", glsl::ExtInst::ExtInstSClamp)
5235 .Case("_Z5clamphhh", glsl::ExtInst::ExtInstUClamp)
5236 .Case("_Z5clampDv2_hS_S_", glsl::ExtInst::ExtInstUClamp)
5237 .Case("_Z5clampDv3_hS_S_", glsl::ExtInst::ExtInstUClamp)
5238 .Case("_Z5clampDv4_hS_S_", glsl::ExtInst::ExtInstUClamp)
Kévin Petit495255d2019-03-06 13:56:48 +00005239 .Case("_Z5clampsss", glsl::ExtInst::ExtInstSClamp)
5240 .Case("_Z5clampDv2_sS_S_", glsl::ExtInst::ExtInstSClamp)
5241 .Case("_Z5clampDv3_sS_S_", glsl::ExtInst::ExtInstSClamp)
5242 .Case("_Z5clampDv4_sS_S_", glsl::ExtInst::ExtInstSClamp)
5243 .Case("_Z5clampttt", glsl::ExtInst::ExtInstUClamp)
5244 .Case("_Z5clampDv2_tS_S_", glsl::ExtInst::ExtInstUClamp)
5245 .Case("_Z5clampDv3_tS_S_", glsl::ExtInst::ExtInstUClamp)
5246 .Case("_Z5clampDv4_tS_S_", glsl::ExtInst::ExtInstUClamp)
David Neto22f144c2017-06-12 14:26:21 -04005247 .Case("_Z5clampiii", glsl::ExtInst::ExtInstSClamp)
5248 .Case("_Z5clampDv2_iS_S_", glsl::ExtInst::ExtInstSClamp)
5249 .Case("_Z5clampDv3_iS_S_", glsl::ExtInst::ExtInstSClamp)
5250 .Case("_Z5clampDv4_iS_S_", glsl::ExtInst::ExtInstSClamp)
5251 .Case("_Z5clampjjj", glsl::ExtInst::ExtInstUClamp)
5252 .Case("_Z5clampDv2_jS_S_", glsl::ExtInst::ExtInstUClamp)
5253 .Case("_Z5clampDv3_jS_S_", glsl::ExtInst::ExtInstUClamp)
5254 .Case("_Z5clampDv4_jS_S_", glsl::ExtInst::ExtInstUClamp)
Kévin Petit495255d2019-03-06 13:56:48 +00005255 .Case("_Z5clamplll", glsl::ExtInst::ExtInstSClamp)
5256 .Case("_Z5clampDv2_lS_S_", glsl::ExtInst::ExtInstSClamp)
5257 .Case("_Z5clampDv3_lS_S_", glsl::ExtInst::ExtInstSClamp)
5258 .Case("_Z5clampDv4_lS_S_", glsl::ExtInst::ExtInstSClamp)
5259 .Case("_Z5clampmmm", glsl::ExtInst::ExtInstUClamp)
5260 .Case("_Z5clampDv2_mS_S_", glsl::ExtInst::ExtInstUClamp)
5261 .Case("_Z5clampDv3_mS_S_", glsl::ExtInst::ExtInstUClamp)
5262 .Case("_Z5clampDv4_mS_S_", glsl::ExtInst::ExtInstUClamp)
David Neto22f144c2017-06-12 14:26:21 -04005263 .Case("_Z5clampfff", glsl::ExtInst::ExtInstFClamp)
5264 .Case("_Z5clampDv2_fS_S_", glsl::ExtInst::ExtInstFClamp)
5265 .Case("_Z5clampDv3_fS_S_", glsl::ExtInst::ExtInstFClamp)
5266 .Case("_Z5clampDv4_fS_S_", glsl::ExtInst::ExtInstFClamp)
alan-bakerb39c8262019-03-08 14:03:37 -05005267 .Case("_Z3maxcc", glsl::ExtInst::ExtInstSMax)
5268 .Case("_Z3maxDv2_cS_", glsl::ExtInst::ExtInstSMax)
5269 .Case("_Z3maxDv3_cS_", glsl::ExtInst::ExtInstSMax)
5270 .Case("_Z3maxDv4_cS_", glsl::ExtInst::ExtInstSMax)
5271 .Case("_Z3maxhh", glsl::ExtInst::ExtInstUMax)
5272 .Case("_Z3maxDv2_hS_", glsl::ExtInst::ExtInstUMax)
5273 .Case("_Z3maxDv3_hS_", glsl::ExtInst::ExtInstUMax)
5274 .Case("_Z3maxDv4_hS_", glsl::ExtInst::ExtInstUMax)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005275 .Case("_Z3maxss", glsl::ExtInst::ExtInstSMax)
5276 .Case("_Z3maxDv2_sS_", glsl::ExtInst::ExtInstSMax)
5277 .Case("_Z3maxDv3_sS_", glsl::ExtInst::ExtInstSMax)
5278 .Case("_Z3maxDv4_sS_", glsl::ExtInst::ExtInstSMax)
5279 .Case("_Z3maxtt", glsl::ExtInst::ExtInstUMax)
5280 .Case("_Z3maxDv2_tS_", glsl::ExtInst::ExtInstUMax)
5281 .Case("_Z3maxDv3_tS_", glsl::ExtInst::ExtInstUMax)
5282 .Case("_Z3maxDv4_tS_", glsl::ExtInst::ExtInstUMax)
David Neto22f144c2017-06-12 14:26:21 -04005283 .Case("_Z3maxii", glsl::ExtInst::ExtInstSMax)
5284 .Case("_Z3maxDv2_iS_", glsl::ExtInst::ExtInstSMax)
5285 .Case("_Z3maxDv3_iS_", glsl::ExtInst::ExtInstSMax)
5286 .Case("_Z3maxDv4_iS_", glsl::ExtInst::ExtInstSMax)
5287 .Case("_Z3maxjj", glsl::ExtInst::ExtInstUMax)
5288 .Case("_Z3maxDv2_jS_", glsl::ExtInst::ExtInstUMax)
5289 .Case("_Z3maxDv3_jS_", glsl::ExtInst::ExtInstUMax)
5290 .Case("_Z3maxDv4_jS_", glsl::ExtInst::ExtInstUMax)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005291 .Case("_Z3maxll", glsl::ExtInst::ExtInstSMax)
5292 .Case("_Z3maxDv2_lS_", glsl::ExtInst::ExtInstSMax)
5293 .Case("_Z3maxDv3_lS_", glsl::ExtInst::ExtInstSMax)
5294 .Case("_Z3maxDv4_lS_", glsl::ExtInst::ExtInstSMax)
5295 .Case("_Z3maxmm", glsl::ExtInst::ExtInstUMax)
5296 .Case("_Z3maxDv2_mS_", glsl::ExtInst::ExtInstUMax)
5297 .Case("_Z3maxDv3_mS_", glsl::ExtInst::ExtInstUMax)
5298 .Case("_Z3maxDv4_mS_", glsl::ExtInst::ExtInstUMax)
David Neto22f144c2017-06-12 14:26:21 -04005299 .Case("_Z3maxff", glsl::ExtInst::ExtInstFMax)
5300 .Case("_Z3maxDv2_fS_", glsl::ExtInst::ExtInstFMax)
5301 .Case("_Z3maxDv3_fS_", glsl::ExtInst::ExtInstFMax)
5302 .Case("_Z3maxDv4_fS_", glsl::ExtInst::ExtInstFMax)
5303 .StartsWith("_Z4fmax", glsl::ExtInst::ExtInstFMax)
alan-bakerb39c8262019-03-08 14:03:37 -05005304 .Case("_Z3mincc", glsl::ExtInst::ExtInstSMin)
5305 .Case("_Z3minDv2_cS_", glsl::ExtInst::ExtInstSMin)
5306 .Case("_Z3minDv3_cS_", glsl::ExtInst::ExtInstSMin)
5307 .Case("_Z3minDv4_cS_", glsl::ExtInst::ExtInstSMin)
5308 .Case("_Z3minhh", glsl::ExtInst::ExtInstUMin)
5309 .Case("_Z3minDv2_hS_", glsl::ExtInst::ExtInstUMin)
5310 .Case("_Z3minDv3_hS_", glsl::ExtInst::ExtInstUMin)
5311 .Case("_Z3minDv4_hS_", glsl::ExtInst::ExtInstUMin)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005312 .Case("_Z3minss", glsl::ExtInst::ExtInstSMin)
5313 .Case("_Z3minDv2_sS_", glsl::ExtInst::ExtInstSMin)
5314 .Case("_Z3minDv3_sS_", glsl::ExtInst::ExtInstSMin)
5315 .Case("_Z3minDv4_sS_", glsl::ExtInst::ExtInstSMin)
5316 .Case("_Z3mintt", glsl::ExtInst::ExtInstUMin)
5317 .Case("_Z3minDv2_tS_", glsl::ExtInst::ExtInstUMin)
5318 .Case("_Z3minDv3_tS_", glsl::ExtInst::ExtInstUMin)
5319 .Case("_Z3minDv4_tS_", glsl::ExtInst::ExtInstUMin)
David Neto22f144c2017-06-12 14:26:21 -04005320 .Case("_Z3minii", glsl::ExtInst::ExtInstSMin)
5321 .Case("_Z3minDv2_iS_", glsl::ExtInst::ExtInstSMin)
5322 .Case("_Z3minDv3_iS_", glsl::ExtInst::ExtInstSMin)
5323 .Case("_Z3minDv4_iS_", glsl::ExtInst::ExtInstSMin)
5324 .Case("_Z3minjj", glsl::ExtInst::ExtInstUMin)
5325 .Case("_Z3minDv2_jS_", glsl::ExtInst::ExtInstUMin)
5326 .Case("_Z3minDv3_jS_", glsl::ExtInst::ExtInstUMin)
5327 .Case("_Z3minDv4_jS_", glsl::ExtInst::ExtInstUMin)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005328 .Case("_Z3minll", glsl::ExtInst::ExtInstSMin)
5329 .Case("_Z3minDv2_lS_", glsl::ExtInst::ExtInstSMin)
5330 .Case("_Z3minDv3_lS_", glsl::ExtInst::ExtInstSMin)
5331 .Case("_Z3minDv4_lS_", glsl::ExtInst::ExtInstSMin)
5332 .Case("_Z3minmm", glsl::ExtInst::ExtInstUMin)
5333 .Case("_Z3minDv2_mS_", glsl::ExtInst::ExtInstUMin)
5334 .Case("_Z3minDv3_mS_", glsl::ExtInst::ExtInstUMin)
5335 .Case("_Z3minDv4_mS_", glsl::ExtInst::ExtInstUMin)
David Neto22f144c2017-06-12 14:26:21 -04005336 .Case("_Z3minff", glsl::ExtInst::ExtInstFMin)
5337 .Case("_Z3minDv2_fS_", glsl::ExtInst::ExtInstFMin)
5338 .Case("_Z3minDv3_fS_", glsl::ExtInst::ExtInstFMin)
5339 .Case("_Z3minDv4_fS_", glsl::ExtInst::ExtInstFMin)
5340 .StartsWith("_Z4fmin", glsl::ExtInst::ExtInstFMin)
5341 .StartsWith("_Z7degrees", glsl::ExtInst::ExtInstDegrees)
5342 .StartsWith("_Z7radians", glsl::ExtInst::ExtInstRadians)
5343 .StartsWith("_Z3mix", glsl::ExtInst::ExtInstFMix)
5344 .StartsWith("_Z4acos", glsl::ExtInst::ExtInstAcos)
5345 .StartsWith("_Z5acosh", glsl::ExtInst::ExtInstAcosh)
5346 .StartsWith("_Z4asin", glsl::ExtInst::ExtInstAsin)
5347 .StartsWith("_Z5asinh", glsl::ExtInst::ExtInstAsinh)
5348 .StartsWith("_Z4atan", glsl::ExtInst::ExtInstAtan)
5349 .StartsWith("_Z5atan2", glsl::ExtInst::ExtInstAtan2)
5350 .StartsWith("_Z5atanh", glsl::ExtInst::ExtInstAtanh)
5351 .StartsWith("_Z4ceil", glsl::ExtInst::ExtInstCeil)
5352 .StartsWith("_Z3sin", glsl::ExtInst::ExtInstSin)
5353 .StartsWith("_Z4sinh", glsl::ExtInst::ExtInstSinh)
5354 .StartsWith("_Z8half_sin", glsl::ExtInst::ExtInstSin)
5355 .StartsWith("_Z10native_sin", glsl::ExtInst::ExtInstSin)
5356 .StartsWith("_Z3cos", glsl::ExtInst::ExtInstCos)
5357 .StartsWith("_Z4cosh", glsl::ExtInst::ExtInstCosh)
5358 .StartsWith("_Z8half_cos", glsl::ExtInst::ExtInstCos)
5359 .StartsWith("_Z10native_cos", glsl::ExtInst::ExtInstCos)
5360 .StartsWith("_Z3tan", glsl::ExtInst::ExtInstTan)
5361 .StartsWith("_Z4tanh", glsl::ExtInst::ExtInstTanh)
5362 .StartsWith("_Z8half_tan", glsl::ExtInst::ExtInstTan)
5363 .StartsWith("_Z10native_tan", glsl::ExtInst::ExtInstTan)
5364 .StartsWith("_Z3exp", glsl::ExtInst::ExtInstExp)
5365 .StartsWith("_Z8half_exp", glsl::ExtInst::ExtInstExp)
5366 .StartsWith("_Z10native_exp", glsl::ExtInst::ExtInstExp)
5367 .StartsWith("_Z4exp2", glsl::ExtInst::ExtInstExp2)
5368 .StartsWith("_Z9half_exp2", glsl::ExtInst::ExtInstExp2)
5369 .StartsWith("_Z11native_exp2", glsl::ExtInst::ExtInstExp2)
5370 .StartsWith("_Z3log", glsl::ExtInst::ExtInstLog)
5371 .StartsWith("_Z8half_log", glsl::ExtInst::ExtInstLog)
5372 .StartsWith("_Z10native_log", glsl::ExtInst::ExtInstLog)
5373 .StartsWith("_Z4log2", glsl::ExtInst::ExtInstLog2)
5374 .StartsWith("_Z9half_log2", glsl::ExtInst::ExtInstLog2)
5375 .StartsWith("_Z11native_log2", glsl::ExtInst::ExtInstLog2)
5376 .StartsWith("_Z4fabs", glsl::ExtInst::ExtInstFAbs)
kpet3458e942018-10-03 14:35:21 +01005377 .StartsWith("_Z3fma", glsl::ExtInst::ExtInstFma)
David Neto22f144c2017-06-12 14:26:21 -04005378 .StartsWith("_Z5floor", glsl::ExtInst::ExtInstFloor)
5379 .StartsWith("_Z5ldexp", glsl::ExtInst::ExtInstLdexp)
5380 .StartsWith("_Z3pow", glsl::ExtInst::ExtInstPow)
5381 .StartsWith("_Z4powr", glsl::ExtInst::ExtInstPow)
5382 .StartsWith("_Z9half_powr", glsl::ExtInst::ExtInstPow)
5383 .StartsWith("_Z11native_powr", glsl::ExtInst::ExtInstPow)
5384 .StartsWith("_Z5round", glsl::ExtInst::ExtInstRound)
5385 .StartsWith("_Z4sqrt", glsl::ExtInst::ExtInstSqrt)
5386 .StartsWith("_Z9half_sqrt", glsl::ExtInst::ExtInstSqrt)
5387 .StartsWith("_Z11native_sqrt", glsl::ExtInst::ExtInstSqrt)
5388 .StartsWith("_Z5rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5389 .StartsWith("_Z10half_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5390 .StartsWith("_Z12native_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5391 .StartsWith("_Z5trunc", glsl::ExtInst::ExtInstTrunc)
5392 .StartsWith("_Z5frexp", glsl::ExtInst::ExtInstFrexp)
5393 .StartsWith("_Z4sign", glsl::ExtInst::ExtInstFSign)
5394 .StartsWith("_Z6length", glsl::ExtInst::ExtInstLength)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005395 .StartsWith("_Z11fast_length", glsl::ExtInst::ExtInstLength)
David Neto22f144c2017-06-12 14:26:21 -04005396 .StartsWith("_Z8distance", glsl::ExtInst::ExtInstDistance)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005397 .StartsWith("_Z13fast_distance", glsl::ExtInst::ExtInstDistance)
David Netoe9a03512017-10-16 10:08:27 -04005398 .StartsWith("_Z4step", glsl::ExtInst::ExtInstStep)
kpet6fd2a262018-10-03 14:48:01 +01005399 .StartsWith("_Z10smoothstep", glsl::ExtInst::ExtInstSmoothStep)
David Neto22f144c2017-06-12 14:26:21 -04005400 .Case("_Z5crossDv3_fS_", glsl::ExtInst::ExtInstCross)
5401 .StartsWith("_Z9normalize", glsl::ExtInst::ExtInstNormalize)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005402 .StartsWith("_Z14fast_normalize", glsl::ExtInst::ExtInstNormalize)
David Neto22f144c2017-06-12 14:26:21 -04005403 .StartsWith("llvm.fmuladd.", glsl::ExtInst::ExtInstFma)
5404 .Case("spirv.unpack.v2f16", glsl::ExtInst::ExtInstUnpackHalf2x16)
5405 .Case("spirv.pack.v2f16", glsl::ExtInst::ExtInstPackHalf2x16)
David Neto62653202017-10-16 19:05:18 -04005406 .Case("clspv.fract.f", glsl::ExtInst::ExtInstFract)
5407 .Case("clspv.fract.v2f", glsl::ExtInst::ExtInstFract)
5408 .Case("clspv.fract.v3f", glsl::ExtInst::ExtInstFract)
5409 .Case("clspv.fract.v4f", glsl::ExtInst::ExtInstFract)
David Neto3fbb4072017-10-16 11:28:14 -04005410 .Default(kGlslExtInstBad);
5411}
5412
5413glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(StringRef Name) {
5414 // Check indirect cases.
5415 return StringSwitch<glsl::ExtInst>(Name)
5416 .StartsWith("_Z3clz", glsl::ExtInst::ExtInstFindUMsb)
5417 // Use exact match on float arg because these need a multiply
5418 // of a constant of the right floating point type.
5419 .Case("_Z6acospif", glsl::ExtInst::ExtInstAcos)
5420 .Case("_Z6acospiDv2_f", glsl::ExtInst::ExtInstAcos)
5421 .Case("_Z6acospiDv3_f", glsl::ExtInst::ExtInstAcos)
5422 .Case("_Z6acospiDv4_f", glsl::ExtInst::ExtInstAcos)
5423 .Case("_Z6asinpif", glsl::ExtInst::ExtInstAsin)
5424 .Case("_Z6asinpiDv2_f", glsl::ExtInst::ExtInstAsin)
5425 .Case("_Z6asinpiDv3_f", glsl::ExtInst::ExtInstAsin)
5426 .Case("_Z6asinpiDv4_f", glsl::ExtInst::ExtInstAsin)
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005427 .Case("_Z6atanpif", glsl::ExtInst::ExtInstAtan)
5428 .Case("_Z6atanpiDv2_f", glsl::ExtInst::ExtInstAtan)
5429 .Case("_Z6atanpiDv3_f", glsl::ExtInst::ExtInstAtan)
5430 .Case("_Z6atanpiDv4_f", glsl::ExtInst::ExtInstAtan)
David Neto3fbb4072017-10-16 11:28:14 -04005431 .Case("_Z7atan2piff", glsl::ExtInst::ExtInstAtan2)
5432 .Case("_Z7atan2piDv2_fS_", glsl::ExtInst::ExtInstAtan2)
5433 .Case("_Z7atan2piDv3_fS_", glsl::ExtInst::ExtInstAtan2)
5434 .Case("_Z7atan2piDv4_fS_", glsl::ExtInst::ExtInstAtan2)
5435 .Default(kGlslExtInstBad);
5436}
5437
alan-bakerb6b09dc2018-11-08 16:59:28 -05005438glsl::ExtInst
5439SPIRVProducerPass::getDirectOrIndirectExtInstEnum(StringRef Name) {
David Neto3fbb4072017-10-16 11:28:14 -04005440 auto direct = getExtInstEnum(Name);
5441 if (direct != kGlslExtInstBad)
5442 return direct;
5443 return getIndirectExtInstEnum(Name);
David Neto22f144c2017-06-12 14:26:21 -04005444}
5445
5446void SPIRVProducerPass::PrintResID(SPIRVInstruction *Inst) {
5447 out << "%" << Inst->getResultID();
5448}
5449
5450void SPIRVProducerPass::PrintOpcode(SPIRVInstruction *Inst) {
5451 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5452 out << "\t" << spv::getOpName(Opcode);
5453}
5454
5455void SPIRVProducerPass::PrintOperand(SPIRVOperand *Op) {
5456 SPIRVOperandType OpTy = Op->getType();
5457 switch (OpTy) {
5458 default: {
5459 llvm_unreachable("Unsupported SPIRV Operand Type???");
5460 break;
5461 }
5462 case SPIRVOperandType::NUMBERID: {
5463 out << "%" << Op->getNumID();
5464 break;
5465 }
5466 case SPIRVOperandType::LITERAL_STRING: {
5467 out << "\"" << Op->getLiteralStr() << "\"";
5468 break;
5469 }
5470 case SPIRVOperandType::LITERAL_INTEGER: {
5471 // TODO: Handle LiteralNum carefully.
Kévin Petite7d0cce2018-10-31 12:38:56 +00005472 auto Words = Op->getLiteralNum();
5473 auto NumWords = Words.size();
5474
5475 if (NumWords == 1) {
5476 out << Words[0];
5477 } else if (NumWords == 2) {
5478 uint64_t Val = (static_cast<uint64_t>(Words[1]) << 32) | Words[0];
5479 out << Val;
5480 } else {
5481 llvm_unreachable("Handle printing arbitrary precision integer literals.");
David Neto22f144c2017-06-12 14:26:21 -04005482 }
5483 break;
5484 }
5485 case SPIRVOperandType::LITERAL_FLOAT: {
5486 // TODO: Handle LiteralNum carefully.
5487 for (auto Word : Op->getLiteralNum()) {
5488 APFloat APF = APFloat(APFloat::IEEEsingle(), APInt(32, Word));
5489 SmallString<8> Str;
5490 APF.toString(Str, 6, 2);
5491 out << Str;
5492 }
5493 break;
5494 }
5495 }
5496}
5497
5498void SPIRVProducerPass::PrintCapability(SPIRVOperand *Op) {
5499 spv::Capability Cap = static_cast<spv::Capability>(Op->getNumID());
5500 out << spv::getCapabilityName(Cap);
5501}
5502
5503void SPIRVProducerPass::PrintExtInst(SPIRVOperand *Op) {
5504 auto LiteralNum = Op->getLiteralNum();
5505 glsl::ExtInst Ext = static_cast<glsl::ExtInst>(LiteralNum[0]);
5506 out << glsl::getExtInstName(Ext);
5507}
5508
5509void SPIRVProducerPass::PrintAddrModel(SPIRVOperand *Op) {
5510 spv::AddressingModel AddrModel =
5511 static_cast<spv::AddressingModel>(Op->getNumID());
5512 out << spv::getAddressingModelName(AddrModel);
5513}
5514
5515void SPIRVProducerPass::PrintMemModel(SPIRVOperand *Op) {
5516 spv::MemoryModel MemModel = static_cast<spv::MemoryModel>(Op->getNumID());
5517 out << spv::getMemoryModelName(MemModel);
5518}
5519
5520void SPIRVProducerPass::PrintExecModel(SPIRVOperand *Op) {
5521 spv::ExecutionModel ExecModel =
5522 static_cast<spv::ExecutionModel>(Op->getNumID());
5523 out << spv::getExecutionModelName(ExecModel);
5524}
5525
5526void SPIRVProducerPass::PrintExecMode(SPIRVOperand *Op) {
5527 spv::ExecutionMode ExecMode = static_cast<spv::ExecutionMode>(Op->getNumID());
5528 out << spv::getExecutionModeName(ExecMode);
5529}
5530
5531void SPIRVProducerPass::PrintSourceLanguage(SPIRVOperand *Op) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005532 spv::SourceLanguage SourceLang =
5533 static_cast<spv::SourceLanguage>(Op->getNumID());
David Neto22f144c2017-06-12 14:26:21 -04005534 out << spv::getSourceLanguageName(SourceLang);
5535}
5536
5537void SPIRVProducerPass::PrintFuncCtrl(SPIRVOperand *Op) {
5538 spv::FunctionControlMask FuncCtrl =
5539 static_cast<spv::FunctionControlMask>(Op->getNumID());
5540 out << spv::getFunctionControlName(FuncCtrl);
5541}
5542
5543void SPIRVProducerPass::PrintStorageClass(SPIRVOperand *Op) {
5544 spv::StorageClass StClass = static_cast<spv::StorageClass>(Op->getNumID());
5545 out << getStorageClassName(StClass);
5546}
5547
5548void SPIRVProducerPass::PrintDecoration(SPIRVOperand *Op) {
5549 spv::Decoration Deco = static_cast<spv::Decoration>(Op->getNumID());
5550 out << getDecorationName(Deco);
5551}
5552
5553void SPIRVProducerPass::PrintBuiltIn(SPIRVOperand *Op) {
5554 spv::BuiltIn BIn = static_cast<spv::BuiltIn>(Op->getNumID());
5555 out << getBuiltInName(BIn);
5556}
5557
5558void SPIRVProducerPass::PrintSelectionControl(SPIRVOperand *Op) {
5559 spv::SelectionControlMask BIn =
5560 static_cast<spv::SelectionControlMask>(Op->getNumID());
5561 out << getSelectionControlName(BIn);
5562}
5563
5564void SPIRVProducerPass::PrintLoopControl(SPIRVOperand *Op) {
5565 spv::LoopControlMask BIn = static_cast<spv::LoopControlMask>(Op->getNumID());
5566 out << getLoopControlName(BIn);
5567}
5568
5569void SPIRVProducerPass::PrintDimensionality(SPIRVOperand *Op) {
5570 spv::Dim DIM = static_cast<spv::Dim>(Op->getNumID());
5571 out << getDimName(DIM);
5572}
5573
5574void SPIRVProducerPass::PrintImageFormat(SPIRVOperand *Op) {
5575 spv::ImageFormat Format = static_cast<spv::ImageFormat>(Op->getNumID());
5576 out << getImageFormatName(Format);
5577}
5578
5579void SPIRVProducerPass::PrintMemoryAccess(SPIRVOperand *Op) {
5580 out << spv::getMemoryAccessName(
5581 static_cast<spv::MemoryAccessMask>(Op->getNumID()));
5582}
5583
5584void SPIRVProducerPass::PrintImageOperandsType(SPIRVOperand *Op) {
5585 auto LiteralNum = Op->getLiteralNum();
5586 spv::ImageOperandsMask Type =
5587 static_cast<spv::ImageOperandsMask>(LiteralNum[0]);
5588 out << getImageOperandsName(Type);
5589}
5590
5591void SPIRVProducerPass::WriteSPIRVAssembly() {
5592 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5593
5594 for (auto Inst : SPIRVInstList) {
5595 SPIRVOperandList Ops = Inst->getOperands();
5596 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5597
5598 switch (Opcode) {
5599 default: {
5600 llvm_unreachable("Unsupported SPIRV instruction");
5601 break;
5602 }
5603 case spv::OpCapability: {
5604 // Ops[0] = Capability
5605 PrintOpcode(Inst);
5606 out << " ";
5607 PrintCapability(Ops[0]);
5608 out << "\n";
5609 break;
5610 }
5611 case spv::OpMemoryModel: {
5612 // Ops[0] = Addressing Model
5613 // Ops[1] = Memory Model
5614 PrintOpcode(Inst);
5615 out << " ";
5616 PrintAddrModel(Ops[0]);
5617 out << " ";
5618 PrintMemModel(Ops[1]);
5619 out << "\n";
5620 break;
5621 }
5622 case spv::OpEntryPoint: {
5623 // Ops[0] = Execution Model
5624 // Ops[1] = EntryPoint ID
5625 // Ops[2] = Name (Literal String)
5626 // Ops[3] ... Ops[n] = Interface ID
5627 PrintOpcode(Inst);
5628 out << " ";
5629 PrintExecModel(Ops[0]);
5630 for (uint32_t i = 1; i < Ops.size(); i++) {
5631 out << " ";
5632 PrintOperand(Ops[i]);
5633 }
5634 out << "\n";
5635 break;
5636 }
5637 case spv::OpExecutionMode: {
5638 // Ops[0] = Entry Point ID
5639 // Ops[1] = Execution Mode
5640 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
5641 PrintOpcode(Inst);
5642 out << " ";
5643 PrintOperand(Ops[0]);
5644 out << " ";
5645 PrintExecMode(Ops[1]);
5646 for (uint32_t i = 2; i < Ops.size(); i++) {
5647 out << " ";
5648 PrintOperand(Ops[i]);
5649 }
5650 out << "\n";
5651 break;
5652 }
5653 case spv::OpSource: {
5654 // Ops[0] = SourceLanguage ID
5655 // Ops[1] = Version (LiteralNum)
5656 PrintOpcode(Inst);
5657 out << " ";
5658 PrintSourceLanguage(Ops[0]);
5659 out << " ";
5660 PrintOperand(Ops[1]);
5661 out << "\n";
5662 break;
5663 }
5664 case spv::OpDecorate: {
5665 // Ops[0] = Target ID
5666 // Ops[1] = Decoration (Block or BufferBlock)
5667 // Ops[2] ... Ops[n] = Optional literals according to Decoration
5668 PrintOpcode(Inst);
5669 out << " ";
5670 PrintOperand(Ops[0]);
5671 out << " ";
5672 PrintDecoration(Ops[1]);
5673 // Handle BuiltIn OpDecorate specially.
5674 if (Ops[1]->getNumID() == spv::DecorationBuiltIn) {
5675 out << " ";
5676 PrintBuiltIn(Ops[2]);
5677 } else {
5678 for (uint32_t i = 2; i < Ops.size(); i++) {
5679 out << " ";
5680 PrintOperand(Ops[i]);
5681 }
5682 }
5683 out << "\n";
5684 break;
5685 }
5686 case spv::OpMemberDecorate: {
5687 // Ops[0] = Structure Type ID
5688 // Ops[1] = Member Index(Literal Number)
5689 // Ops[2] = Decoration
5690 // Ops[3] ... Ops[n] = Optional literals according to Decoration
5691 PrintOpcode(Inst);
5692 out << " ";
5693 PrintOperand(Ops[0]);
5694 out << " ";
5695 PrintOperand(Ops[1]);
5696 out << " ";
5697 PrintDecoration(Ops[2]);
5698 for (uint32_t i = 3; i < Ops.size(); i++) {
5699 out << " ";
5700 PrintOperand(Ops[i]);
5701 }
5702 out << "\n";
5703 break;
5704 }
5705 case spv::OpTypePointer: {
5706 // Ops[0] = Storage Class
5707 // Ops[1] = Element Type ID
5708 PrintResID(Inst);
5709 out << " = ";
5710 PrintOpcode(Inst);
5711 out << " ";
5712 PrintStorageClass(Ops[0]);
5713 out << " ";
5714 PrintOperand(Ops[1]);
5715 out << "\n";
5716 break;
5717 }
5718 case spv::OpTypeImage: {
5719 // Ops[0] = Sampled Type ID
5720 // Ops[1] = Dim ID
5721 // Ops[2] = Depth (Literal Number)
5722 // Ops[3] = Arrayed (Literal Number)
5723 // Ops[4] = MS (Literal Number)
5724 // Ops[5] = Sampled (Literal Number)
5725 // Ops[6] = Image Format ID
5726 PrintResID(Inst);
5727 out << " = ";
5728 PrintOpcode(Inst);
5729 out << " ";
5730 PrintOperand(Ops[0]);
5731 out << " ";
5732 PrintDimensionality(Ops[1]);
5733 out << " ";
5734 PrintOperand(Ops[2]);
5735 out << " ";
5736 PrintOperand(Ops[3]);
5737 out << " ";
5738 PrintOperand(Ops[4]);
5739 out << " ";
5740 PrintOperand(Ops[5]);
5741 out << " ";
5742 PrintImageFormat(Ops[6]);
5743 out << "\n";
5744 break;
5745 }
5746 case spv::OpFunction: {
5747 // Ops[0] : Result Type ID
5748 // Ops[1] : Function Control
5749 // Ops[2] : Function Type ID
5750 PrintResID(Inst);
5751 out << " = ";
5752 PrintOpcode(Inst);
5753 out << " ";
5754 PrintOperand(Ops[0]);
5755 out << " ";
5756 PrintFuncCtrl(Ops[1]);
5757 out << " ";
5758 PrintOperand(Ops[2]);
5759 out << "\n";
5760 break;
5761 }
5762 case spv::OpSelectionMerge: {
5763 // Ops[0] = Merge Block ID
5764 // Ops[1] = Selection Control
5765 PrintOpcode(Inst);
5766 out << " ";
5767 PrintOperand(Ops[0]);
5768 out << " ";
5769 PrintSelectionControl(Ops[1]);
5770 out << "\n";
5771 break;
5772 }
5773 case spv::OpLoopMerge: {
5774 // Ops[0] = Merge Block ID
5775 // Ops[1] = Continue Target ID
5776 // Ops[2] = Selection Control
5777 PrintOpcode(Inst);
5778 out << " ";
5779 PrintOperand(Ops[0]);
5780 out << " ";
5781 PrintOperand(Ops[1]);
5782 out << " ";
5783 PrintLoopControl(Ops[2]);
5784 out << "\n";
5785 break;
5786 }
5787 case spv::OpImageSampleExplicitLod: {
5788 // Ops[0] = Result Type ID
5789 // Ops[1] = Sampled Image ID
5790 // Ops[2] = Coordinate ID
5791 // Ops[3] = Image Operands Type ID
5792 // Ops[4] ... Ops[n] = Operands ID
5793 PrintResID(Inst);
5794 out << " = ";
5795 PrintOpcode(Inst);
5796 for (uint32_t i = 0; i < 3; i++) {
5797 out << " ";
5798 PrintOperand(Ops[i]);
5799 }
5800 out << " ";
5801 PrintImageOperandsType(Ops[3]);
5802 for (uint32_t i = 4; i < Ops.size(); i++) {
5803 out << " ";
5804 PrintOperand(Ops[i]);
5805 }
5806 out << "\n";
5807 break;
5808 }
5809 case spv::OpVariable: {
5810 // Ops[0] : Result Type ID
5811 // Ops[1] : Storage Class
5812 // Ops[2] ... Ops[n] = Initializer IDs
5813 PrintResID(Inst);
5814 out << " = ";
5815 PrintOpcode(Inst);
5816 out << " ";
5817 PrintOperand(Ops[0]);
5818 out << " ";
5819 PrintStorageClass(Ops[1]);
5820 for (uint32_t i = 2; i < Ops.size(); i++) {
5821 out << " ";
5822 PrintOperand(Ops[i]);
5823 }
5824 out << "\n";
5825 break;
5826 }
5827 case spv::OpExtInst: {
5828 // Ops[0] = Result Type ID
5829 // Ops[1] = Set ID (OpExtInstImport ID)
5830 // Ops[2] = Instruction Number (Literal Number)
5831 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5832 PrintResID(Inst);
5833 out << " = ";
5834 PrintOpcode(Inst);
5835 out << " ";
5836 PrintOperand(Ops[0]);
5837 out << " ";
5838 PrintOperand(Ops[1]);
5839 out << " ";
5840 PrintExtInst(Ops[2]);
5841 for (uint32_t i = 3; i < Ops.size(); i++) {
5842 out << " ";
5843 PrintOperand(Ops[i]);
5844 }
5845 out << "\n";
5846 break;
5847 }
5848 case spv::OpCopyMemory: {
5849 // Ops[0] = Addressing Model
5850 // Ops[1] = Memory Model
5851 PrintOpcode(Inst);
5852 out << " ";
5853 PrintOperand(Ops[0]);
5854 out << " ";
5855 PrintOperand(Ops[1]);
5856 out << " ";
5857 PrintMemoryAccess(Ops[2]);
5858 out << " ";
5859 PrintOperand(Ops[3]);
5860 out << "\n";
5861 break;
5862 }
5863 case spv::OpExtension:
5864 case spv::OpControlBarrier:
5865 case spv::OpMemoryBarrier:
5866 case spv::OpBranch:
5867 case spv::OpBranchConditional:
5868 case spv::OpStore:
5869 case spv::OpImageWrite:
5870 case spv::OpReturnValue:
5871 case spv::OpReturn:
5872 case spv::OpFunctionEnd: {
5873 PrintOpcode(Inst);
5874 for (uint32_t i = 0; i < Ops.size(); i++) {
5875 out << " ";
5876 PrintOperand(Ops[i]);
5877 }
5878 out << "\n";
5879 break;
5880 }
5881 case spv::OpExtInstImport:
5882 case spv::OpTypeRuntimeArray:
5883 case spv::OpTypeStruct:
5884 case spv::OpTypeSampler:
5885 case spv::OpTypeSampledImage:
5886 case spv::OpTypeInt:
5887 case spv::OpTypeFloat:
5888 case spv::OpTypeArray:
5889 case spv::OpTypeVector:
5890 case spv::OpTypeBool:
5891 case spv::OpTypeVoid:
5892 case spv::OpTypeFunction:
5893 case spv::OpFunctionParameter:
5894 case spv::OpLabel:
5895 case spv::OpPhi:
5896 case spv::OpLoad:
5897 case spv::OpSelect:
5898 case spv::OpAccessChain:
5899 case spv::OpPtrAccessChain:
5900 case spv::OpInBoundsAccessChain:
5901 case spv::OpUConvert:
5902 case spv::OpSConvert:
5903 case spv::OpConvertFToU:
5904 case spv::OpConvertFToS:
5905 case spv::OpConvertUToF:
5906 case spv::OpConvertSToF:
5907 case spv::OpFConvert:
5908 case spv::OpConvertPtrToU:
5909 case spv::OpConvertUToPtr:
5910 case spv::OpBitcast:
5911 case spv::OpIAdd:
5912 case spv::OpFAdd:
5913 case spv::OpISub:
5914 case spv::OpFSub:
5915 case spv::OpIMul:
5916 case spv::OpFMul:
5917 case spv::OpUDiv:
5918 case spv::OpSDiv:
5919 case spv::OpFDiv:
5920 case spv::OpUMod:
5921 case spv::OpSRem:
5922 case spv::OpFRem:
Kévin Petit8a560882019-03-21 15:24:34 +00005923 case spv::OpUMulExtended:
5924 case spv::OpSMulExtended:
David Neto22f144c2017-06-12 14:26:21 -04005925 case spv::OpBitwiseOr:
5926 case spv::OpBitwiseXor:
5927 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005928 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005929 case spv::OpShiftLeftLogical:
5930 case spv::OpShiftRightLogical:
5931 case spv::OpShiftRightArithmetic:
5932 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04005933 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04005934 case spv::OpCompositeExtract:
5935 case spv::OpVectorExtractDynamic:
5936 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04005937 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04005938 case spv::OpVectorInsertDynamic:
5939 case spv::OpVectorShuffle:
5940 case spv::OpIEqual:
5941 case spv::OpINotEqual:
5942 case spv::OpUGreaterThan:
5943 case spv::OpUGreaterThanEqual:
5944 case spv::OpULessThan:
5945 case spv::OpULessThanEqual:
5946 case spv::OpSGreaterThan:
5947 case spv::OpSGreaterThanEqual:
5948 case spv::OpSLessThan:
5949 case spv::OpSLessThanEqual:
5950 case spv::OpFOrdEqual:
5951 case spv::OpFOrdGreaterThan:
5952 case spv::OpFOrdGreaterThanEqual:
5953 case spv::OpFOrdLessThan:
5954 case spv::OpFOrdLessThanEqual:
5955 case spv::OpFOrdNotEqual:
5956 case spv::OpFUnordEqual:
5957 case spv::OpFUnordGreaterThan:
5958 case spv::OpFUnordGreaterThanEqual:
5959 case spv::OpFUnordLessThan:
5960 case spv::OpFUnordLessThanEqual:
5961 case spv::OpFUnordNotEqual:
5962 case spv::OpSampledImage:
5963 case spv::OpFunctionCall:
5964 case spv::OpConstantTrue:
5965 case spv::OpConstantFalse:
5966 case spv::OpConstant:
5967 case spv::OpSpecConstant:
5968 case spv::OpConstantComposite:
5969 case spv::OpSpecConstantComposite:
5970 case spv::OpConstantNull:
5971 case spv::OpLogicalOr:
5972 case spv::OpLogicalAnd:
5973 case spv::OpLogicalNot:
5974 case spv::OpLogicalNotEqual:
5975 case spv::OpUndef:
5976 case spv::OpIsInf:
5977 case spv::OpIsNan:
5978 case spv::OpAny:
5979 case spv::OpAll:
David Neto5c22a252018-03-15 16:07:41 -04005980 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04005981 case spv::OpAtomicIAdd:
5982 case spv::OpAtomicISub:
5983 case spv::OpAtomicExchange:
5984 case spv::OpAtomicIIncrement:
5985 case spv::OpAtomicIDecrement:
5986 case spv::OpAtomicCompareExchange:
5987 case spv::OpAtomicUMin:
5988 case spv::OpAtomicSMin:
5989 case spv::OpAtomicUMax:
5990 case spv::OpAtomicSMax:
5991 case spv::OpAtomicAnd:
5992 case spv::OpAtomicOr:
5993 case spv::OpAtomicXor:
5994 case spv::OpDot: {
5995 PrintResID(Inst);
5996 out << " = ";
5997 PrintOpcode(Inst);
5998 for (uint32_t i = 0; i < Ops.size(); i++) {
5999 out << " ";
6000 PrintOperand(Ops[i]);
6001 }
6002 out << "\n";
6003 break;
6004 }
6005 }
6006 }
6007}
6008
6009void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04006010 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04006011}
6012
6013void SPIRVProducerPass::WriteResultID(SPIRVInstruction *Inst) {
6014 WriteOneWord(Inst->getResultID());
6015}
6016
6017void SPIRVProducerPass::WriteWordCountAndOpcode(SPIRVInstruction *Inst) {
6018 // High 16 bit : Word Count
6019 // Low 16 bit : Opcode
6020 uint32_t Word = Inst->getOpcode();
David Netoee2660d2018-06-28 16:31:29 -04006021 const uint32_t count = Inst->getWordCount();
6022 if (count > 65535) {
6023 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
6024 llvm_unreachable("Word count too high");
6025 }
David Neto22f144c2017-06-12 14:26:21 -04006026 Word |= Inst->getWordCount() << 16;
6027 WriteOneWord(Word);
6028}
6029
6030void SPIRVProducerPass::WriteOperand(SPIRVOperand *Op) {
6031 SPIRVOperandType OpTy = Op->getType();
6032 switch (OpTy) {
6033 default: {
6034 llvm_unreachable("Unsupported SPIRV Operand Type???");
6035 break;
6036 }
6037 case SPIRVOperandType::NUMBERID: {
6038 WriteOneWord(Op->getNumID());
6039 break;
6040 }
6041 case SPIRVOperandType::LITERAL_STRING: {
6042 std::string Str = Op->getLiteralStr();
6043 const char *Data = Str.c_str();
6044 size_t WordSize = Str.size() / 4;
6045 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
6046 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
6047 }
6048
6049 uint32_t Remainder = Str.size() % 4;
6050 uint32_t LastWord = 0;
6051 if (Remainder) {
6052 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
6053 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
6054 }
6055 }
6056
6057 WriteOneWord(LastWord);
6058 break;
6059 }
6060 case SPIRVOperandType::LITERAL_INTEGER:
6061 case SPIRVOperandType::LITERAL_FLOAT: {
6062 auto LiteralNum = Op->getLiteralNum();
6063 // TODO: Handle LiteranNum carefully.
6064 for (auto Word : LiteralNum) {
6065 WriteOneWord(Word);
6066 }
6067 break;
6068 }
6069 }
6070}
6071
6072void SPIRVProducerPass::WriteSPIRVBinary() {
6073 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
6074
6075 for (auto Inst : SPIRVInstList) {
David Netoc6f3ab22018-04-06 18:02:31 -04006076 SPIRVOperandList Ops{Inst->getOperands()};
David Neto22f144c2017-06-12 14:26:21 -04006077 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
6078
6079 switch (Opcode) {
6080 default: {
David Neto5c22a252018-03-15 16:07:41 -04006081 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04006082 llvm_unreachable("Unsupported SPIRV instruction");
6083 break;
6084 }
6085 case spv::OpCapability:
6086 case spv::OpExtension:
6087 case spv::OpMemoryModel:
6088 case spv::OpEntryPoint:
6089 case spv::OpExecutionMode:
6090 case spv::OpSource:
6091 case spv::OpDecorate:
6092 case spv::OpMemberDecorate:
6093 case spv::OpBranch:
6094 case spv::OpBranchConditional:
6095 case spv::OpSelectionMerge:
6096 case spv::OpLoopMerge:
6097 case spv::OpStore:
6098 case spv::OpImageWrite:
6099 case spv::OpReturnValue:
6100 case spv::OpControlBarrier:
6101 case spv::OpMemoryBarrier:
6102 case spv::OpReturn:
6103 case spv::OpFunctionEnd:
6104 case spv::OpCopyMemory: {
6105 WriteWordCountAndOpcode(Inst);
6106 for (uint32_t i = 0; i < Ops.size(); i++) {
6107 WriteOperand(Ops[i]);
6108 }
6109 break;
6110 }
6111 case spv::OpTypeBool:
6112 case spv::OpTypeVoid:
6113 case spv::OpTypeSampler:
6114 case spv::OpLabel:
6115 case spv::OpExtInstImport:
6116 case spv::OpTypePointer:
6117 case spv::OpTypeRuntimeArray:
6118 case spv::OpTypeStruct:
6119 case spv::OpTypeImage:
6120 case spv::OpTypeSampledImage:
6121 case spv::OpTypeInt:
6122 case spv::OpTypeFloat:
6123 case spv::OpTypeArray:
6124 case spv::OpTypeVector:
6125 case spv::OpTypeFunction: {
6126 WriteWordCountAndOpcode(Inst);
6127 WriteResultID(Inst);
6128 for (uint32_t i = 0; i < Ops.size(); i++) {
6129 WriteOperand(Ops[i]);
6130 }
6131 break;
6132 }
6133 case spv::OpFunction:
6134 case spv::OpFunctionParameter:
6135 case spv::OpAccessChain:
6136 case spv::OpPtrAccessChain:
6137 case spv::OpInBoundsAccessChain:
6138 case spv::OpUConvert:
6139 case spv::OpSConvert:
6140 case spv::OpConvertFToU:
6141 case spv::OpConvertFToS:
6142 case spv::OpConvertUToF:
6143 case spv::OpConvertSToF:
6144 case spv::OpFConvert:
6145 case spv::OpConvertPtrToU:
6146 case spv::OpConvertUToPtr:
6147 case spv::OpBitcast:
6148 case spv::OpIAdd:
6149 case spv::OpFAdd:
6150 case spv::OpISub:
6151 case spv::OpFSub:
6152 case spv::OpIMul:
6153 case spv::OpFMul:
6154 case spv::OpUDiv:
6155 case spv::OpSDiv:
6156 case spv::OpFDiv:
6157 case spv::OpUMod:
6158 case spv::OpSRem:
6159 case spv::OpFRem:
Kévin Petit8a560882019-03-21 15:24:34 +00006160 case spv::OpUMulExtended:
6161 case spv::OpSMulExtended:
David Neto22f144c2017-06-12 14:26:21 -04006162 case spv::OpBitwiseOr:
6163 case spv::OpBitwiseXor:
6164 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04006165 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04006166 case spv::OpShiftLeftLogical:
6167 case spv::OpShiftRightLogical:
6168 case spv::OpShiftRightArithmetic:
6169 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04006170 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04006171 case spv::OpCompositeExtract:
6172 case spv::OpVectorExtractDynamic:
6173 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04006174 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04006175 case spv::OpVectorInsertDynamic:
6176 case spv::OpVectorShuffle:
6177 case spv::OpIEqual:
6178 case spv::OpINotEqual:
6179 case spv::OpUGreaterThan:
6180 case spv::OpUGreaterThanEqual:
6181 case spv::OpULessThan:
6182 case spv::OpULessThanEqual:
6183 case spv::OpSGreaterThan:
6184 case spv::OpSGreaterThanEqual:
6185 case spv::OpSLessThan:
6186 case spv::OpSLessThanEqual:
6187 case spv::OpFOrdEqual:
6188 case spv::OpFOrdGreaterThan:
6189 case spv::OpFOrdGreaterThanEqual:
6190 case spv::OpFOrdLessThan:
6191 case spv::OpFOrdLessThanEqual:
6192 case spv::OpFOrdNotEqual:
6193 case spv::OpFUnordEqual:
6194 case spv::OpFUnordGreaterThan:
6195 case spv::OpFUnordGreaterThanEqual:
6196 case spv::OpFUnordLessThan:
6197 case spv::OpFUnordLessThanEqual:
6198 case spv::OpFUnordNotEqual:
6199 case spv::OpExtInst:
6200 case spv::OpIsInf:
6201 case spv::OpIsNan:
6202 case spv::OpAny:
6203 case spv::OpAll:
6204 case spv::OpUndef:
6205 case spv::OpConstantNull:
6206 case spv::OpLogicalOr:
6207 case spv::OpLogicalAnd:
6208 case spv::OpLogicalNot:
6209 case spv::OpLogicalNotEqual:
6210 case spv::OpConstantComposite:
6211 case spv::OpSpecConstantComposite:
6212 case spv::OpConstantTrue:
6213 case spv::OpConstantFalse:
6214 case spv::OpConstant:
6215 case spv::OpSpecConstant:
6216 case spv::OpVariable:
6217 case spv::OpFunctionCall:
6218 case spv::OpSampledImage:
6219 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04006220 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04006221 case spv::OpSelect:
6222 case spv::OpPhi:
6223 case spv::OpLoad:
6224 case spv::OpAtomicIAdd:
6225 case spv::OpAtomicISub:
6226 case spv::OpAtomicExchange:
6227 case spv::OpAtomicIIncrement:
6228 case spv::OpAtomicIDecrement:
6229 case spv::OpAtomicCompareExchange:
6230 case spv::OpAtomicUMin:
6231 case spv::OpAtomicSMin:
6232 case spv::OpAtomicUMax:
6233 case spv::OpAtomicSMax:
6234 case spv::OpAtomicAnd:
6235 case spv::OpAtomicOr:
6236 case spv::OpAtomicXor:
6237 case spv::OpDot: {
6238 WriteWordCountAndOpcode(Inst);
6239 WriteOperand(Ops[0]);
6240 WriteResultID(Inst);
6241 for (uint32_t i = 1; i < Ops.size(); i++) {
6242 WriteOperand(Ops[i]);
6243 }
6244 break;
6245 }
6246 }
6247 }
6248}
Alan Baker9bf93fb2018-08-28 16:59:26 -04006249
alan-bakerb6b09dc2018-11-08 16:59:28 -05006250bool SPIRVProducerPass::IsTypeNullable(const Type *type) const {
Alan Baker9bf93fb2018-08-28 16:59:26 -04006251 switch (type->getTypeID()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05006252 case Type::HalfTyID:
6253 case Type::FloatTyID:
6254 case Type::DoubleTyID:
6255 case Type::IntegerTyID:
6256 case Type::VectorTyID:
6257 return true;
6258 case Type::PointerTyID: {
6259 const PointerType *pointer_type = cast<PointerType>(type);
6260 if (pointer_type->getPointerAddressSpace() !=
6261 AddressSpace::UniformConstant) {
6262 auto pointee_type = pointer_type->getPointerElementType();
6263 if (pointee_type->isStructTy() &&
6264 cast<StructType>(pointee_type)->isOpaque()) {
6265 // Images and samplers are not nullable.
6266 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04006267 }
Alan Baker9bf93fb2018-08-28 16:59:26 -04006268 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05006269 return true;
6270 }
6271 case Type::ArrayTyID:
6272 return IsTypeNullable(cast<CompositeType>(type)->getTypeAtIndex(0u));
6273 case Type::StructTyID: {
6274 const StructType *struct_type = cast<StructType>(type);
6275 // Images and samplers are not nullable.
6276 if (struct_type->isOpaque())
Alan Baker9bf93fb2018-08-28 16:59:26 -04006277 return false;
alan-bakerb6b09dc2018-11-08 16:59:28 -05006278 for (const auto element : struct_type->elements()) {
6279 if (!IsTypeNullable(element))
6280 return false;
6281 }
6282 return true;
6283 }
6284 default:
6285 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04006286 }
6287}
Alan Bakerfcda9482018-10-02 17:09:59 -04006288
6289void SPIRVProducerPass::PopulateUBOTypeMaps(Module &module) {
6290 if (auto *offsets_md =
6291 module.getNamedMetadata(clspv::RemappedTypeOffsetMetadataName())) {
6292 // Metdata is stored as key-value pair operands. The first element of each
6293 // operand is the type and the second is a vector of offsets.
6294 for (const auto *operand : offsets_md->operands()) {
6295 const auto *pair = cast<MDTuple>(operand);
6296 auto *type =
6297 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
6298 const auto *offset_vector = cast<MDTuple>(pair->getOperand(1));
6299 std::vector<uint32_t> offsets;
6300 for (const Metadata *offset_md : offset_vector->operands()) {
6301 const auto *constant_md = cast<ConstantAsMetadata>(offset_md);
alan-bakerb6b09dc2018-11-08 16:59:28 -05006302 offsets.push_back(static_cast<uint32_t>(
6303 cast<ConstantInt>(constant_md->getValue())->getZExtValue()));
Alan Bakerfcda9482018-10-02 17:09:59 -04006304 }
6305 RemappedUBOTypeOffsets.insert(std::make_pair(type, offsets));
6306 }
6307 }
6308
6309 if (auto *sizes_md =
6310 module.getNamedMetadata(clspv::RemappedTypeSizesMetadataName())) {
6311 // Metadata is stored as key-value pair operands. The first element of each
6312 // operand is the type and the second is a triple of sizes: type size in
6313 // bits, store size and alloc size.
6314 for (const auto *operand : sizes_md->operands()) {
6315 const auto *pair = cast<MDTuple>(operand);
6316 auto *type =
6317 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
6318 const auto *size_triple = cast<MDTuple>(pair->getOperand(1));
6319 uint64_t type_size_in_bits =
6320 cast<ConstantInt>(
6321 cast<ConstantAsMetadata>(size_triple->getOperand(0))->getValue())
6322 ->getZExtValue();
6323 uint64_t type_store_size =
6324 cast<ConstantInt>(
6325 cast<ConstantAsMetadata>(size_triple->getOperand(1))->getValue())
6326 ->getZExtValue();
6327 uint64_t type_alloc_size =
6328 cast<ConstantInt>(
6329 cast<ConstantAsMetadata>(size_triple->getOperand(2))->getValue())
6330 ->getZExtValue();
6331 RemappedUBOTypeSizes.insert(std::make_pair(
6332 type, std::make_tuple(type_size_in_bits, type_store_size,
6333 type_alloc_size)));
6334 }
6335 }
6336}
6337
6338uint64_t SPIRVProducerPass::GetTypeSizeInBits(Type *type,
6339 const DataLayout &DL) {
6340 auto iter = RemappedUBOTypeSizes.find(type);
6341 if (iter != RemappedUBOTypeSizes.end()) {
6342 return std::get<0>(iter->second);
6343 }
6344
6345 return DL.getTypeSizeInBits(type);
6346}
6347
6348uint64_t SPIRVProducerPass::GetTypeStoreSize(Type *type, const DataLayout &DL) {
6349 auto iter = RemappedUBOTypeSizes.find(type);
6350 if (iter != RemappedUBOTypeSizes.end()) {
6351 return std::get<1>(iter->second);
6352 }
6353
6354 return DL.getTypeStoreSize(type);
6355}
6356
6357uint64_t SPIRVProducerPass::GetTypeAllocSize(Type *type, const DataLayout &DL) {
6358 auto iter = RemappedUBOTypeSizes.find(type);
6359 if (iter != RemappedUBOTypeSizes.end()) {
6360 return std::get<2>(iter->second);
6361 }
6362
6363 return DL.getTypeAllocSize(type);
6364}
alan-baker5b86ed72019-02-15 08:26:50 -05006365
6366void SPIRVProducerPass::setVariablePointersCapabilities(unsigned address_space) {
6367 if (GetStorageClass(address_space) == spv::StorageClassStorageBuffer) {
6368 setVariablePointersStorageBuffer(true);
6369 } else {
6370 setVariablePointers(true);
6371 }
6372}
6373
6374Value *SPIRVProducerPass::GetBasePointer(Value* v) {
6375 if (auto *gep = dyn_cast<GetElementPtrInst>(v)) {
6376 return GetBasePointer(gep->getPointerOperand());
6377 }
6378
6379 // Conservatively return |v|.
6380 return v;
6381}
6382
6383bool SPIRVProducerPass::sameResource(Value *lhs, Value *rhs) const {
6384 if (auto *lhs_call = dyn_cast<CallInst>(lhs)) {
6385 if (auto *rhs_call = dyn_cast<CallInst>(rhs)) {
6386 if (lhs_call->getCalledFunction()->getName().startswith(
6387 clspv::ResourceAccessorFunction()) &&
6388 rhs_call->getCalledFunction()->getName().startswith(
6389 clspv::ResourceAccessorFunction())) {
6390 // For resource accessors, match descriptor set and binding.
6391 if (lhs_call->getOperand(0) == rhs_call->getOperand(0) &&
6392 lhs_call->getOperand(1) == rhs_call->getOperand(1))
6393 return true;
6394 } else if (lhs_call->getCalledFunction()->getName().startswith(
6395 clspv::WorkgroupAccessorFunction()) &&
6396 rhs_call->getCalledFunction()->getName().startswith(
6397 clspv::WorkgroupAccessorFunction())) {
6398 // For workgroup resources, match spec id.
6399 if (lhs_call->getOperand(0) == rhs_call->getOperand(0))
6400 return true;
6401 }
6402 }
6403 }
6404
6405 return false;
6406}
6407
6408bool SPIRVProducerPass::selectFromSameObject(Instruction *inst) {
6409 assert(inst->getType()->isPointerTy());
6410 assert(GetStorageClass(inst->getType()->getPointerAddressSpace()) ==
6411 spv::StorageClassStorageBuffer);
6412 const bool hack_undef = clspv::Option::HackUndef();
6413 if (auto *select = dyn_cast<SelectInst>(inst)) {
6414 auto *true_base = GetBasePointer(select->getTrueValue());
6415 auto *false_base = GetBasePointer(select->getFalseValue());
6416
6417 if (true_base == false_base)
6418 return true;
6419
6420 // If either the true or false operand is a null, then we satisfy the same
6421 // object constraint.
6422 if (auto *true_cst = dyn_cast<Constant>(true_base)) {
6423 if (true_cst->isNullValue() || (hack_undef && isa<UndefValue>(true_base)))
6424 return true;
6425 }
6426
6427 if (auto *false_cst = dyn_cast<Constant>(false_base)) {
6428 if (false_cst->isNullValue() ||
6429 (hack_undef && isa<UndefValue>(false_base)))
6430 return true;
6431 }
6432
6433 if (sameResource(true_base, false_base))
6434 return true;
6435 } else if (auto *phi = dyn_cast<PHINode>(inst)) {
6436 Value *value = nullptr;
6437 bool ok = true;
6438 for (unsigned i = 0; ok && i != phi->getNumIncomingValues(); ++i) {
6439 auto *base = GetBasePointer(phi->getIncomingValue(i));
6440 // Null values satisfy the constraint of selecting of selecting from the
6441 // same object.
6442 if (!value) {
6443 if (auto *cst = dyn_cast<Constant>(base)) {
6444 if (!cst->isNullValue() && !(hack_undef && isa<UndefValue>(base)))
6445 value = base;
6446 } else {
6447 value = base;
6448 }
6449 } else if (base != value) {
6450 if (auto *base_cst = dyn_cast<Constant>(base)) {
6451 if (base_cst->isNullValue() || (hack_undef && isa<UndefValue>(base)))
6452 continue;
6453 }
6454
6455 if (sameResource(value, base))
6456 continue;
6457
6458 // Values don't represent the same base.
6459 ok = false;
6460 }
6461 }
6462
6463 return ok;
6464 }
6465
6466 // Conservatively return false.
6467 return false;
6468}
alan-bakere9308012019-03-15 10:25:13 -04006469
6470bool SPIRVProducerPass::CalledWithCoherentResource(Argument &Arg) {
6471 if (!Arg.getType()->isPointerTy() ||
6472 Arg.getType()->getPointerAddressSpace() != clspv::AddressSpace::Global) {
6473 // Only SSBOs need to be annotated as coherent.
6474 return false;
6475 }
6476
6477 DenseSet<Value *> visited;
6478 std::vector<Value *> stack;
6479 for (auto *U : Arg.getParent()->users()) {
6480 if (auto *call = dyn_cast<CallInst>(U)) {
6481 stack.push_back(call->getOperand(Arg.getArgNo()));
6482 }
6483 }
6484
6485 while (!stack.empty()) {
6486 Value *v = stack.back();
6487 stack.pop_back();
6488
6489 if (!visited.insert(v).second)
6490 continue;
6491
6492 auto *resource_call = dyn_cast<CallInst>(v);
6493 if (resource_call &&
6494 resource_call->getCalledFunction()->getName().startswith(
6495 clspv::ResourceAccessorFunction())) {
6496 // If this is a resource accessor function, check if the coherent operand
6497 // is set.
6498 const auto coherent =
6499 unsigned(dyn_cast<ConstantInt>(resource_call->getArgOperand(5))
6500 ->getZExtValue());
6501 if (coherent == 1)
6502 return true;
6503 } else if (auto *arg = dyn_cast<Argument>(v)) {
6504 // If this is a function argument, trace through its callers.
6505 for (auto U : arg->users()) {
6506 if (auto *call = dyn_cast<CallInst>(U)) {
6507 stack.push_back(call->getOperand(arg->getArgNo()));
6508 }
6509 }
6510 } else if (auto *user = dyn_cast<User>(v)) {
6511 // If this is a user, traverse all operands that could lead to resource
6512 // variables.
6513 for (unsigned i = 0; i != user->getNumOperands(); ++i) {
6514 Value *operand = user->getOperand(i);
6515 if (operand->getType()->isPointerTy() &&
6516 operand->getType()->getPointerAddressSpace() ==
6517 clspv::AddressSpace::Global) {
6518 stack.push_back(operand);
6519 }
6520 }
6521 }
6522 }
6523
6524 // No coherent resource variables encountered.
6525 return false;
6526}