blob: 5d31d6b751961f5b261211970f5d83ad229640d4 [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 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400286 bool hasVariablePointers() { return HasVariablePointers; };
David Neto22f144c2017-06-12 14:26:21 -0400287 void setVariablePointers(bool Val) { HasVariablePointers = Val; };
alan-bakerb6b09dc2018-11-08 16:59:28 -0500288 ArrayRef<std::pair<unsigned, std::string>> &getSamplerMap() {
289 return samplerMap;
290 }
David Neto22f144c2017-06-12 14:26:21 -0400291 GlobalConstFuncMapType &getGlobalConstFuncTypeMap() {
292 return GlobalConstFuncTypeMap;
293 }
294 SmallPtrSet<Value *, 16> &getGlobalConstArgSet() {
295 return GlobalConstArgumentSet;
296 }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500297 TypeList &getTypesNeedingArrayStride() { return TypesNeedingArrayStride; }
David Neto22f144c2017-06-12 14:26:21 -0400298
David Netoc6f3ab22018-04-06 18:02:31 -0400299 void GenerateLLVMIRInfo(Module &M, const DataLayout &DL);
alan-bakerb6b09dc2018-11-08 16:59:28 -0500300 // Populate GlobalConstFuncTypeMap. Also, if module-scope __constant will
301 // *not* be converted to a storage buffer, replace each such global variable
302 // with one in the storage class expecgted by SPIR-V.
David Neto862b7d82018-06-14 18:48:37 -0400303 void FindGlobalConstVars(Module &M, const DataLayout &DL);
304 // Populate ResourceVarInfoList, FunctionToResourceVarsMap, and
305 // ModuleOrderedResourceVars.
306 void FindResourceVars(Module &M, const DataLayout &DL);
Alan Baker202c8c72018-08-13 13:47:44 -0400307 void FindWorkgroupVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400308 bool FindExtInst(Module &M);
309 void FindTypePerGlobalVar(GlobalVariable &GV);
310 void FindTypePerFunc(Function &F);
David Neto862b7d82018-06-14 18:48:37 -0400311 void FindTypesForSamplerMap(Module &M);
312 void FindTypesForResourceVars(Module &M);
alan-bakerb6b09dc2018-11-08 16:59:28 -0500313 // Inserts |Ty| and relevant sub-types into the |Types| member, indicating
314 // that |Ty| and its subtypes will need a corresponding SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400315 void FindType(Type *Ty);
316 void FindConstantPerGlobalVar(GlobalVariable &GV);
317 void FindConstantPerFunc(Function &F);
318 void FindConstant(Value *V);
319 void GenerateExtInstImport();
David Neto19a1bad2017-08-25 15:01:41 -0400320 // Generates instructions for SPIR-V types corresponding to the LLVM types
321 // saved in the |Types| member. A type follows its subtypes. IDs are
322 // allocated sequentially starting with the current value of nextID, and
323 // with a type following its subtypes. Also updates nextID to just beyond
324 // the last generated ID.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500325 void GenerateSPIRVTypes(LLVMContext &context, Module &module);
David Neto22f144c2017-06-12 14:26:21 -0400326 void GenerateSPIRVConstants();
David Neto5c22a252018-03-15 16:07:41 -0400327 void GenerateModuleInfo(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400328 void GenerateGlobalVar(GlobalVariable &GV);
David Netoc6f3ab22018-04-06 18:02:31 -0400329 void GenerateWorkgroupVars();
David Neto862b7d82018-06-14 18:48:37 -0400330 // Generate descriptor map entries for resource variables associated with
331 // arguments to F.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500332 void GenerateDescriptorMapInfo(const DataLayout &DL, Function &F);
David Neto22f144c2017-06-12 14:26:21 -0400333 void GenerateSamplers(Module &M);
David Neto862b7d82018-06-14 18:48:37 -0400334 // Generate OpVariables for %clspv.resource.var.* calls.
335 void GenerateResourceVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400336 void GenerateFuncPrologue(Function &F);
337 void GenerateFuncBody(Function &F);
David Netob6e2e062018-04-25 10:32:06 -0400338 void GenerateEntryPointInitialStores();
David Neto22f144c2017-06-12 14:26:21 -0400339 spv::Op GetSPIRVCmpOpcode(CmpInst *CmpI);
340 spv::Op GetSPIRVCastOpcode(Instruction &I);
341 spv::Op GetSPIRVBinaryOpcode(Instruction &I);
342 void GenerateInstruction(Instruction &I);
343 void GenerateFuncEpilogue();
344 void HandleDeferredInstruction();
alan-bakerb6b09dc2018-11-08 16:59:28 -0500345 void HandleDeferredDecorations(const DataLayout &DL);
David Neto22f144c2017-06-12 14:26:21 -0400346 bool is4xi8vec(Type *Ty) const;
David Neto257c3892018-04-11 13:19:45 -0400347 // Return the SPIR-V Id for 32-bit constant zero. The constant must already
348 // have been created.
349 uint32_t GetI32Zero();
David Neto22f144c2017-06-12 14:26:21 -0400350 spv::StorageClass GetStorageClass(unsigned AddrSpace) const;
David Neto862b7d82018-06-14 18:48:37 -0400351 spv::StorageClass GetStorageClassForArgKind(clspv::ArgKind arg_kind) const;
David Neto22f144c2017-06-12 14:26:21 -0400352 spv::BuiltIn GetBuiltin(StringRef globalVarName) const;
David Neto3fbb4072017-10-16 11:28:14 -0400353 // Returns the GLSL extended instruction enum that the given function
354 // call maps to. If none, then returns the 0 value, i.e. GLSLstd4580Bad.
David Neto22f144c2017-06-12 14:26:21 -0400355 glsl::ExtInst getExtInstEnum(StringRef Name);
David Neto3fbb4072017-10-16 11:28:14 -0400356 // Returns the GLSL extended instruction enum indirectly used by the given
357 // function. That is, to implement the given function, we use an extended
358 // instruction plus one more instruction. If none, then returns the 0 value,
359 // i.e. GLSLstd4580Bad.
360 glsl::ExtInst getIndirectExtInstEnum(StringRef Name);
361 // Returns the single GLSL extended instruction used directly or
362 // indirectly by the given function call.
363 glsl::ExtInst getDirectOrIndirectExtInstEnum(StringRef Name);
David Neto22f144c2017-06-12 14:26:21 -0400364 void PrintResID(SPIRVInstruction *Inst);
365 void PrintOpcode(SPIRVInstruction *Inst);
366 void PrintOperand(SPIRVOperand *Op);
367 void PrintCapability(SPIRVOperand *Op);
368 void PrintExtInst(SPIRVOperand *Op);
369 void PrintAddrModel(SPIRVOperand *Op);
370 void PrintMemModel(SPIRVOperand *Op);
371 void PrintExecModel(SPIRVOperand *Op);
372 void PrintExecMode(SPIRVOperand *Op);
373 void PrintSourceLanguage(SPIRVOperand *Op);
374 void PrintFuncCtrl(SPIRVOperand *Op);
375 void PrintStorageClass(SPIRVOperand *Op);
376 void PrintDecoration(SPIRVOperand *Op);
377 void PrintBuiltIn(SPIRVOperand *Op);
378 void PrintSelectionControl(SPIRVOperand *Op);
379 void PrintLoopControl(SPIRVOperand *Op);
380 void PrintDimensionality(SPIRVOperand *Op);
381 void PrintImageFormat(SPIRVOperand *Op);
382 void PrintMemoryAccess(SPIRVOperand *Op);
383 void PrintImageOperandsType(SPIRVOperand *Op);
384 void WriteSPIRVAssembly();
385 void WriteOneWord(uint32_t Word);
386 void WriteResultID(SPIRVInstruction *Inst);
387 void WriteWordCountAndOpcode(SPIRVInstruction *Inst);
388 void WriteOperand(SPIRVOperand *Op);
389 void WriteSPIRVBinary();
390
Alan Baker9bf93fb2018-08-28 16:59:26 -0400391 // Returns true if |type| is compatible with OpConstantNull.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500392 bool IsTypeNullable(const Type *type) const;
Alan Baker9bf93fb2018-08-28 16:59:26 -0400393
Alan Bakerfcda9482018-10-02 17:09:59 -0400394 // Populate UBO remapped type maps.
395 void PopulateUBOTypeMaps(Module &module);
396
397 // Wrapped methods of DataLayout accessors. If |type| was remapped for UBOs,
398 // uses the internal map, otherwise it falls back on the data layout.
399 uint64_t GetTypeSizeInBits(Type *type, const DataLayout &DL);
400 uint64_t GetTypeStoreSize(Type *type, const DataLayout &DL);
401 uint64_t GetTypeAllocSize(Type *type, const DataLayout &DL);
402
alan-baker5b86ed72019-02-15 08:26:50 -0500403 // Returns the base pointer of |v|.
404 Value *GetBasePointer(Value *v);
405
406 // Sets |HasVariablePointersStorageBuffer| or |HasVariablePointers| base on
407 // |address_space|.
408 void setVariablePointersCapabilities(unsigned address_space);
409
410 // Returns true if |lhs| and |rhs| represent the same resource or workgroup
411 // variable.
412 bool sameResource(Value *lhs, Value *rhs) const;
413
414 // Returns true if |inst| is phi or select that selects from the same
415 // structure (or null).
416 bool selectFromSameObject(Instruction *inst);
417
alan-bakere9308012019-03-15 10:25:13 -0400418 // Returns true if |Arg| is called with a coherent resource.
419 bool CalledWithCoherentResource(Argument &Arg);
420
David Neto22f144c2017-06-12 14:26:21 -0400421private:
422 static char ID;
David Neto44795152017-07-13 15:45:28 -0400423 ArrayRef<std::pair<unsigned, std::string>> samplerMap;
David Neto22f144c2017-06-12 14:26:21 -0400424 raw_pwrite_stream &out;
David Neto0676e6f2017-07-11 18:47:44 -0400425
426 // TODO(dneto): Wouldn't it be better to always just emit a binary, and then
427 // convert to other formats on demand?
428
429 // When emitting a C initialization list, the WriteSPIRVBinary method
430 // will actually write its words to this vector via binaryTempOut.
431 SmallVector<char, 100> binaryTempUnderlyingVector;
432 raw_svector_ostream binaryTempOut;
433
434 // Binary output writes to this stream, which might be |out| or
435 // |binaryTempOut|. It's the latter when we really want to write a C
436 // initializer list.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400437 raw_pwrite_stream *binaryOut;
alan-bakerf5e5f692018-11-27 08:33:24 -0500438 std::vector<version0::DescriptorMapEntry> *descriptorMapEntries;
David Neto22f144c2017-06-12 14:26:21 -0400439 const bool outputAsm;
David Neto0676e6f2017-07-11 18:47:44 -0400440 const bool outputCInitList; // If true, output look like {0x7023, ... , 5}
David Neto22f144c2017-06-12 14:26:21 -0400441 uint64_t patchBoundOffset;
442 uint32_t nextID;
443
David Neto19a1bad2017-08-25 15:01:41 -0400444 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400445 TypeMapType TypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400446 // Maps an LLVM image type to its SPIR-V ID.
David Neto22f144c2017-06-12 14:26:21 -0400447 TypeMapType ImageTypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400448 // A unique-vector of LLVM types that map to a SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400449 TypeList Types;
450 ValueList Constants;
David Neto19a1bad2017-08-25 15:01:41 -0400451 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400452 ValueMapType ValueMap;
453 ValueMapType AllocatedValueMap;
454 SPIRVInstructionList SPIRVInsts;
David Neto862b7d82018-06-14 18:48:37 -0400455
David Neto22f144c2017-06-12 14:26:21 -0400456 EntryPointVecType EntryPointVec;
457 DeferredInstVecType DeferredInstVec;
458 ValueList EntryPointInterfacesVec;
459 uint32_t OpExtInstImportID;
460 std::vector<uint32_t> BuiltinDimensionVec;
alan-baker5b86ed72019-02-15 08:26:50 -0500461 bool HasVariablePointersStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -0400462 bool HasVariablePointers;
463 Type *SamplerTy;
alan-bakerb6b09dc2018-11-08 16:59:28 -0500464 DenseMap<unsigned, uint32_t> SamplerMapIndexToIDMap;
David Netoc77d9e22018-03-24 06:30:28 -0700465
466 // If a function F has a pointer-to-__constant parameter, then this variable
David Neto9ed8e2f2018-03-24 06:47:24 -0700467 // will map F's type to (G, index of the parameter), where in a first phase
468 // G is F's type. During FindTypePerFunc, G will be changed to F's type
469 // but replacing the pointer-to-constant parameter with
470 // pointer-to-ModuleScopePrivate.
David Netoc77d9e22018-03-24 06:30:28 -0700471 // TODO(dneto): This doesn't seem general enough? A function might have
472 // more than one such parameter.
David Neto22f144c2017-06-12 14:26:21 -0400473 GlobalConstFuncMapType GlobalConstFuncTypeMap;
474 SmallPtrSet<Value *, 16> GlobalConstArgumentSet;
David Neto1a1a0582017-07-07 12:01:44 -0400475 // An ordered set of pointer types of Base arguments to OpPtrAccessChain,
David Neto85082642018-03-24 06:55:20 -0700476 // or array types, and which point into transparent memory (StorageBuffer
477 // storage class). These will require an ArrayStride decoration.
David Neto1a1a0582017-07-07 12:01:44 -0400478 // See SPV_KHR_variable_pointers rev 13.
David Neto85082642018-03-24 06:55:20 -0700479 TypeList TypesNeedingArrayStride;
David Netoa60b00b2017-09-15 16:34:09 -0400480
481 // This is truly ugly, but works around what look like driver bugs.
482 // For get_local_size, an earlier part of the flow has created a module-scope
483 // variable in Private address space to hold the value for the workgroup
484 // size. Its intializer is a uint3 value marked as builtin WorkgroupSize.
485 // When this is present, save the IDs of the initializer value and variable
486 // in these two variables. We only ever do a vector load from it, and
487 // when we see one of those, substitute just the value of the intializer.
488 // This mimics what Glslang does, and that's what drivers are used to.
David Neto66cfe642018-03-24 06:13:56 -0700489 // TODO(dneto): Remove this once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -0400490 uint32_t WorkgroupSizeValueID;
491 uint32_t WorkgroupSizeVarID;
David Neto26aaf622017-10-23 18:11:53 -0400492
David Neto862b7d82018-06-14 18:48:37 -0400493 // Bookkeeping for mapping kernel arguments to resource variables.
494 struct ResourceVarInfo {
495 ResourceVarInfo(int index_arg, unsigned set_arg, unsigned binding_arg,
alan-bakere9308012019-03-15 10:25:13 -0400496 Function *fn, clspv::ArgKind arg_kind_arg, int coherent_arg)
David Neto862b7d82018-06-14 18:48:37 -0400497 : index(index_arg), descriptor_set(set_arg), binding(binding_arg),
alan-bakere9308012019-03-15 10:25:13 -0400498 var_fn(fn), arg_kind(arg_kind_arg), coherent(coherent_arg),
David Neto862b7d82018-06-14 18:48:37 -0400499 addr_space(fn->getReturnType()->getPointerAddressSpace()) {}
500 const int index; // Index into ResourceVarInfoList
501 const unsigned descriptor_set;
502 const unsigned binding;
503 Function *const var_fn; // The @clspv.resource.var.* function.
504 const clspv::ArgKind arg_kind;
alan-bakere9308012019-03-15 10:25:13 -0400505 const int coherent;
David Neto862b7d82018-06-14 18:48:37 -0400506 const unsigned addr_space; // The LLVM address space
507 // The SPIR-V ID of the OpVariable. Not populated at construction time.
508 uint32_t var_id = 0;
509 };
510 // A list of resource var info. Each one correponds to a module-scope
511 // resource variable we will have to create. Resource var indices are
512 // indices into this vector.
513 SmallVector<std::unique_ptr<ResourceVarInfo>, 8> ResourceVarInfoList;
514 // This is a vector of pointers of all the resource vars, but ordered by
515 // kernel function, and then by argument.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500516 UniqueVector<ResourceVarInfo *> ModuleOrderedResourceVars;
David Neto862b7d82018-06-14 18:48:37 -0400517 // Map a function to the ordered list of resource variables it uses, one for
518 // each argument. If an argument does not use a resource variable, it
519 // will have a null pointer entry.
520 using FunctionToResourceVarsMapType =
521 DenseMap<Function *, SmallVector<ResourceVarInfo *, 8>>;
522 FunctionToResourceVarsMapType FunctionToResourceVarsMap;
523
524 // What LLVM types map to SPIR-V types needing layout? These are the
525 // arrays and structures supporting storage buffers and uniform buffers.
526 TypeList TypesNeedingLayout;
527 // What LLVM struct types map to a SPIR-V struct type with Block decoration?
528 UniqueVector<StructType *> StructTypesNeedingBlock;
529 // For a call that represents a load from an opaque type (samplers, images),
530 // map it to the variable id it should load from.
531 DenseMap<CallInst *, uint32_t> ResourceVarDeferredLoadCalls;
David Neto85082642018-03-24 06:55:20 -0700532
Alan Baker202c8c72018-08-13 13:47:44 -0400533 // One larger than the maximum used SpecId for pointer-to-local arguments.
534 int max_local_spec_id_;
David Netoc6f3ab22018-04-06 18:02:31 -0400535 // An ordered list of the kernel arguments of type pointer-to-local.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500536 using LocalArgList = SmallVector<Argument *, 8>;
David Netoc6f3ab22018-04-06 18:02:31 -0400537 LocalArgList LocalArgs;
538 // Information about a pointer-to-local argument.
539 struct LocalArgInfo {
540 // The SPIR-V ID of the array variable.
541 uint32_t variable_id;
542 // The element type of the
alan-bakerb6b09dc2018-11-08 16:59:28 -0500543 Type *elem_type;
David Netoc6f3ab22018-04-06 18:02:31 -0400544 // The ID of the array type.
545 uint32_t array_size_id;
546 // The ID of the array type.
547 uint32_t array_type_id;
548 // The ID of the pointer to the array type.
549 uint32_t ptr_array_type_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400550 // The specialization constant ID of the array size.
551 int spec_id;
552 };
Alan Baker202c8c72018-08-13 13:47:44 -0400553 // A mapping from Argument to its assigned SpecId.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500554 DenseMap<const Argument *, int> LocalArgSpecIds;
Alan Baker202c8c72018-08-13 13:47:44 -0400555 // A mapping from SpecId to its LocalArgInfo.
556 DenseMap<int, LocalArgInfo> LocalSpecIdInfoMap;
Alan Bakerfcda9482018-10-02 17:09:59 -0400557 // A mapping from a remapped type to its real offsets.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500558 DenseMap<Type *, std::vector<uint32_t>> RemappedUBOTypeOffsets;
Alan Bakerfcda9482018-10-02 17:09:59 -0400559 // A mapping from a remapped type to its real sizes.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500560 DenseMap<Type *, std::tuple<uint64_t, uint64_t, uint64_t>>
561 RemappedUBOTypeSizes;
David Neto257c3892018-04-11 13:19:45 -0400562
563 // The ID of 32-bit integer zero constant. This is only valid after
564 // GenerateSPIRVConstants has run.
565 uint32_t constant_i32_zero_id_;
David Neto22f144c2017-06-12 14:26:21 -0400566};
567
568char SPIRVProducerPass::ID;
David Netoc6f3ab22018-04-06 18:02:31 -0400569
alan-bakerb6b09dc2018-11-08 16:59:28 -0500570} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400571
572namespace clspv {
alan-bakerf5e5f692018-11-27 08:33:24 -0500573ModulePass *createSPIRVProducerPass(
574 raw_pwrite_stream &out,
575 std::vector<version0::DescriptorMapEntry> *descriptor_map_entries,
576 ArrayRef<std::pair<unsigned, std::string>> samplerMap, bool outputAsm,
577 bool outputCInitList) {
578 return new SPIRVProducerPass(out, descriptor_map_entries, samplerMap,
579 outputAsm, outputCInitList);
David Neto22f144c2017-06-12 14:26:21 -0400580}
David Netoc2c368d2017-06-30 16:50:17 -0400581} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400582
583bool SPIRVProducerPass::runOnModule(Module &module) {
David Neto0676e6f2017-07-11 18:47:44 -0400584 binaryOut = outputCInitList ? &binaryTempOut : &out;
585
David Neto257c3892018-04-11 13:19:45 -0400586 constant_i32_zero_id_ = 0; // Reset, for the benefit of validity checks.
587
Alan Bakerfcda9482018-10-02 17:09:59 -0400588 PopulateUBOTypeMaps(module);
589
David Neto22f144c2017-06-12 14:26:21 -0400590 // SPIR-V always begins with its header information
591 outputHeader();
592
David Netoc6f3ab22018-04-06 18:02:31 -0400593 const DataLayout &DL = module.getDataLayout();
594
David Neto22f144c2017-06-12 14:26:21 -0400595 // Gather information from the LLVM IR that we require.
David Netoc6f3ab22018-04-06 18:02:31 -0400596 GenerateLLVMIRInfo(module, DL);
David Neto22f144c2017-06-12 14:26:21 -0400597
David Neto22f144c2017-06-12 14:26:21 -0400598 // Collect information on global variables too.
599 for (GlobalVariable &GV : module.globals()) {
600 // If the GV is one of our special __spirv_* variables, remove the
601 // initializer as it was only placed there to force LLVM to not throw the
602 // value away.
603 if (GV.getName().startswith("__spirv_")) {
604 GV.setInitializer(nullptr);
605 }
606
607 // Collect types' information from global variable.
608 FindTypePerGlobalVar(GV);
609
610 // Collect constant information from global variable.
611 FindConstantPerGlobalVar(GV);
612
613 // If the variable is an input, entry points need to know about it.
614 if (AddressSpace::Input == GV.getType()->getPointerAddressSpace()) {
David Netofb9a7972017-08-25 17:08:24 -0400615 getEntryPointInterfacesVec().insert(&GV);
David Neto22f144c2017-06-12 14:26:21 -0400616 }
617 }
618
619 // If there are extended instructions, generate OpExtInstImport.
620 if (FindExtInst(module)) {
621 GenerateExtInstImport();
622 }
623
624 // Generate SPIRV instructions for types.
Alan Bakerfcda9482018-10-02 17:09:59 -0400625 GenerateSPIRVTypes(module.getContext(), module);
David Neto22f144c2017-06-12 14:26:21 -0400626
627 // Generate SPIRV constants.
628 GenerateSPIRVConstants();
629
630 // If we have a sampler map, we might have literal samplers to generate.
631 if (0 < getSamplerMap().size()) {
632 GenerateSamplers(module);
633 }
634
635 // Generate SPIRV variables.
636 for (GlobalVariable &GV : module.globals()) {
637 GenerateGlobalVar(GV);
638 }
David Neto862b7d82018-06-14 18:48:37 -0400639 GenerateResourceVars(module);
David Netoc6f3ab22018-04-06 18:02:31 -0400640 GenerateWorkgroupVars();
David Neto22f144c2017-06-12 14:26:21 -0400641
642 // Generate SPIRV instructions for each function.
643 for (Function &F : module) {
644 if (F.isDeclaration()) {
645 continue;
646 }
647
David Neto862b7d82018-06-14 18:48:37 -0400648 GenerateDescriptorMapInfo(DL, F);
649
David Neto22f144c2017-06-12 14:26:21 -0400650 // Generate Function Prologue.
651 GenerateFuncPrologue(F);
652
653 // Generate SPIRV instructions for function body.
654 GenerateFuncBody(F);
655
656 // Generate Function Epilogue.
657 GenerateFuncEpilogue();
658 }
659
660 HandleDeferredInstruction();
David Neto1a1a0582017-07-07 12:01:44 -0400661 HandleDeferredDecorations(DL);
David Neto22f144c2017-06-12 14:26:21 -0400662
663 // Generate SPIRV module information.
David Neto5c22a252018-03-15 16:07:41 -0400664 GenerateModuleInfo(module);
David Neto22f144c2017-06-12 14:26:21 -0400665
666 if (outputAsm) {
667 WriteSPIRVAssembly();
668 } else {
669 WriteSPIRVBinary();
670 }
671
672 // We need to patch the SPIR-V header to set bound correctly.
673 patchHeader();
David Neto0676e6f2017-07-11 18:47:44 -0400674
675 if (outputCInitList) {
676 bool first = true;
David Neto0676e6f2017-07-11 18:47:44 -0400677 std::ostringstream os;
678
David Neto57fb0b92017-08-04 15:35:09 -0400679 auto emit_word = [&os, &first](uint32_t word) {
David Neto0676e6f2017-07-11 18:47:44 -0400680 if (!first)
David Neto57fb0b92017-08-04 15:35:09 -0400681 os << ",\n";
682 os << word;
David Neto0676e6f2017-07-11 18:47:44 -0400683 first = false;
684 };
685
686 os << "{";
David Neto57fb0b92017-08-04 15:35:09 -0400687 const std::string str(binaryTempOut.str());
688 for (unsigned i = 0; i < str.size(); i += 4) {
689 const uint32_t a = static_cast<unsigned char>(str[i]);
690 const uint32_t b = static_cast<unsigned char>(str[i + 1]);
691 const uint32_t c = static_cast<unsigned char>(str[i + 2]);
692 const uint32_t d = static_cast<unsigned char>(str[i + 3]);
693 emit_word(a | (b << 8) | (c << 16) | (d << 24));
David Neto0676e6f2017-07-11 18:47:44 -0400694 }
695 os << "}\n";
696 out << os.str();
697 }
698
David Neto22f144c2017-06-12 14:26:21 -0400699 return false;
700}
701
702void SPIRVProducerPass::outputHeader() {
703 if (outputAsm) {
704 // for ASM output the header goes into 5 comments at the beginning of the
705 // file
706 out << "; SPIR-V\n";
707
708 // the major version number is in the 2nd highest byte
709 const uint32_t major = (spv::Version >> 16) & 0xFF;
710
711 // the minor version number is in the 2nd lowest byte
712 const uint32_t minor = (spv::Version >> 8) & 0xFF;
713 out << "; Version: " << major << "." << minor << "\n";
714
715 // use Codeplay's vendor ID
716 out << "; Generator: Codeplay; 0\n";
717
718 out << "; Bound: ";
719
720 // we record where we need to come back to and patch in the bound value
721 patchBoundOffset = out.tell();
722
723 // output one space per digit for the max size of a 32 bit unsigned integer
724 // (which is the maximum ID we could possibly be using)
725 for (uint32_t i = std::numeric_limits<uint32_t>::max(); 0 != i; i /= 10) {
726 out << " ";
727 }
728
729 out << "\n";
730
731 out << "; Schema: 0\n";
732 } else {
David Neto0676e6f2017-07-11 18:47:44 -0400733 binaryOut->write(reinterpret_cast<const char *>(&spv::MagicNumber),
alan-bakerb6b09dc2018-11-08 16:59:28 -0500734 sizeof(spv::MagicNumber));
David Neto0676e6f2017-07-11 18:47:44 -0400735 binaryOut->write(reinterpret_cast<const char *>(&spv::Version),
alan-bakerb6b09dc2018-11-08 16:59:28 -0500736 sizeof(spv::Version));
David Neto22f144c2017-06-12 14:26:21 -0400737
738 // use Codeplay's vendor ID
739 const uint32_t vendor = 3 << 16;
David Neto0676e6f2017-07-11 18:47:44 -0400740 binaryOut->write(reinterpret_cast<const char *>(&vendor), sizeof(vendor));
David Neto22f144c2017-06-12 14:26:21 -0400741
742 // we record where we need to come back to and patch in the bound value
David Neto0676e6f2017-07-11 18:47:44 -0400743 patchBoundOffset = binaryOut->tell();
David Neto22f144c2017-06-12 14:26:21 -0400744
745 // output a bad bound for now
David Neto0676e6f2017-07-11 18:47:44 -0400746 binaryOut->write(reinterpret_cast<const char *>(&nextID), sizeof(nextID));
David Neto22f144c2017-06-12 14:26:21 -0400747
748 // output the schema (reserved for use and must be 0)
749 const uint32_t schema = 0;
David Neto0676e6f2017-07-11 18:47:44 -0400750 binaryOut->write(reinterpret_cast<const char *>(&schema), sizeof(schema));
David Neto22f144c2017-06-12 14:26:21 -0400751 }
752}
753
754void SPIRVProducerPass::patchHeader() {
755 if (outputAsm) {
756 // get the string representation of the max bound used (nextID will be the
757 // max ID used)
758 auto asString = std::to_string(nextID);
759 out.pwrite(asString.c_str(), asString.size(), patchBoundOffset);
760 } else {
761 // for a binary we just write the value of nextID over bound
David Neto0676e6f2017-07-11 18:47:44 -0400762 binaryOut->pwrite(reinterpret_cast<char *>(&nextID), sizeof(nextID),
763 patchBoundOffset);
David Neto22f144c2017-06-12 14:26:21 -0400764 }
765}
766
David Netoc6f3ab22018-04-06 18:02:31 -0400767void SPIRVProducerPass::GenerateLLVMIRInfo(Module &M, const DataLayout &DL) {
David Neto22f144c2017-06-12 14:26:21 -0400768 // This function generates LLVM IR for function such as global variable for
769 // argument, constant and pointer type for argument access. These information
770 // is artificial one because we need Vulkan SPIR-V output. This function is
771 // executed ahead of FindType and FindConstant.
David Neto22f144c2017-06-12 14:26:21 -0400772 LLVMContext &Context = M.getContext();
773
David Neto862b7d82018-06-14 18:48:37 -0400774 FindGlobalConstVars(M, DL);
David Neto5c22a252018-03-15 16:07:41 -0400775
David Neto862b7d82018-06-14 18:48:37 -0400776 FindResourceVars(M, DL);
David Neto22f144c2017-06-12 14:26:21 -0400777
778 bool HasWorkGroupBuiltin = false;
779 for (GlobalVariable &GV : M.globals()) {
780 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
781 if (spv::BuiltInWorkgroupSize == BuiltinType) {
782 HasWorkGroupBuiltin = true;
783 }
784 }
785
David Neto862b7d82018-06-14 18:48:37 -0400786 FindTypesForSamplerMap(M);
787 FindTypesForResourceVars(M);
Alan Baker202c8c72018-08-13 13:47:44 -0400788 FindWorkgroupVars(M);
David Neto22f144c2017-06-12 14:26:21 -0400789
David Neto862b7d82018-06-14 18:48:37 -0400790 // These function calls need a <2 x i32> as an intermediate result but not
791 // the final result.
792 std::unordered_set<std::string> NeedsIVec2{
793 "_Z15get_image_width14ocl_image2d_ro",
794 "_Z15get_image_width14ocl_image2d_wo",
795 "_Z16get_image_height14ocl_image2d_ro",
796 "_Z16get_image_height14ocl_image2d_wo",
797 };
798
David Neto22f144c2017-06-12 14:26:21 -0400799 for (Function &F : M) {
Kévin Petitabef4522019-03-27 13:08:01 +0000800 if (F.isDeclaration()) {
David Neto22f144c2017-06-12 14:26:21 -0400801 continue;
802 }
803
804 for (BasicBlock &BB : F) {
805 for (Instruction &I : BB) {
806 if (I.getOpcode() == Instruction::ZExt ||
807 I.getOpcode() == Instruction::SExt ||
808 I.getOpcode() == Instruction::UIToFP) {
809 // If there is zext with i1 type, it will be changed to OpSelect. The
810 // OpSelect needs constant 0 and 1 so the constants are added here.
811
812 auto OpTy = I.getOperand(0)->getType();
813
Kévin Petit24272b62018-10-18 19:16:12 +0000814 if (OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -0400815 if (I.getOpcode() == Instruction::ZExt) {
David Neto22f144c2017-06-12 14:26:21 -0400816 FindConstant(Constant::getNullValue(I.getType()));
Kévin Petit7bfb8992019-02-26 13:45:08 +0000817 FindConstant(ConstantInt::get(I.getType(), 1));
David Neto22f144c2017-06-12 14:26:21 -0400818 } else if (I.getOpcode() == Instruction::SExt) {
David Neto22f144c2017-06-12 14:26:21 -0400819 FindConstant(Constant::getNullValue(I.getType()));
Kévin Petit7bfb8992019-02-26 13:45:08 +0000820 FindConstant(ConstantInt::getSigned(I.getType(), -1));
David Neto22f144c2017-06-12 14:26:21 -0400821 } else {
822 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
823 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
824 }
825 }
826 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
David Neto862b7d82018-06-14 18:48:37 -0400827 StringRef callee_name = Call->getCalledFunction()->getName();
David Neto22f144c2017-06-12 14:26:21 -0400828
829 // Handle image type specially.
David Neto862b7d82018-06-14 18:48:37 -0400830 if (callee_name.equals(
David Neto22f144c2017-06-12 14:26:21 -0400831 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
David Neto862b7d82018-06-14 18:48:37 -0400832 callee_name.equals(
David Neto22f144c2017-06-12 14:26:21 -0400833 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
834 TypeMapType &OpImageTypeMap = getImageTypeMap();
835 Type *ImageTy =
836 Call->getArgOperand(0)->getType()->getPointerElementType();
837 OpImageTypeMap[ImageTy] = 0;
838
839 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
840 }
David Neto5c22a252018-03-15 16:07:41 -0400841
David Neto862b7d82018-06-14 18:48:37 -0400842 if (NeedsIVec2.find(callee_name) != NeedsIVec2.end()) {
David Neto5c22a252018-03-15 16:07:41 -0400843 FindType(VectorType::get(Type::getInt32Ty(Context), 2));
844 }
David Neto22f144c2017-06-12 14:26:21 -0400845 }
846 }
847 }
848
Kévin Petitabef4522019-03-27 13:08:01 +0000849 // More things to do on kernel functions
850 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
851 if (const MDNode *MD =
852 dyn_cast<Function>(&F)->getMetadata("reqd_work_group_size")) {
853 // We generate constants if the WorkgroupSize builtin is being used.
854 if (HasWorkGroupBuiltin) {
855 // Collect constant information for work group size.
856 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(0)));
857 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(1)));
858 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(2)));
David Neto22f144c2017-06-12 14:26:21 -0400859 }
860 }
861 }
862
863 if (M.getTypeByName("opencl.image2d_ro_t") ||
864 M.getTypeByName("opencl.image2d_wo_t") ||
865 M.getTypeByName("opencl.image3d_ro_t") ||
866 M.getTypeByName("opencl.image3d_wo_t")) {
867 // Assume Image type's sampled type is float type.
868 FindType(Type::getFloatTy(Context));
869 }
870
871 // Collect types' information from function.
872 FindTypePerFunc(F);
873
874 // Collect constant information from function.
875 FindConstantPerFunc(F);
876 }
877}
878
David Neto862b7d82018-06-14 18:48:37 -0400879void SPIRVProducerPass::FindGlobalConstVars(Module &M, const DataLayout &DL) {
880 SmallVector<GlobalVariable *, 8> GVList;
881 SmallVector<GlobalVariable *, 8> DeadGVList;
882 for (GlobalVariable &GV : M.globals()) {
883 if (GV.getType()->getAddressSpace() == AddressSpace::Constant) {
884 if (GV.use_empty()) {
885 DeadGVList.push_back(&GV);
886 } else {
887 GVList.push_back(&GV);
888 }
889 }
890 }
891
892 // Remove dead global __constant variables.
893 for (auto GV : DeadGVList) {
894 GV->eraseFromParent();
895 }
896 DeadGVList.clear();
897
898 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
899 // For now, we only support a single storage buffer.
900 if (GVList.size() > 0) {
901 assert(GVList.size() == 1);
902 const auto *GV = GVList[0];
903 const auto constants_byte_size =
Alan Bakerfcda9482018-10-02 17:09:59 -0400904 (GetTypeSizeInBits(GV->getInitializer()->getType(), DL)) / 8;
David Neto862b7d82018-06-14 18:48:37 -0400905 const size_t kConstantMaxSize = 65536;
906 if (constants_byte_size > kConstantMaxSize) {
907 outs() << "Max __constant capacity of " << kConstantMaxSize
908 << " bytes exceeded: " << constants_byte_size << " bytes used\n";
909 llvm_unreachable("Max __constant capacity exceeded");
910 }
911 }
912 } else {
913 // Change global constant variable's address space to ModuleScopePrivate.
914 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
915 for (auto GV : GVList) {
916 // Create new gv with ModuleScopePrivate address space.
917 Type *NewGVTy = GV->getType()->getPointerElementType();
918 GlobalVariable *NewGV = new GlobalVariable(
919 M, NewGVTy, false, GV->getLinkage(), GV->getInitializer(), "",
920 nullptr, GV->getThreadLocalMode(), AddressSpace::ModuleScopePrivate);
921 NewGV->takeName(GV);
922
923 const SmallVector<User *, 8> GVUsers(GV->user_begin(), GV->user_end());
924 SmallVector<User *, 8> CandidateUsers;
925
926 auto record_called_function_type_as_user =
927 [&GlobalConstFuncTyMap](Value *gv, CallInst *call) {
928 // Find argument index.
929 unsigned index = 0;
930 for (unsigned i = 0; i < call->getNumArgOperands(); i++) {
931 if (gv == call->getOperand(i)) {
932 // TODO(dneto): Should we break here?
933 index = i;
934 }
935 }
936
937 // Record function type with global constant.
938 GlobalConstFuncTyMap[call->getFunctionType()] =
939 std::make_pair(call->getFunctionType(), index);
940 };
941
942 for (User *GVU : GVUsers) {
943 if (CallInst *Call = dyn_cast<CallInst>(GVU)) {
944 record_called_function_type_as_user(GV, Call);
945 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(GVU)) {
946 // Check GEP users.
947 for (User *GEPU : GEP->users()) {
948 if (CallInst *GEPCall = dyn_cast<CallInst>(GEPU)) {
949 record_called_function_type_as_user(GEP, GEPCall);
950 }
951 }
952 }
953
954 CandidateUsers.push_back(GVU);
955 }
956
957 for (User *U : CandidateUsers) {
958 // Update users of gv with new gv.
alan-bakered80f572019-02-11 17:28:26 -0500959 if (!isa<Constant>(U)) {
960 // #254: Can't change operands of a constant, but this shouldn't be
961 // something that sticks around in the module.
962 U->replaceUsesOfWith(GV, NewGV);
963 }
David Neto862b7d82018-06-14 18:48:37 -0400964 }
965
966 // Delete original gv.
967 GV->eraseFromParent();
968 }
969 }
970}
971
Radek Szymanskibe4b0c42018-10-04 22:20:53 +0100972void SPIRVProducerPass::FindResourceVars(Module &M, const DataLayout &) {
David Neto862b7d82018-06-14 18:48:37 -0400973 ResourceVarInfoList.clear();
974 FunctionToResourceVarsMap.clear();
975 ModuleOrderedResourceVars.reset();
976 // Normally, there is one resource variable per clspv.resource.var.*
977 // function, since that is unique'd by arg type and index. By design,
978 // we can share these resource variables across kernels because all
979 // kernels use the same descriptor set.
980 //
981 // But if the user requested distinct descriptor sets per kernel, then
982 // the descriptor allocator has made different (set,binding) pairs for
983 // the same (type,arg_index) pair. Since we can decorate a resource
984 // variable with only exactly one DescriptorSet and Binding, we are
985 // forced in this case to make distinct resource variables whenever
986 // the same clspv.reource.var.X function is seen with disintct
987 // (set,binding) values.
988 const bool always_distinct_sets =
989 clspv::Option::DistinctKernelDescriptorSets();
990 for (Function &F : M) {
991 // Rely on the fact the resource var functions have a stable ordering
992 // in the module.
Alan Baker202c8c72018-08-13 13:47:44 -0400993 if (F.getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -0400994 // Find all calls to this function with distinct set and binding pairs.
995 // Save them in ResourceVarInfoList.
996
997 // Determine uniqueness of the (set,binding) pairs only withing this
998 // one resource-var builtin function.
999 using SetAndBinding = std::pair<unsigned, unsigned>;
1000 // Maps set and binding to the resource var info.
1001 DenseMap<SetAndBinding, ResourceVarInfo *> set_and_binding_map;
1002 bool first_use = true;
1003 for (auto &U : F.uses()) {
1004 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
1005 const auto set = unsigned(
1006 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
1007 const auto binding = unsigned(
1008 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
1009 const auto arg_kind = clspv::ArgKind(
1010 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
1011 const auto arg_index = unsigned(
1012 dyn_cast<ConstantInt>(call->getArgOperand(3))->getZExtValue());
alan-bakere9308012019-03-15 10:25:13 -04001013 const auto coherent = unsigned(
1014 dyn_cast<ConstantInt>(call->getArgOperand(5))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04001015
1016 // Find or make the resource var info for this combination.
1017 ResourceVarInfo *rv = nullptr;
1018 if (always_distinct_sets) {
1019 // Make a new resource var any time we see a different
1020 // (set,binding) pair.
1021 SetAndBinding key{set, binding};
1022 auto where = set_and_binding_map.find(key);
1023 if (where == set_and_binding_map.end()) {
1024 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
alan-bakere9308012019-03-15 10:25:13 -04001025 binding, &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001026 ResourceVarInfoList.emplace_back(rv);
1027 set_and_binding_map[key] = rv;
1028 } else {
1029 rv = where->second;
1030 }
1031 } else {
1032 // The default is to make exactly one resource for each
1033 // clspv.resource.var.* function.
1034 if (first_use) {
1035 first_use = false;
1036 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
alan-bakere9308012019-03-15 10:25:13 -04001037 binding, &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001038 ResourceVarInfoList.emplace_back(rv);
1039 } else {
1040 rv = ResourceVarInfoList.back().get();
1041 }
1042 }
1043
1044 // Now populate FunctionToResourceVarsMap.
1045 auto &mapping =
1046 FunctionToResourceVarsMap[call->getParent()->getParent()];
1047 while (mapping.size() <= arg_index) {
1048 mapping.push_back(nullptr);
1049 }
1050 mapping[arg_index] = rv;
1051 }
1052 }
1053 }
1054 }
1055
1056 // Populate ModuleOrderedResourceVars.
1057 for (Function &F : M) {
1058 auto where = FunctionToResourceVarsMap.find(&F);
1059 if (where != FunctionToResourceVarsMap.end()) {
1060 for (auto &rv : where->second) {
1061 if (rv != nullptr) {
1062 ModuleOrderedResourceVars.insert(rv);
1063 }
1064 }
1065 }
1066 }
1067 if (ShowResourceVars) {
1068 for (auto *info : ModuleOrderedResourceVars) {
1069 outs() << "MORV index " << info->index << " (" << info->descriptor_set
1070 << "," << info->binding << ") " << *(info->var_fn->getReturnType())
1071 << "\n";
1072 }
1073 }
1074}
1075
David Neto22f144c2017-06-12 14:26:21 -04001076bool SPIRVProducerPass::FindExtInst(Module &M) {
1077 LLVMContext &Context = M.getContext();
1078 bool HasExtInst = false;
1079
1080 for (Function &F : M) {
1081 for (BasicBlock &BB : F) {
1082 for (Instruction &I : BB) {
1083 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1084 Function *Callee = Call->getCalledFunction();
1085 // Check whether this call is for extend instructions.
David Neto3fbb4072017-10-16 11:28:14 -04001086 auto callee_name = Callee->getName();
1087 const glsl::ExtInst EInst = getExtInstEnum(callee_name);
1088 const glsl::ExtInst IndirectEInst =
1089 getIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04001090
David Neto3fbb4072017-10-16 11:28:14 -04001091 HasExtInst |=
1092 (EInst != kGlslExtInstBad) || (IndirectEInst != kGlslExtInstBad);
1093
1094 if (IndirectEInst) {
1095 // Register extra constants if needed.
1096
1097 // Registers a type and constant for computing the result of the
1098 // given instruction. If the result of the instruction is a vector,
1099 // then make a splat vector constant with the same number of
1100 // elements.
1101 auto register_constant = [this, &I](Constant *constant) {
1102 FindType(constant->getType());
1103 FindConstant(constant);
1104 if (auto *vectorTy = dyn_cast<VectorType>(I.getType())) {
1105 // Register the splat vector of the value with the same
1106 // width as the result of the instruction.
1107 auto *vec_constant = ConstantVector::getSplat(
1108 static_cast<unsigned>(vectorTy->getNumElements()),
1109 constant);
1110 FindConstant(vec_constant);
1111 FindType(vec_constant->getType());
1112 }
1113 };
1114 switch (IndirectEInst) {
1115 case glsl::ExtInstFindUMsb:
1116 // clz needs OpExtInst and OpISub with constant 31, or splat
1117 // vector of 31. Add it to the constant list here.
1118 register_constant(
1119 ConstantInt::get(Type::getInt32Ty(Context), 31));
1120 break;
1121 case glsl::ExtInstAcos:
1122 case glsl::ExtInstAsin:
Kévin Petiteb9f90a2018-09-29 12:29:34 +01001123 case glsl::ExtInstAtan:
David Neto3fbb4072017-10-16 11:28:14 -04001124 case glsl::ExtInstAtan2:
1125 // We need 1/pi for acospi, asinpi, atan2pi.
1126 register_constant(
1127 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
1128 break;
1129 default:
1130 assert(false && "internally inconsistent");
1131 }
David Neto22f144c2017-06-12 14:26:21 -04001132 }
1133 }
1134 }
1135 }
1136 }
1137
1138 return HasExtInst;
1139}
1140
1141void SPIRVProducerPass::FindTypePerGlobalVar(GlobalVariable &GV) {
1142 // Investigate global variable's type.
1143 FindType(GV.getType());
1144}
1145
1146void SPIRVProducerPass::FindTypePerFunc(Function &F) {
1147 // Investigate function's type.
1148 FunctionType *FTy = F.getFunctionType();
1149
1150 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
1151 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
David Neto9ed8e2f2018-03-24 06:47:24 -07001152 // Handle a regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04001153 if (GlobalConstFuncTyMap.count(FTy)) {
1154 uint32_t GVCstArgIdx = GlobalConstFuncTypeMap[FTy].second;
1155 SmallVector<Type *, 4> NewFuncParamTys;
1156 for (unsigned i = 0; i < FTy->getNumParams(); i++) {
1157 Type *ParamTy = FTy->getParamType(i);
1158 if (i == GVCstArgIdx) {
1159 Type *EleTy = ParamTy->getPointerElementType();
1160 ParamTy = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1161 }
1162
1163 NewFuncParamTys.push_back(ParamTy);
1164 }
1165
1166 FunctionType *NewFTy =
1167 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1168 GlobalConstFuncTyMap[FTy] = std::make_pair(NewFTy, GVCstArgIdx);
1169 FTy = NewFTy;
1170 }
1171
1172 FindType(FTy);
1173 } else {
1174 // As kernel functions do not have parameters, create new function type and
1175 // add it to type map.
1176 SmallVector<Type *, 4> NewFuncParamTys;
1177 FunctionType *NewFTy =
1178 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1179 FindType(NewFTy);
1180 }
1181
1182 // Investigate instructions' type in function body.
1183 for (BasicBlock &BB : F) {
1184 for (Instruction &I : BB) {
1185 if (isa<ShuffleVectorInst>(I)) {
1186 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1187 // Ignore type for mask of shuffle vector instruction.
1188 if (i == 2) {
1189 continue;
1190 }
1191
1192 Value *Op = I.getOperand(i);
1193 if (!isa<MetadataAsValue>(Op)) {
1194 FindType(Op->getType());
1195 }
1196 }
1197
1198 FindType(I.getType());
1199 continue;
1200 }
1201
David Neto862b7d82018-06-14 18:48:37 -04001202 CallInst *Call = dyn_cast<CallInst>(&I);
1203
1204 if (Call && Call->getCalledFunction()->getName().startswith(
Alan Baker202c8c72018-08-13 13:47:44 -04001205 clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001206 // This is a fake call representing access to a resource variable.
1207 // We handle that elsewhere.
1208 continue;
1209 }
1210
Alan Baker202c8c72018-08-13 13:47:44 -04001211 if (Call && Call->getCalledFunction()->getName().startswith(
1212 clspv::WorkgroupAccessorFunction())) {
1213 // This is a fake call representing access to a workgroup variable.
1214 // We handle that elsewhere.
1215 continue;
1216 }
1217
David Neto22f144c2017-06-12 14:26:21 -04001218 // Work through the operands of the instruction.
1219 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1220 Value *const Op = I.getOperand(i);
1221 // If any of the operands is a constant, find the type!
1222 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1223 FindType(Op->getType());
1224 }
1225 }
1226
1227 for (Use &Op : I.operands()) {
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001228 if (isa<CallInst>(&I)) {
David Neto22f144c2017-06-12 14:26:21 -04001229 // Avoid to check call instruction's type.
1230 break;
1231 }
Alan Baker202c8c72018-08-13 13:47:44 -04001232 if (CallInst *OpCall = dyn_cast<CallInst>(Op)) {
1233 if (OpCall && OpCall->getCalledFunction()->getName().startswith(
1234 clspv::WorkgroupAccessorFunction())) {
1235 // This is a fake call representing access to a workgroup variable.
1236 // We handle that elsewhere.
1237 continue;
1238 }
1239 }
David Neto22f144c2017-06-12 14:26:21 -04001240 if (!isa<MetadataAsValue>(&Op)) {
1241 FindType(Op->getType());
1242 continue;
1243 }
1244 }
1245
David Neto22f144c2017-06-12 14:26:21 -04001246 // We don't want to track the type of this call as we are going to replace
1247 // it.
Kévin Petitdf71de32019-04-09 14:09:50 +01001248 if (Call && (clspv::LiteralSamplerFunction() ==
David Neto22f144c2017-06-12 14:26:21 -04001249 Call->getCalledFunction()->getName())) {
1250 continue;
1251 }
1252
1253 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1254 // If gep's base operand has ModuleScopePrivate address space, make gep
1255 // return ModuleScopePrivate address space.
1256 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate) {
1257 // Add pointer type with private address space for global constant to
1258 // type list.
1259 Type *EleTy = I.getType()->getPointerElementType();
1260 Type *NewPTy =
1261 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1262
1263 FindType(NewPTy);
1264 continue;
1265 }
1266 }
1267
1268 FindType(I.getType());
1269 }
1270 }
1271}
1272
David Neto862b7d82018-06-14 18:48:37 -04001273void SPIRVProducerPass::FindTypesForSamplerMap(Module &M) {
1274 // If we are using a sampler map, find the type of the sampler.
Kévin Petitdf71de32019-04-09 14:09:50 +01001275 if (M.getFunction(clspv::LiteralSamplerFunction()) ||
David Neto862b7d82018-06-14 18:48:37 -04001276 0 < getSamplerMap().size()) {
1277 auto SamplerStructTy = M.getTypeByName("opencl.sampler_t");
1278 if (!SamplerStructTy) {
1279 SamplerStructTy = StructType::create(M.getContext(), "opencl.sampler_t");
1280 }
1281
1282 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
1283
1284 FindType(SamplerTy);
1285 }
1286}
1287
1288void SPIRVProducerPass::FindTypesForResourceVars(Module &M) {
1289 // Record types so they are generated.
1290 TypesNeedingLayout.reset();
1291 StructTypesNeedingBlock.reset();
1292
1293 // To match older clspv codegen, generate the float type first if required
1294 // for images.
1295 for (const auto *info : ModuleOrderedResourceVars) {
1296 if (info->arg_kind == clspv::ArgKind::ReadOnlyImage ||
1297 info->arg_kind == clspv::ArgKind::WriteOnlyImage) {
1298 // We need "float" for the sampled component type.
1299 FindType(Type::getFloatTy(M.getContext()));
1300 // We only need to find it once.
1301 break;
1302 }
1303 }
1304
1305 for (const auto *info : ModuleOrderedResourceVars) {
1306 Type *type = info->var_fn->getReturnType();
1307
1308 switch (info->arg_kind) {
1309 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04001310 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04001311 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1312 StructTypesNeedingBlock.insert(sty);
1313 } else {
1314 errs() << *type << "\n";
1315 llvm_unreachable("Buffer arguments must map to structures!");
1316 }
1317 break;
1318 case clspv::ArgKind::Pod:
1319 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1320 StructTypesNeedingBlock.insert(sty);
1321 } else {
1322 errs() << *type << "\n";
1323 llvm_unreachable("POD arguments must map to structures!");
1324 }
1325 break;
1326 case clspv::ArgKind::ReadOnlyImage:
1327 case clspv::ArgKind::WriteOnlyImage:
1328 case clspv::ArgKind::Sampler:
1329 // Sampler and image types map to the pointee type but
1330 // in the uniform constant address space.
1331 type = PointerType::get(type->getPointerElementType(),
1332 clspv::AddressSpace::UniformConstant);
1333 break;
1334 default:
1335 break;
1336 }
1337
1338 // The converted type is the type of the OpVariable we will generate.
1339 // If the pointee type is an array of size zero, FindType will convert it
1340 // to a runtime array.
1341 FindType(type);
1342 }
1343
1344 // Traverse the arrays and structures underneath each Block, and
1345 // mark them as needing layout.
1346 std::vector<Type *> work_list(StructTypesNeedingBlock.begin(),
1347 StructTypesNeedingBlock.end());
1348 while (!work_list.empty()) {
1349 Type *type = work_list.back();
1350 work_list.pop_back();
1351 TypesNeedingLayout.insert(type);
1352 switch (type->getTypeID()) {
1353 case Type::ArrayTyID:
1354 work_list.push_back(type->getArrayElementType());
1355 if (!Hack_generate_runtime_array_stride_early) {
1356 // Remember this array type for deferred decoration.
1357 TypesNeedingArrayStride.insert(type);
1358 }
1359 break;
1360 case Type::StructTyID:
1361 for (auto *elem_ty : cast<StructType>(type)->elements()) {
1362 work_list.push_back(elem_ty);
1363 }
1364 default:
1365 // This type and its contained types don't get layout.
1366 break;
1367 }
1368 }
1369}
1370
Alan Baker202c8c72018-08-13 13:47:44 -04001371void SPIRVProducerPass::FindWorkgroupVars(Module &M) {
1372 // The SpecId assignment for pointer-to-local arguments is recorded in
1373 // module-level metadata. Translate that information into local argument
1374 // information.
1375 NamedMDNode *nmd = M.getNamedMetadata(clspv::LocalSpecIdMetadataName());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001376 if (!nmd)
1377 return;
Alan Baker202c8c72018-08-13 13:47:44 -04001378 for (auto operand : nmd->operands()) {
1379 MDTuple *tuple = cast<MDTuple>(operand);
1380 ValueAsMetadata *fn_md = cast<ValueAsMetadata>(tuple->getOperand(0));
1381 Function *func = cast<Function>(fn_md->getValue());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001382 ConstantAsMetadata *arg_index_md =
1383 cast<ConstantAsMetadata>(tuple->getOperand(1));
1384 int arg_index = static_cast<int>(
1385 cast<ConstantInt>(arg_index_md->getValue())->getSExtValue());
1386 Argument *arg = &*(func->arg_begin() + arg_index);
Alan Baker202c8c72018-08-13 13:47:44 -04001387
1388 ConstantAsMetadata *spec_id_md =
1389 cast<ConstantAsMetadata>(tuple->getOperand(2));
alan-bakerb6b09dc2018-11-08 16:59:28 -05001390 int spec_id = static_cast<int>(
1391 cast<ConstantInt>(spec_id_md->getValue())->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04001392
1393 max_local_spec_id_ = std::max(max_local_spec_id_, spec_id + 1);
1394 LocalArgSpecIds[arg] = spec_id;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001395 if (LocalSpecIdInfoMap.count(spec_id))
1396 continue;
Alan Baker202c8c72018-08-13 13:47:44 -04001397
1398 // We haven't seen this SpecId yet, so generate the LocalArgInfo for it.
1399 LocalArgInfo info{nextID, arg->getType()->getPointerElementType(),
1400 nextID + 1, nextID + 2,
1401 nextID + 3, spec_id};
1402 LocalSpecIdInfoMap[spec_id] = info;
1403 nextID += 4;
1404
1405 // Ensure the types necessary for this argument get generated.
1406 Type *IdxTy = Type::getInt32Ty(M.getContext());
1407 FindConstant(ConstantInt::get(IdxTy, 0));
1408 FindType(IdxTy);
1409 FindType(arg->getType());
1410 }
1411}
1412
David Neto22f144c2017-06-12 14:26:21 -04001413void SPIRVProducerPass::FindType(Type *Ty) {
1414 TypeList &TyList = getTypeList();
1415
1416 if (0 != TyList.idFor(Ty)) {
1417 return;
1418 }
1419
1420 if (Ty->isPointerTy()) {
1421 auto AddrSpace = Ty->getPointerAddressSpace();
1422 if ((AddressSpace::Constant == AddrSpace) ||
1423 (AddressSpace::Global == AddrSpace)) {
1424 auto PointeeTy = Ty->getPointerElementType();
1425
1426 if (PointeeTy->isStructTy() &&
1427 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1428 FindType(PointeeTy);
1429 auto ActualPointerTy =
1430 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1431 FindType(ActualPointerTy);
1432 return;
1433 }
1434 }
1435 }
1436
David Neto862b7d82018-06-14 18:48:37 -04001437 // By convention, LLVM array type with 0 elements will map to
1438 // OpTypeRuntimeArray. Otherwise, it will map to OpTypeArray, which
1439 // has a constant number of elements. We need to support type of the
1440 // constant.
1441 if (auto *arrayTy = dyn_cast<ArrayType>(Ty)) {
1442 if (arrayTy->getNumElements() > 0) {
1443 LLVMContext &Context = Ty->getContext();
1444 FindType(Type::getInt32Ty(Context));
1445 }
David Neto22f144c2017-06-12 14:26:21 -04001446 }
1447
1448 for (Type *SubTy : Ty->subtypes()) {
1449 FindType(SubTy);
1450 }
1451
1452 TyList.insert(Ty);
1453}
1454
1455void SPIRVProducerPass::FindConstantPerGlobalVar(GlobalVariable &GV) {
1456 // If the global variable has a (non undef) initializer.
1457 if (GV.hasInitializer() && !isa<UndefValue>(GV.getInitializer())) {
David Neto862b7d82018-06-14 18:48:37 -04001458 // Generate the constant if it's not the initializer to a module scope
1459 // constant that we will expect in a storage buffer.
1460 const bool module_scope_constant_external_init =
1461 (GV.getType()->getPointerAddressSpace() == AddressSpace::Constant) &&
1462 clspv::Option::ModuleConstantsInStorageBuffer();
1463 if (!module_scope_constant_external_init) {
1464 FindConstant(GV.getInitializer());
1465 }
David Neto22f144c2017-06-12 14:26:21 -04001466 }
1467}
1468
1469void SPIRVProducerPass::FindConstantPerFunc(Function &F) {
1470 // Investigate constants in function body.
1471 for (BasicBlock &BB : F) {
1472 for (Instruction &I : BB) {
David Neto862b7d82018-06-14 18:48:37 -04001473 if (auto *call = dyn_cast<CallInst>(&I)) {
1474 auto name = call->getCalledFunction()->getName();
Kévin Petitdf71de32019-04-09 14:09:50 +01001475 if (name == clspv::LiteralSamplerFunction()) {
David Neto862b7d82018-06-14 18:48:37 -04001476 // We've handled these constants elsewhere, so skip it.
1477 continue;
1478 }
Alan Baker202c8c72018-08-13 13:47:44 -04001479 if (name.startswith(clspv::ResourceAccessorFunction())) {
1480 continue;
1481 }
1482 if (name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001483 continue;
1484 }
Kévin Petit617a76d2019-04-04 13:54:16 +01001485 if (name.startswith(clspv::SPIRVOpIntrinsicFunction())) {
1486 // Skip the first operand that has the SPIR-V Opcode
1487 for (unsigned i = 1; i < I.getNumOperands(); i++) {
1488 if (isa<Constant>(I.getOperand(i)) &&
1489 !isa<GlobalValue>(I.getOperand(i))) {
1490 FindConstant(I.getOperand(i));
1491 }
1492 }
1493 continue;
1494 }
David Neto22f144c2017-06-12 14:26:21 -04001495 }
1496
1497 if (isa<AllocaInst>(I)) {
1498 // Alloca instruction has constant for the number of element. Ignore it.
1499 continue;
1500 } else if (isa<ShuffleVectorInst>(I)) {
1501 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1502 // Ignore constant for mask of shuffle vector instruction.
1503 if (i == 2) {
1504 continue;
1505 }
1506
1507 if (isa<Constant>(I.getOperand(i)) &&
1508 !isa<GlobalValue>(I.getOperand(i))) {
1509 FindConstant(I.getOperand(i));
1510 }
1511 }
1512
1513 continue;
1514 } else if (isa<InsertElementInst>(I)) {
1515 // Handle InsertElement with <4 x i8> specially.
1516 Type *CompositeTy = I.getOperand(0)->getType();
1517 if (is4xi8vec(CompositeTy)) {
1518 LLVMContext &Context = CompositeTy->getContext();
1519 if (isa<Constant>(I.getOperand(0))) {
1520 FindConstant(I.getOperand(0));
1521 }
1522
1523 if (isa<Constant>(I.getOperand(1))) {
1524 FindConstant(I.getOperand(1));
1525 }
1526
1527 // Add mask constant 0xFF.
1528 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1529 FindConstant(CstFF);
1530
1531 // Add shift amount constant.
1532 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
1533 uint64_t Idx = CI->getZExtValue();
1534 Constant *CstShiftAmount =
1535 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1536 FindConstant(CstShiftAmount);
1537 }
1538
1539 continue;
1540 }
1541
1542 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1543 // Ignore constant for index of InsertElement instruction.
1544 if (i == 2) {
1545 continue;
1546 }
1547
1548 if (isa<Constant>(I.getOperand(i)) &&
1549 !isa<GlobalValue>(I.getOperand(i))) {
1550 FindConstant(I.getOperand(i));
1551 }
1552 }
1553
1554 continue;
1555 } else if (isa<ExtractElementInst>(I)) {
1556 // Handle ExtractElement with <4 x i8> specially.
1557 Type *CompositeTy = I.getOperand(0)->getType();
1558 if (is4xi8vec(CompositeTy)) {
1559 LLVMContext &Context = CompositeTy->getContext();
1560 if (isa<Constant>(I.getOperand(0))) {
1561 FindConstant(I.getOperand(0));
1562 }
1563
1564 // Add mask constant 0xFF.
1565 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1566 FindConstant(CstFF);
1567
1568 // Add shift amount constant.
1569 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1570 uint64_t Idx = CI->getZExtValue();
1571 Constant *CstShiftAmount =
1572 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1573 FindConstant(CstShiftAmount);
1574 } else {
1575 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
1576 FindConstant(Cst8);
1577 }
1578
1579 continue;
1580 }
1581
1582 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1583 // Ignore constant for index of ExtractElement instruction.
1584 if (i == 1) {
1585 continue;
1586 }
1587
1588 if (isa<Constant>(I.getOperand(i)) &&
1589 !isa<GlobalValue>(I.getOperand(i))) {
1590 FindConstant(I.getOperand(i));
1591 }
1592 }
1593
1594 continue;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001595 } else if ((Instruction::Xor == I.getOpcode()) &&
1596 I.getType()->isIntegerTy(1)) {
1597 // We special case for Xor where the type is i1 and one of the arguments
1598 // is a constant 1 (true), this is an OpLogicalNot in SPIR-V, and we
1599 // don't need the constant
David Neto22f144c2017-06-12 14:26:21 -04001600 bool foundConstantTrue = false;
1601 for (Use &Op : I.operands()) {
1602 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1603 auto CI = cast<ConstantInt>(Op);
1604
1605 if (CI->isZero() || foundConstantTrue) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05001606 // If we already found the true constant, we might (probably only
1607 // on -O0) have an OpLogicalNot which is taking a constant
1608 // argument, so discover it anyway.
David Neto22f144c2017-06-12 14:26:21 -04001609 FindConstant(Op);
1610 } else {
1611 foundConstantTrue = true;
1612 }
1613 }
1614 }
1615
1616 continue;
David Netod2de94a2017-08-28 17:27:47 -04001617 } else if (isa<TruncInst>(I)) {
alan-bakerb39c8262019-03-08 14:03:37 -05001618 // Special case if i8 is not generally handled.
1619 if (!clspv::Option::Int8Support()) {
1620 // For truncation to i8 we mask against 255.
1621 Type *ToTy = I.getType();
1622 if (8u == ToTy->getPrimitiveSizeInBits()) {
1623 LLVMContext &Context = ToTy->getContext();
1624 Constant *Cst255 =
1625 ConstantInt::get(Type::getInt32Ty(Context), 0xff);
1626 FindConstant(Cst255);
1627 }
David Netod2de94a2017-08-28 17:27:47 -04001628 }
Neil Henning39672102017-09-29 14:33:13 +01001629 } else if (isa<AtomicRMWInst>(I)) {
1630 LLVMContext &Context = I.getContext();
1631
1632 FindConstant(
1633 ConstantInt::get(Type::getInt32Ty(Context), spv::ScopeDevice));
1634 FindConstant(ConstantInt::get(
1635 Type::getInt32Ty(Context),
1636 spv::MemorySemanticsUniformMemoryMask |
1637 spv::MemorySemanticsSequentiallyConsistentMask));
David Neto22f144c2017-06-12 14:26:21 -04001638 }
1639
1640 for (Use &Op : I.operands()) {
1641 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1642 FindConstant(Op);
1643 }
1644 }
1645 }
1646 }
1647}
1648
1649void SPIRVProducerPass::FindConstant(Value *V) {
David Neto22f144c2017-06-12 14:26:21 -04001650 ValueList &CstList = getConstantList();
1651
David Netofb9a7972017-08-25 17:08:24 -04001652 // If V is already tracked, ignore it.
1653 if (0 != CstList.idFor(V)) {
David Neto22f144c2017-06-12 14:26:21 -04001654 return;
1655 }
1656
David Neto862b7d82018-06-14 18:48:37 -04001657 if (isa<GlobalValue>(V) && clspv::Option::ModuleConstantsInStorageBuffer()) {
1658 return;
1659 }
1660
David Neto22f144c2017-06-12 14:26:21 -04001661 Constant *Cst = cast<Constant>(V);
David Neto862b7d82018-06-14 18:48:37 -04001662 Type *CstTy = Cst->getType();
David Neto22f144c2017-06-12 14:26:21 -04001663
1664 // Handle constant with <4 x i8> type specially.
David Neto22f144c2017-06-12 14:26:21 -04001665 if (is4xi8vec(CstTy)) {
1666 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001667 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001668 }
1669 }
1670
1671 if (Cst->getNumOperands()) {
1672 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end(); I != E;
1673 ++I) {
1674 FindConstant(*I);
1675 }
1676
David Netofb9a7972017-08-25 17:08:24 -04001677 CstList.insert(Cst);
David Neto22f144c2017-06-12 14:26:21 -04001678 return;
1679 } else if (const ConstantDataSequential *CDS =
1680 dyn_cast<ConstantDataSequential>(Cst)) {
1681 // Add constants for each element to constant list.
1682 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
1683 Constant *EleCst = CDS->getElementAsConstant(i);
1684 FindConstant(EleCst);
1685 }
1686 }
1687
1688 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001689 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001690 }
1691}
1692
1693spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1694 switch (AddrSpace) {
1695 default:
1696 llvm_unreachable("Unsupported OpenCL address space");
1697 case AddressSpace::Private:
1698 return spv::StorageClassFunction;
1699 case AddressSpace::Global:
David Neto22f144c2017-06-12 14:26:21 -04001700 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001701 case AddressSpace::Constant:
1702 return clspv::Option::ConstantArgsInUniformBuffer()
1703 ? spv::StorageClassUniform
1704 : spv::StorageClassStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -04001705 case AddressSpace::Input:
1706 return spv::StorageClassInput;
1707 case AddressSpace::Local:
1708 return spv::StorageClassWorkgroup;
1709 case AddressSpace::UniformConstant:
1710 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001711 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001712 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001713 case AddressSpace::ModuleScopePrivate:
1714 return spv::StorageClassPrivate;
1715 }
1716}
1717
David Neto862b7d82018-06-14 18:48:37 -04001718spv::StorageClass
1719SPIRVProducerPass::GetStorageClassForArgKind(clspv::ArgKind arg_kind) const {
1720 switch (arg_kind) {
1721 case clspv::ArgKind::Buffer:
1722 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001723 case clspv::ArgKind::BufferUBO:
1724 return spv::StorageClassUniform;
David Neto862b7d82018-06-14 18:48:37 -04001725 case clspv::ArgKind::Pod:
1726 return clspv::Option::PodArgsInUniformBuffer()
1727 ? spv::StorageClassUniform
1728 : spv::StorageClassStorageBuffer;
1729 case clspv::ArgKind::Local:
1730 return spv::StorageClassWorkgroup;
1731 case clspv::ArgKind::ReadOnlyImage:
1732 case clspv::ArgKind::WriteOnlyImage:
1733 case clspv::ArgKind::Sampler:
1734 return spv::StorageClassUniformConstant;
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001735 default:
1736 llvm_unreachable("Unsupported storage class for argument kind");
David Neto862b7d82018-06-14 18:48:37 -04001737 }
1738}
1739
David Neto22f144c2017-06-12 14:26:21 -04001740spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1741 return StringSwitch<spv::BuiltIn>(Name)
1742 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1743 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1744 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1745 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1746 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
1747 .Default(spv::BuiltInMax);
1748}
1749
1750void SPIRVProducerPass::GenerateExtInstImport() {
1751 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1752 uint32_t &ExtInstImportID = getOpExtInstImportID();
1753
1754 //
1755 // Generate OpExtInstImport.
1756 //
1757 // Ops[0] ... Ops[n] = Name (Literal String)
David Neto22f144c2017-06-12 14:26:21 -04001758 ExtInstImportID = nextID;
David Neto87846742018-04-11 17:36:22 -04001759 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpExtInstImport, nextID++,
1760 MkString("GLSL.std.450")));
David Neto22f144c2017-06-12 14:26:21 -04001761}
1762
alan-bakerb6b09dc2018-11-08 16:59:28 -05001763void SPIRVProducerPass::GenerateSPIRVTypes(LLVMContext &Context,
1764 Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04001765 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1766 ValueMapType &VMap = getValueMap();
1767 ValueMapType &AllocatedVMap = getAllocatedValueMap();
Alan Bakerfcda9482018-10-02 17:09:59 -04001768 const auto &DL = module.getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04001769
1770 // Map for OpTypeRuntimeArray. If argument has pointer type, 2 spirv type
1771 // instructions are generated. They are OpTypePointer and OpTypeRuntimeArray.
1772 DenseMap<Type *, uint32_t> OpRuntimeTyMap;
1773
1774 for (Type *Ty : getTypeList()) {
1775 // Update TypeMap with nextID for reference later.
1776 TypeMap[Ty] = nextID;
1777
1778 switch (Ty->getTypeID()) {
1779 default: {
1780 Ty->print(errs());
1781 llvm_unreachable("Unsupported type???");
1782 break;
1783 }
1784 case Type::MetadataTyID:
1785 case Type::LabelTyID: {
1786 // Ignore these types.
1787 break;
1788 }
1789 case Type::PointerTyID: {
1790 PointerType *PTy = cast<PointerType>(Ty);
1791 unsigned AddrSpace = PTy->getAddressSpace();
1792
1793 // For the purposes of our Vulkan SPIR-V type system, constant and global
1794 // are conflated.
1795 bool UseExistingOpTypePointer = false;
1796 if (AddressSpace::Constant == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001797 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1798 AddrSpace = AddressSpace::Global;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001799 // Check to see if we already created this type (for instance, if we
1800 // had a constant <type>* and a global <type>*, the type would be
1801 // created by one of these types, and shared by both).
Alan Bakerfcda9482018-10-02 17:09:59 -04001802 auto GlobalTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1803 if (0 < TypeMap.count(GlobalTy)) {
1804 TypeMap[PTy] = TypeMap[GlobalTy];
1805 UseExistingOpTypePointer = true;
1806 break;
1807 }
David Neto22f144c2017-06-12 14:26:21 -04001808 }
1809 } else if (AddressSpace::Global == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001810 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1811 AddrSpace = AddressSpace::Constant;
David Neto22f144c2017-06-12 14:26:21 -04001812
alan-bakerb6b09dc2018-11-08 16:59:28 -05001813 // Check to see if we already created this type (for instance, if we
1814 // had a constant <type>* and a global <type>*, the type would be
1815 // created by one of these types, and shared by both).
1816 auto ConstantTy =
1817 PTy->getPointerElementType()->getPointerTo(AddrSpace);
Alan Bakerfcda9482018-10-02 17:09:59 -04001818 if (0 < TypeMap.count(ConstantTy)) {
1819 TypeMap[PTy] = TypeMap[ConstantTy];
1820 UseExistingOpTypePointer = true;
1821 }
David Neto22f144c2017-06-12 14:26:21 -04001822 }
1823 }
1824
David Neto862b7d82018-06-14 18:48:37 -04001825 const bool HasArgUser = true;
David Neto22f144c2017-06-12 14:26:21 -04001826
David Neto862b7d82018-06-14 18:48:37 -04001827 if (HasArgUser && !UseExistingOpTypePointer) {
David Neto22f144c2017-06-12 14:26:21 -04001828 //
1829 // Generate OpTypePointer.
1830 //
1831
1832 // OpTypePointer
1833 // Ops[0] = Storage Class
1834 // Ops[1] = Element Type ID
1835 SPIRVOperandList Ops;
1836
David Neto257c3892018-04-11 13:19:45 -04001837 Ops << MkNum(GetStorageClass(AddrSpace))
1838 << MkId(lookupType(PTy->getElementType()));
David Neto22f144c2017-06-12 14:26:21 -04001839
David Neto87846742018-04-11 17:36:22 -04001840 auto *Inst = new SPIRVInstruction(spv::OpTypePointer, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001841 SPIRVInstList.push_back(Inst);
1842 }
David Neto22f144c2017-06-12 14:26:21 -04001843 break;
1844 }
1845 case Type::StructTyID: {
David Neto22f144c2017-06-12 14:26:21 -04001846 StructType *STy = cast<StructType>(Ty);
1847
1848 // Handle sampler type.
1849 if (STy->isOpaque()) {
1850 if (STy->getName().equals("opencl.sampler_t")) {
1851 //
1852 // Generate OpTypeSampler
1853 //
1854 // Empty Ops.
1855 SPIRVOperandList Ops;
1856
David Neto87846742018-04-11 17:36:22 -04001857 auto *Inst = new SPIRVInstruction(spv::OpTypeSampler, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001858 SPIRVInstList.push_back(Inst);
1859 break;
1860 } else if (STy->getName().equals("opencl.image2d_ro_t") ||
1861 STy->getName().equals("opencl.image2d_wo_t") ||
1862 STy->getName().equals("opencl.image3d_ro_t") ||
1863 STy->getName().equals("opencl.image3d_wo_t")) {
1864 //
1865 // Generate OpTypeImage
1866 //
1867 // Ops[0] = Sampled Type ID
1868 // Ops[1] = Dim ID
1869 // Ops[2] = Depth (Literal Number)
1870 // Ops[3] = Arrayed (Literal Number)
1871 // Ops[4] = MS (Literal Number)
1872 // Ops[5] = Sampled (Literal Number)
1873 // Ops[6] = Image Format ID
1874 //
1875 SPIRVOperandList Ops;
1876
1877 // TODO: Changed Sampled Type according to situations.
1878 uint32_t SampledTyID = lookupType(Type::getFloatTy(Context));
David Neto257c3892018-04-11 13:19:45 -04001879 Ops << MkId(SampledTyID);
David Neto22f144c2017-06-12 14:26:21 -04001880
1881 spv::Dim DimID = spv::Dim2D;
1882 if (STy->getName().equals("opencl.image3d_ro_t") ||
1883 STy->getName().equals("opencl.image3d_wo_t")) {
1884 DimID = spv::Dim3D;
1885 }
David Neto257c3892018-04-11 13:19:45 -04001886 Ops << MkNum(DimID);
David Neto22f144c2017-06-12 14:26:21 -04001887
1888 // TODO: Set up Depth.
David Neto257c3892018-04-11 13:19:45 -04001889 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001890
1891 // TODO: Set up Arrayed.
David Neto257c3892018-04-11 13:19:45 -04001892 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001893
1894 // TODO: Set up MS.
David Neto257c3892018-04-11 13:19:45 -04001895 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001896
1897 // TODO: Set up Sampled.
1898 //
1899 // From Spec
1900 //
1901 // 0 indicates this is only known at run time, not at compile time
1902 // 1 indicates will be used with sampler
1903 // 2 indicates will be used without a sampler (a storage image)
1904 uint32_t Sampled = 1;
1905 if (STy->getName().equals("opencl.image2d_wo_t") ||
1906 STy->getName().equals("opencl.image3d_wo_t")) {
1907 Sampled = 2;
1908 }
David Neto257c3892018-04-11 13:19:45 -04001909 Ops << MkNum(Sampled);
David Neto22f144c2017-06-12 14:26:21 -04001910
1911 // TODO: Set up Image Format.
David Neto257c3892018-04-11 13:19:45 -04001912 Ops << MkNum(spv::ImageFormatUnknown);
David Neto22f144c2017-06-12 14:26:21 -04001913
David Neto87846742018-04-11 17:36:22 -04001914 auto *Inst = new SPIRVInstruction(spv::OpTypeImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001915 SPIRVInstList.push_back(Inst);
1916 break;
1917 }
1918 }
1919
1920 //
1921 // Generate OpTypeStruct
1922 //
1923 // Ops[0] ... Ops[n] = Member IDs
1924 SPIRVOperandList Ops;
1925
1926 for (auto *EleTy : STy->elements()) {
David Neto862b7d82018-06-14 18:48:37 -04001927 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04001928 }
1929
David Neto22f144c2017-06-12 14:26:21 -04001930 uint32_t STyID = nextID;
1931
alan-bakerb6b09dc2018-11-08 16:59:28 -05001932 auto *Inst = new SPIRVInstruction(spv::OpTypeStruct, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001933 SPIRVInstList.push_back(Inst);
1934
1935 // Generate OpMemberDecorate.
1936 auto DecoInsertPoint =
1937 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
1938 [](SPIRVInstruction *Inst) -> bool {
1939 return Inst->getOpcode() != spv::OpDecorate &&
1940 Inst->getOpcode() != spv::OpMemberDecorate &&
1941 Inst->getOpcode() != spv::OpExtInstImport;
1942 });
1943
David Netoc463b372017-08-10 15:32:21 -04001944 const auto StructLayout = DL.getStructLayout(STy);
Alan Bakerfcda9482018-10-02 17:09:59 -04001945 // Search for the correct offsets if this type was remapped.
1946 std::vector<uint32_t> *offsets = nullptr;
1947 auto iter = RemappedUBOTypeOffsets.find(STy);
1948 if (iter != RemappedUBOTypeOffsets.end()) {
1949 offsets = &iter->second;
1950 }
David Netoc463b372017-08-10 15:32:21 -04001951
David Neto862b7d82018-06-14 18:48:37 -04001952 // #error TODO(dneto): Only do this if in TypesNeedingLayout.
David Neto22f144c2017-06-12 14:26:21 -04001953 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
1954 MemberIdx++) {
1955 // Ops[0] = Structure Type ID
1956 // Ops[1] = Member Index(Literal Number)
1957 // Ops[2] = Decoration (Offset)
1958 // Ops[3] = Byte Offset (Literal Number)
1959 Ops.clear();
1960
David Neto257c3892018-04-11 13:19:45 -04001961 Ops << MkId(STyID) << MkNum(MemberIdx) << MkNum(spv::DecorationOffset);
David Neto22f144c2017-06-12 14:26:21 -04001962
alan-bakerb6b09dc2018-11-08 16:59:28 -05001963 auto ByteOffset =
1964 static_cast<uint32_t>(StructLayout->getElementOffset(MemberIdx));
Alan Bakerfcda9482018-10-02 17:09:59 -04001965 if (offsets) {
1966 ByteOffset = (*offsets)[MemberIdx];
1967 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05001968 // const auto ByteOffset =
Alan Bakerfcda9482018-10-02 17:09:59 -04001969 // uint32_t(StructLayout->getElementOffset(MemberIdx));
David Neto257c3892018-04-11 13:19:45 -04001970 Ops << MkNum(ByteOffset);
David Neto22f144c2017-06-12 14:26:21 -04001971
David Neto87846742018-04-11 17:36:22 -04001972 auto *DecoInst = new SPIRVInstruction(spv::OpMemberDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001973 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04001974 }
1975
1976 // Generate OpDecorate.
David Neto862b7d82018-06-14 18:48:37 -04001977 if (StructTypesNeedingBlock.idFor(STy)) {
1978 Ops.clear();
1979 // Use Block decorations with StorageBuffer storage class.
1980 Ops << MkId(STyID) << MkNum(spv::DecorationBlock);
David Neto22f144c2017-06-12 14:26:21 -04001981
David Neto862b7d82018-06-14 18:48:37 -04001982 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
1983 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04001984 }
1985 break;
1986 }
1987 case Type::IntegerTyID: {
1988 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
1989
1990 if (BitWidth == 1) {
David Neto87846742018-04-11 17:36:22 -04001991 auto *Inst = new SPIRVInstruction(spv::OpTypeBool, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04001992 SPIRVInstList.push_back(Inst);
1993 } else {
alan-bakerb39c8262019-03-08 14:03:37 -05001994 if (!clspv::Option::Int8Support()) {
1995 // i8 is added to TypeMap as i32.
1996 // No matter what LLVM type is requested first, always alias the
1997 // second one's SPIR-V type to be the same as the one we generated
1998 // first.
1999 unsigned aliasToWidth = 0;
2000 if (BitWidth == 8) {
2001 aliasToWidth = 32;
2002 BitWidth = 32;
2003 } else if (BitWidth == 32) {
2004 aliasToWidth = 8;
2005 }
2006 if (aliasToWidth) {
2007 Type *otherType = Type::getIntNTy(Ty->getContext(), aliasToWidth);
2008 auto where = TypeMap.find(otherType);
2009 if (where == TypeMap.end()) {
2010 // Go ahead and make it, but also map the other type to it.
2011 TypeMap[otherType] = nextID;
2012 } else {
2013 // Alias this SPIR-V type the existing type.
2014 TypeMap[Ty] = where->second;
2015 break;
2016 }
David Neto391aeb12017-08-26 15:51:58 -04002017 }
David Neto22f144c2017-06-12 14:26:21 -04002018 }
2019
David Neto257c3892018-04-11 13:19:45 -04002020 SPIRVOperandList Ops;
2021 Ops << MkNum(BitWidth) << MkNum(0 /* not signed */);
David Neto22f144c2017-06-12 14:26:21 -04002022
2023 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002024 new SPIRVInstruction(spv::OpTypeInt, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002025 }
2026 break;
2027 }
2028 case Type::HalfTyID:
2029 case Type::FloatTyID:
2030 case Type::DoubleTyID: {
2031 SPIRVOperand *WidthOp = new SPIRVOperand(
2032 SPIRVOperandType::LITERAL_INTEGER, Ty->getPrimitiveSizeInBits());
2033
2034 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002035 new SPIRVInstruction(spv::OpTypeFloat, nextID++, WidthOp));
David Neto22f144c2017-06-12 14:26:21 -04002036 break;
2037 }
2038 case Type::ArrayTyID: {
David Neto22f144c2017-06-12 14:26:21 -04002039 ArrayType *ArrTy = cast<ArrayType>(Ty);
David Neto862b7d82018-06-14 18:48:37 -04002040 const uint64_t Length = ArrTy->getArrayNumElements();
2041 if (Length == 0) {
2042 // By convention, map it to a RuntimeArray.
David Neto22f144c2017-06-12 14:26:21 -04002043
David Neto862b7d82018-06-14 18:48:37 -04002044 // Only generate the type once.
2045 // TODO(dneto): Can it ever be generated more than once?
2046 // Doesn't LLVM type uniqueness guarantee we'll only see this
2047 // once?
2048 Type *EleTy = ArrTy->getArrayElementType();
2049 if (OpRuntimeTyMap.count(EleTy) == 0) {
2050 uint32_t OpTypeRuntimeArrayID = nextID;
2051 OpRuntimeTyMap[Ty] = nextID;
David Neto22f144c2017-06-12 14:26:21 -04002052
David Neto862b7d82018-06-14 18:48:37 -04002053 //
2054 // Generate OpTypeRuntimeArray.
2055 //
David Neto22f144c2017-06-12 14:26:21 -04002056
David Neto862b7d82018-06-14 18:48:37 -04002057 // OpTypeRuntimeArray
2058 // Ops[0] = Element Type ID
2059 SPIRVOperandList Ops;
2060 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04002061
David Neto862b7d82018-06-14 18:48:37 -04002062 SPIRVInstList.push_back(
2063 new SPIRVInstruction(spv::OpTypeRuntimeArray, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002064
David Neto862b7d82018-06-14 18:48:37 -04002065 if (Hack_generate_runtime_array_stride_early) {
2066 // Generate OpDecorate.
2067 auto DecoInsertPoint = std::find_if(
2068 SPIRVInstList.begin(), SPIRVInstList.end(),
2069 [](SPIRVInstruction *Inst) -> bool {
2070 return Inst->getOpcode() != spv::OpDecorate &&
2071 Inst->getOpcode() != spv::OpMemberDecorate &&
2072 Inst->getOpcode() != spv::OpExtInstImport;
2073 });
David Neto22f144c2017-06-12 14:26:21 -04002074
David Neto862b7d82018-06-14 18:48:37 -04002075 // Ops[0] = Target ID
2076 // Ops[1] = Decoration (ArrayStride)
2077 // Ops[2] = Stride Number(Literal Number)
2078 Ops.clear();
David Neto85082642018-03-24 06:55:20 -07002079
David Neto862b7d82018-06-14 18:48:37 -04002080 Ops << MkId(OpTypeRuntimeArrayID)
2081 << MkNum(spv::DecorationArrayStride)
Alan Bakerfcda9482018-10-02 17:09:59 -04002082 << MkNum(static_cast<uint32_t>(GetTypeAllocSize(EleTy, DL)));
David Neto22f144c2017-06-12 14:26:21 -04002083
David Neto862b7d82018-06-14 18:48:37 -04002084 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
2085 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
2086 }
2087 }
David Neto22f144c2017-06-12 14:26:21 -04002088
David Neto862b7d82018-06-14 18:48:37 -04002089 } else {
David Neto22f144c2017-06-12 14:26:21 -04002090
David Neto862b7d82018-06-14 18:48:37 -04002091 //
2092 // Generate OpConstant and OpTypeArray.
2093 //
2094
2095 //
2096 // Generate OpConstant for array length.
2097 //
2098 // Ops[0] = Result Type ID
2099 // Ops[1] .. Ops[n] = Values LiteralNumber
2100 SPIRVOperandList Ops;
2101
2102 Type *LengthTy = Type::getInt32Ty(Context);
2103 uint32_t ResTyID = lookupType(LengthTy);
2104 Ops << MkId(ResTyID);
2105
2106 assert(Length < UINT32_MAX);
2107 Ops << MkNum(static_cast<uint32_t>(Length));
2108
2109 // Add constant for length to constant list.
2110 Constant *CstLength = ConstantInt::get(LengthTy, Length);
2111 AllocatedVMap[CstLength] = nextID;
2112 VMap[CstLength] = nextID;
2113 uint32_t LengthID = nextID;
2114
2115 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
2116 SPIRVInstList.push_back(CstInst);
2117
2118 // Remember to generate ArrayStride later
2119 getTypesNeedingArrayStride().insert(Ty);
2120
2121 //
2122 // Generate OpTypeArray.
2123 //
2124 // Ops[0] = Element Type ID
2125 // Ops[1] = Array Length Constant ID
2126 Ops.clear();
2127
2128 uint32_t EleTyID = lookupType(ArrTy->getElementType());
2129 Ops << MkId(EleTyID) << MkId(LengthID);
2130
2131 // Update TypeMap with nextID.
2132 TypeMap[Ty] = nextID;
2133
2134 auto *ArrayInst = new SPIRVInstruction(spv::OpTypeArray, nextID++, Ops);
2135 SPIRVInstList.push_back(ArrayInst);
2136 }
David Neto22f144c2017-06-12 14:26:21 -04002137 break;
2138 }
2139 case Type::VectorTyID: {
alan-bakerb39c8262019-03-08 14:03:37 -05002140 // <4 x i8> is changed to i32 if i8 is not generally supported.
2141 if (!clspv::Option::Int8Support() &&
2142 Ty->getVectorElementType() == Type::getInt8Ty(Context)) {
David Neto22f144c2017-06-12 14:26:21 -04002143 if (Ty->getVectorNumElements() == 4) {
2144 TypeMap[Ty] = lookupType(Ty->getVectorElementType());
2145 break;
2146 } else {
2147 Ty->print(errs());
2148 llvm_unreachable("Support above i8 vector type");
2149 }
2150 }
2151
2152 // Ops[0] = Component Type ID
2153 // Ops[1] = Component Count (Literal Number)
David Neto257c3892018-04-11 13:19:45 -04002154 SPIRVOperandList Ops;
2155 Ops << MkId(lookupType(Ty->getVectorElementType()))
2156 << MkNum(Ty->getVectorNumElements());
David Neto22f144c2017-06-12 14:26:21 -04002157
alan-bakerb6b09dc2018-11-08 16:59:28 -05002158 SPIRVInstruction *inst =
2159 new SPIRVInstruction(spv::OpTypeVector, nextID++, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002160 SPIRVInstList.push_back(inst);
David Neto22f144c2017-06-12 14:26:21 -04002161 break;
2162 }
2163 case Type::VoidTyID: {
David Neto87846742018-04-11 17:36:22 -04002164 auto *Inst = new SPIRVInstruction(spv::OpTypeVoid, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04002165 SPIRVInstList.push_back(Inst);
2166 break;
2167 }
2168 case Type::FunctionTyID: {
2169 // Generate SPIRV instruction for function type.
2170 FunctionType *FTy = cast<FunctionType>(Ty);
2171
2172 // Ops[0] = Return Type ID
2173 // Ops[1] ... Ops[n] = Parameter Type IDs
2174 SPIRVOperandList Ops;
2175
2176 // Find SPIRV instruction for return type
David Netoc6f3ab22018-04-06 18:02:31 -04002177 Ops << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04002178
2179 // Find SPIRV instructions for parameter types
2180 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
2181 // Find SPIRV instruction for parameter type.
2182 auto ParamTy = FTy->getParamType(k);
2183 if (ParamTy->isPointerTy()) {
2184 auto PointeeTy = ParamTy->getPointerElementType();
2185 if (PointeeTy->isStructTy() &&
2186 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
2187 ParamTy = PointeeTy;
2188 }
2189 }
2190
David Netoc6f3ab22018-04-06 18:02:31 -04002191 Ops << MkId(lookupType(ParamTy));
David Neto22f144c2017-06-12 14:26:21 -04002192 }
2193
David Neto87846742018-04-11 17:36:22 -04002194 auto *Inst = new SPIRVInstruction(spv::OpTypeFunction, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002195 SPIRVInstList.push_back(Inst);
2196 break;
2197 }
2198 }
2199 }
2200
2201 // Generate OpTypeSampledImage.
2202 TypeMapType &OpImageTypeMap = getImageTypeMap();
2203 for (auto &ImageType : OpImageTypeMap) {
2204 //
2205 // Generate OpTypeSampledImage.
2206 //
2207 // Ops[0] = Image Type ID
2208 //
2209 SPIRVOperandList Ops;
2210
2211 Type *ImgTy = ImageType.first;
David Netoc6f3ab22018-04-06 18:02:31 -04002212 Ops << MkId(TypeMap[ImgTy]);
David Neto22f144c2017-06-12 14:26:21 -04002213
2214 // Update OpImageTypeMap.
2215 ImageType.second = nextID;
2216
David Neto87846742018-04-11 17:36:22 -04002217 auto *Inst = new SPIRVInstruction(spv::OpTypeSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002218 SPIRVInstList.push_back(Inst);
2219 }
David Netoc6f3ab22018-04-06 18:02:31 -04002220
2221 // Generate types for pointer-to-local arguments.
Alan Baker202c8c72018-08-13 13:47:44 -04002222 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2223 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002224 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002225
2226 // Generate the spec constant.
2227 SPIRVOperandList Ops;
2228 Ops << MkId(lookupType(Type::getInt32Ty(Context))) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04002229 SPIRVInstList.push_back(
2230 new SPIRVInstruction(spv::OpSpecConstant, arg_info.array_size_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002231
2232 // Generate the array type.
2233 Ops.clear();
2234 // The element type must have been created.
2235 uint32_t elem_ty_id = lookupType(arg_info.elem_type);
2236 assert(elem_ty_id);
2237 Ops << MkId(elem_ty_id) << MkId(arg_info.array_size_id);
2238
2239 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002240 new SPIRVInstruction(spv::OpTypeArray, arg_info.array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002241
2242 Ops.clear();
2243 Ops << MkNum(spv::StorageClassWorkgroup) << MkId(arg_info.array_type_id);
David Neto87846742018-04-11 17:36:22 -04002244 SPIRVInstList.push_back(new SPIRVInstruction(
2245 spv::OpTypePointer, arg_info.ptr_array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002246 }
David Neto22f144c2017-06-12 14:26:21 -04002247}
2248
2249void SPIRVProducerPass::GenerateSPIRVConstants() {
2250 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2251 ValueMapType &VMap = getValueMap();
2252 ValueMapType &AllocatedVMap = getAllocatedValueMap();
2253 ValueList &CstList = getConstantList();
David Neto482550a2018-03-24 05:21:07 -07002254 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04002255
2256 for (uint32_t i = 0; i < CstList.size(); i++) {
David Netofb9a7972017-08-25 17:08:24 -04002257 // UniqueVector ids are 1-based.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002258 Constant *Cst = cast<Constant>(CstList[i + 1]);
David Neto22f144c2017-06-12 14:26:21 -04002259
2260 // OpTypeArray's constant was already generated.
David Netofb9a7972017-08-25 17:08:24 -04002261 if (AllocatedVMap.find_as(Cst) != AllocatedVMap.end()) {
David Neto22f144c2017-06-12 14:26:21 -04002262 continue;
2263 }
2264
David Netofb9a7972017-08-25 17:08:24 -04002265 // Set ValueMap with nextID for reference later.
David Neto22f144c2017-06-12 14:26:21 -04002266 VMap[Cst] = nextID;
2267
2268 //
2269 // Generate OpConstant.
2270 //
2271
2272 // Ops[0] = Result Type ID
2273 // Ops[1] .. Ops[n] = Values LiteralNumber
2274 SPIRVOperandList Ops;
2275
David Neto257c3892018-04-11 13:19:45 -04002276 Ops << MkId(lookupType(Cst->getType()));
David Neto22f144c2017-06-12 14:26:21 -04002277
2278 std::vector<uint32_t> LiteralNum;
David Neto22f144c2017-06-12 14:26:21 -04002279 spv::Op Opcode = spv::OpNop;
2280
2281 if (isa<UndefValue>(Cst)) {
2282 // Ops[0] = Result Type ID
David Netoc66b3352017-10-20 14:28:46 -04002283 Opcode = spv::OpUndef;
Alan Baker9bf93fb2018-08-28 16:59:26 -04002284 if (hack_undef && IsTypeNullable(Cst->getType())) {
2285 Opcode = spv::OpConstantNull;
David Netoc66b3352017-10-20 14:28:46 -04002286 }
David Neto22f144c2017-06-12 14:26:21 -04002287 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
2288 unsigned BitWidth = CI->getBitWidth();
2289 if (BitWidth == 1) {
2290 // If the bitwidth of constant is 1, generate OpConstantTrue or
2291 // OpConstantFalse.
2292 if (CI->getZExtValue()) {
2293 // Ops[0] = Result Type ID
2294 Opcode = spv::OpConstantTrue;
2295 } else {
2296 // Ops[0] = Result Type ID
2297 Opcode = spv::OpConstantFalse;
2298 }
David Neto22f144c2017-06-12 14:26:21 -04002299 } else {
2300 auto V = CI->getZExtValue();
2301 LiteralNum.push_back(V & 0xFFFFFFFF);
2302
2303 if (BitWidth > 32) {
2304 LiteralNum.push_back(V >> 32);
2305 }
2306
2307 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002308
David Neto257c3892018-04-11 13:19:45 -04002309 Ops << MkInteger(LiteralNum);
2310
2311 if (BitWidth == 32 && V == 0) {
2312 constant_i32_zero_id_ = nextID;
2313 }
David Neto22f144c2017-06-12 14:26:21 -04002314 }
2315 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2316 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2317 Type *CFPTy = CFP->getType();
2318 if (CFPTy->isFloatTy()) {
2319 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
Kévin Petit02ee34e2019-04-04 19:03:22 +01002320 } else if (CFPTy->isDoubleTy()) {
2321 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2322 LiteralNum.push_back(FPVal >> 32);
David Neto22f144c2017-06-12 14:26:21 -04002323 } else {
2324 CFPTy->print(errs());
2325 llvm_unreachable("Implement this ConstantFP Type");
2326 }
2327
2328 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002329
David Neto257c3892018-04-11 13:19:45 -04002330 Ops << MkFloat(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002331 } else if (isa<ConstantDataSequential>(Cst) &&
2332 cast<ConstantDataSequential>(Cst)->isString()) {
2333 Cst->print(errs());
2334 llvm_unreachable("Implement this Constant");
2335
2336 } else if (const ConstantDataSequential *CDS =
2337 dyn_cast<ConstantDataSequential>(Cst)) {
David Neto49351ac2017-08-26 17:32:20 -04002338 // Let's convert <4 x i8> constant to int constant specially.
2339 // This case occurs when all the values are specified as constant
2340 // ints.
2341 Type *CstTy = Cst->getType();
2342 if (is4xi8vec(CstTy)) {
2343 LLVMContext &Context = CstTy->getContext();
2344
2345 //
2346 // Generate OpConstant with OpTypeInt 32 0.
2347 //
Neil Henning39672102017-09-29 14:33:13 +01002348 uint32_t IntValue = 0;
2349 for (unsigned k = 0; k < 4; k++) {
2350 const uint64_t Val = CDS->getElementAsInteger(k);
David Neto49351ac2017-08-26 17:32:20 -04002351 IntValue = (IntValue << 8) | (Val & 0xffu);
2352 }
2353
2354 Type *i32 = Type::getInt32Ty(Context);
2355 Constant *CstInt = ConstantInt::get(i32, IntValue);
2356 // If this constant is already registered on VMap, use it.
2357 if (VMap.count(CstInt)) {
2358 uint32_t CstID = VMap[CstInt];
2359 VMap[Cst] = CstID;
2360 continue;
2361 }
2362
David Neto257c3892018-04-11 13:19:45 -04002363 Ops << MkNum(IntValue);
David Neto49351ac2017-08-26 17:32:20 -04002364
David Neto87846742018-04-11 17:36:22 -04002365 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto49351ac2017-08-26 17:32:20 -04002366 SPIRVInstList.push_back(CstInst);
2367
2368 continue;
2369 }
2370
2371 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002372 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
2373 Constant *EleCst = CDS->getElementAsConstant(k);
2374 uint32_t EleCstID = VMap[EleCst];
David Neto257c3892018-04-11 13:19:45 -04002375 Ops << MkId(EleCstID);
David Neto22f144c2017-06-12 14:26:21 -04002376 }
2377
2378 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002379 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2380 // Let's convert <4 x i8> constant to int constant specially.
David Neto49351ac2017-08-26 17:32:20 -04002381 // This case occurs when at least one of the values is an undef.
David Neto22f144c2017-06-12 14:26:21 -04002382 Type *CstTy = Cst->getType();
2383 if (is4xi8vec(CstTy)) {
2384 LLVMContext &Context = CstTy->getContext();
2385
2386 //
2387 // Generate OpConstant with OpTypeInt 32 0.
2388 //
Neil Henning39672102017-09-29 14:33:13 +01002389 uint32_t IntValue = 0;
David Neto22f144c2017-06-12 14:26:21 -04002390 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2391 I != E; ++I) {
2392 uint64_t Val = 0;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002393 const Value *CV = *I;
Neil Henning39672102017-09-29 14:33:13 +01002394 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2395 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002396 }
David Neto49351ac2017-08-26 17:32:20 -04002397 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002398 }
2399
David Neto49351ac2017-08-26 17:32:20 -04002400 Type *i32 = Type::getInt32Ty(Context);
2401 Constant *CstInt = ConstantInt::get(i32, IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002402 // If this constant is already registered on VMap, use it.
2403 if (VMap.count(CstInt)) {
2404 uint32_t CstID = VMap[CstInt];
2405 VMap[Cst] = CstID;
David Neto19a1bad2017-08-25 15:01:41 -04002406 continue;
David Neto22f144c2017-06-12 14:26:21 -04002407 }
2408
David Neto257c3892018-04-11 13:19:45 -04002409 Ops << MkNum(IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002410
David Neto87846742018-04-11 17:36:22 -04002411 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002412 SPIRVInstList.push_back(CstInst);
2413
David Neto19a1bad2017-08-25 15:01:41 -04002414 continue;
David Neto22f144c2017-06-12 14:26:21 -04002415 }
2416
2417 // We use a constant composite in SPIR-V for our constant aggregate in
2418 // LLVM.
2419 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002420
2421 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
2422 // Look up the ID of the element of this aggregate (which we will
2423 // previously have created a constant for).
2424 uint32_t ElementConstantID = VMap[CA->getAggregateElement(k)];
2425
2426 // And add an operand to the composite we are constructing
David Neto257c3892018-04-11 13:19:45 -04002427 Ops << MkId(ElementConstantID);
David Neto22f144c2017-06-12 14:26:21 -04002428 }
2429 } else if (Cst->isNullValue()) {
2430 Opcode = spv::OpConstantNull;
David Neto22f144c2017-06-12 14:26:21 -04002431 } else {
2432 Cst->print(errs());
2433 llvm_unreachable("Unsupported Constant???");
2434 }
2435
alan-baker5b86ed72019-02-15 08:26:50 -05002436 if (Opcode == spv::OpConstantNull && Cst->getType()->isPointerTy()) {
2437 // Null pointer requires variable pointers.
2438 setVariablePointersCapabilities(Cst->getType()->getPointerAddressSpace());
2439 }
2440
David Neto87846742018-04-11 17:36:22 -04002441 auto *CstInst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002442 SPIRVInstList.push_back(CstInst);
2443 }
2444}
2445
2446void SPIRVProducerPass::GenerateSamplers(Module &M) {
2447 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto22f144c2017-06-12 14:26:21 -04002448
alan-bakerb6b09dc2018-11-08 16:59:28 -05002449 auto &sampler_map = getSamplerMap();
David Neto862b7d82018-06-14 18:48:37 -04002450 SamplerMapIndexToIDMap.clear();
David Neto22f144c2017-06-12 14:26:21 -04002451 DenseMap<unsigned, unsigned> SamplerLiteralToIDMap;
David Neto862b7d82018-06-14 18:48:37 -04002452 DenseMap<unsigned, unsigned> SamplerLiteralToDescriptorSetMap;
2453 DenseMap<unsigned, unsigned> SamplerLiteralToBindingMap;
David Neto22f144c2017-06-12 14:26:21 -04002454
David Neto862b7d82018-06-14 18:48:37 -04002455 // We might have samplers in the sampler map that are not used
2456 // in the translation unit. We need to allocate variables
2457 // for them and bindings too.
2458 DenseSet<unsigned> used_bindings;
David Neto22f144c2017-06-12 14:26:21 -04002459
Kévin Petitdf71de32019-04-09 14:09:50 +01002460 auto *var_fn = M.getFunction(clspv::LiteralSamplerFunction());
alan-bakerb6b09dc2018-11-08 16:59:28 -05002461 if (!var_fn)
2462 return;
David Neto862b7d82018-06-14 18:48:37 -04002463 for (auto user : var_fn->users()) {
2464 // Populate SamplerLiteralToDescriptorSetMap and
2465 // SamplerLiteralToBindingMap.
2466 //
2467 // Look for calls like
2468 // call %opencl.sampler_t addrspace(2)*
2469 // @clspv.sampler.var.literal(
2470 // i32 descriptor,
2471 // i32 binding,
2472 // i32 index-into-sampler-map)
alan-bakerb6b09dc2018-11-08 16:59:28 -05002473 if (auto *call = dyn_cast<CallInst>(user)) {
2474 const size_t index_into_sampler_map = static_cast<size_t>(
2475 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04002476 if (index_into_sampler_map >= sampler_map.size()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002477 errs() << "Out of bounds index to sampler map: "
2478 << index_into_sampler_map;
David Neto862b7d82018-06-14 18:48:37 -04002479 llvm_unreachable("bad sampler init: out of bounds");
2480 }
2481
2482 auto sampler_value = sampler_map[index_into_sampler_map].first;
2483 const auto descriptor_set = static_cast<unsigned>(
2484 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
2485 const auto binding = static_cast<unsigned>(
2486 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
2487
2488 SamplerLiteralToDescriptorSetMap[sampler_value] = descriptor_set;
2489 SamplerLiteralToBindingMap[sampler_value] = binding;
2490 used_bindings.insert(binding);
2491 }
2492 }
2493
2494 unsigned index = 0;
2495 for (auto SamplerLiteral : sampler_map) {
David Neto22f144c2017-06-12 14:26:21 -04002496 // Generate OpVariable.
2497 //
2498 // GIDOps[0] : Result Type ID
2499 // GIDOps[1] : Storage Class
2500 SPIRVOperandList Ops;
2501
David Neto257c3892018-04-11 13:19:45 -04002502 Ops << MkId(lookupType(SamplerTy))
2503 << MkNum(spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002504
David Neto862b7d82018-06-14 18:48:37 -04002505 auto sampler_var_id = nextID++;
2506 auto *Inst = new SPIRVInstruction(spv::OpVariable, sampler_var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002507 SPIRVInstList.push_back(Inst);
2508
David Neto862b7d82018-06-14 18:48:37 -04002509 SamplerMapIndexToIDMap[index] = sampler_var_id;
2510 SamplerLiteralToIDMap[SamplerLiteral.first] = sampler_var_id;
David Neto22f144c2017-06-12 14:26:21 -04002511
2512 // Find Insert Point for OpDecorate.
2513 auto DecoInsertPoint =
2514 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2515 [](SPIRVInstruction *Inst) -> bool {
2516 return Inst->getOpcode() != spv::OpDecorate &&
2517 Inst->getOpcode() != spv::OpMemberDecorate &&
2518 Inst->getOpcode() != spv::OpExtInstImport;
2519 });
2520
2521 // Ops[0] = Target ID
2522 // Ops[1] = Decoration (DescriptorSet)
2523 // Ops[2] = LiteralNumber according to Decoration
2524 Ops.clear();
2525
David Neto862b7d82018-06-14 18:48:37 -04002526 unsigned descriptor_set;
2527 unsigned binding;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002528 if (SamplerLiteralToBindingMap.find(SamplerLiteral.first) ==
2529 SamplerLiteralToBindingMap.end()) {
David Neto862b7d82018-06-14 18:48:37 -04002530 // This sampler is not actually used. Find the next one.
2531 for (binding = 0; used_bindings.count(binding); binding++)
2532 ;
2533 descriptor_set = 0; // Literal samplers always use descriptor set 0.
2534 used_bindings.insert(binding);
2535 } else {
2536 descriptor_set = SamplerLiteralToDescriptorSetMap[SamplerLiteral.first];
2537 binding = SamplerLiteralToBindingMap[SamplerLiteral.first];
2538 }
2539
2540 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationDescriptorSet)
2541 << MkNum(descriptor_set);
David Neto22f144c2017-06-12 14:26:21 -04002542
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002543 version0::DescriptorMapEntry::SamplerData sampler_data = {
2544 SamplerLiteral.first};
2545 descriptorMapEntries->emplace_back(std::move(sampler_data), descriptor_set,
2546 binding);
David Neto22f144c2017-06-12 14:26:21 -04002547
David Neto87846742018-04-11 17:36:22 -04002548 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002549 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2550
2551 // Ops[0] = Target ID
2552 // Ops[1] = Decoration (Binding)
2553 // Ops[2] = LiteralNumber according to Decoration
2554 Ops.clear();
David Neto862b7d82018-06-14 18:48:37 -04002555 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationBinding)
2556 << MkNum(binding);
David Neto22f144c2017-06-12 14:26:21 -04002557
David Neto87846742018-04-11 17:36:22 -04002558 auto *BindDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002559 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
David Neto862b7d82018-06-14 18:48:37 -04002560
2561 index++;
David Neto22f144c2017-06-12 14:26:21 -04002562 }
David Neto862b7d82018-06-14 18:48:37 -04002563}
David Neto22f144c2017-06-12 14:26:21 -04002564
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01002565void SPIRVProducerPass::GenerateResourceVars(Module &) {
David Neto862b7d82018-06-14 18:48:37 -04002566 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2567 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04002568
David Neto862b7d82018-06-14 18:48:37 -04002569 // Generate variables. Make one for each of resource var info object.
2570 for (auto *info : ModuleOrderedResourceVars) {
2571 Type *type = info->var_fn->getReturnType();
2572 // Remap the address space for opaque types.
2573 switch (info->arg_kind) {
2574 case clspv::ArgKind::Sampler:
2575 case clspv::ArgKind::ReadOnlyImage:
2576 case clspv::ArgKind::WriteOnlyImage:
2577 type = PointerType::get(type->getPointerElementType(),
2578 clspv::AddressSpace::UniformConstant);
2579 break;
2580 default:
2581 break;
2582 }
David Neto22f144c2017-06-12 14:26:21 -04002583
David Neto862b7d82018-06-14 18:48:37 -04002584 info->var_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04002585
David Neto862b7d82018-06-14 18:48:37 -04002586 const auto type_id = lookupType(type);
2587 const auto sc = GetStorageClassForArgKind(info->arg_kind);
2588 SPIRVOperandList Ops;
2589 Ops << MkId(type_id) << MkNum(sc);
David Neto22f144c2017-06-12 14:26:21 -04002590
David Neto862b7d82018-06-14 18:48:37 -04002591 auto *Inst = new SPIRVInstruction(spv::OpVariable, info->var_id, Ops);
2592 SPIRVInstList.push_back(Inst);
2593
2594 // Map calls to the variable-builtin-function.
2595 for (auto &U : info->var_fn->uses()) {
2596 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
2597 const auto set = unsigned(
2598 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
2599 const auto binding = unsigned(
2600 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
2601 if (set == info->descriptor_set && binding == info->binding) {
2602 switch (info->arg_kind) {
2603 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002604 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002605 case clspv::ArgKind::Pod:
2606 // The call maps to the variable directly.
2607 VMap[call] = info->var_id;
2608 break;
2609 case clspv::ArgKind::Sampler:
2610 case clspv::ArgKind::ReadOnlyImage:
2611 case clspv::ArgKind::WriteOnlyImage:
2612 // The call maps to a load we generate later.
2613 ResourceVarDeferredLoadCalls[call] = info->var_id;
2614 break;
2615 default:
2616 llvm_unreachable("Unhandled arg kind");
2617 }
2618 }
David Neto22f144c2017-06-12 14:26:21 -04002619 }
David Neto862b7d82018-06-14 18:48:37 -04002620 }
2621 }
David Neto22f144c2017-06-12 14:26:21 -04002622
David Neto862b7d82018-06-14 18:48:37 -04002623 // Generate associated decorations.
David Neto22f144c2017-06-12 14:26:21 -04002624
David Neto862b7d82018-06-14 18:48:37 -04002625 // Find Insert Point for OpDecorate.
2626 auto DecoInsertPoint =
2627 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2628 [](SPIRVInstruction *Inst) -> bool {
2629 return Inst->getOpcode() != spv::OpDecorate &&
2630 Inst->getOpcode() != spv::OpMemberDecorate &&
2631 Inst->getOpcode() != spv::OpExtInstImport;
2632 });
2633
2634 SPIRVOperandList Ops;
2635 for (auto *info : ModuleOrderedResourceVars) {
2636 // Decorate with DescriptorSet and Binding.
2637 Ops.clear();
2638 Ops << MkId(info->var_id) << MkNum(spv::DecorationDescriptorSet)
2639 << MkNum(info->descriptor_set);
2640 SPIRVInstList.insert(DecoInsertPoint,
2641 new SPIRVInstruction(spv::OpDecorate, Ops));
2642
2643 Ops.clear();
2644 Ops << MkId(info->var_id) << MkNum(spv::DecorationBinding)
2645 << MkNum(info->binding);
2646 SPIRVInstList.insert(DecoInsertPoint,
2647 new SPIRVInstruction(spv::OpDecorate, Ops));
2648
alan-bakere9308012019-03-15 10:25:13 -04002649 if (info->coherent) {
2650 // Decorate with Coherent if required for the variable.
2651 Ops.clear();
2652 Ops << MkId(info->var_id) << MkNum(spv::DecorationCoherent);
2653 SPIRVInstList.insert(DecoInsertPoint,
2654 new SPIRVInstruction(spv::OpDecorate, Ops));
2655 }
2656
David Neto862b7d82018-06-14 18:48:37 -04002657 // Generate NonWritable and NonReadable
2658 switch (info->arg_kind) {
2659 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002660 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002661 if (info->var_fn->getReturnType()->getPointerAddressSpace() ==
2662 clspv::AddressSpace::Constant) {
2663 Ops.clear();
2664 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
2665 SPIRVInstList.insert(DecoInsertPoint,
2666 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002667 }
David Neto862b7d82018-06-14 18:48:37 -04002668 break;
David Neto862b7d82018-06-14 18:48:37 -04002669 case clspv::ArgKind::WriteOnlyImage:
2670 Ops.clear();
2671 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonReadable);
2672 SPIRVInstList.insert(DecoInsertPoint,
2673 new SPIRVInstruction(spv::OpDecorate, Ops));
2674 break;
2675 default:
2676 break;
David Neto22f144c2017-06-12 14:26:21 -04002677 }
2678 }
2679}
2680
2681void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002682 Module &M = *GV.getParent();
David Neto22f144c2017-06-12 14:26:21 -04002683 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2684 ValueMapType &VMap = getValueMap();
2685 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07002686 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002687
2688 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2689 Type *Ty = GV.getType();
2690 PointerType *PTy = cast<PointerType>(Ty);
2691
2692 uint32_t InitializerID = 0;
2693
2694 // Workgroup size is handled differently (it goes into a constant)
2695 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2696 std::vector<bool> HasMDVec;
2697 uint32_t PrevXDimCst = 0xFFFFFFFF;
2698 uint32_t PrevYDimCst = 0xFFFFFFFF;
2699 uint32_t PrevZDimCst = 0xFFFFFFFF;
2700 for (Function &Func : *GV.getParent()) {
2701 if (Func.isDeclaration()) {
2702 continue;
2703 }
2704
2705 // We only need to check kernels.
2706 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2707 continue;
2708 }
2709
2710 if (const MDNode *MD =
2711 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2712 uint32_t CurXDimCst = static_cast<uint32_t>(
2713 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2714 uint32_t CurYDimCst = static_cast<uint32_t>(
2715 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2716 uint32_t CurZDimCst = static_cast<uint32_t>(
2717 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2718
2719 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2720 PrevZDimCst == 0xFFFFFFFF) {
2721 PrevXDimCst = CurXDimCst;
2722 PrevYDimCst = CurYDimCst;
2723 PrevZDimCst = CurZDimCst;
2724 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2725 CurZDimCst != PrevZDimCst) {
2726 llvm_unreachable(
2727 "reqd_work_group_size must be the same across all kernels");
2728 } else {
2729 continue;
2730 }
2731
2732 //
2733 // Generate OpConstantComposite.
2734 //
2735 // Ops[0] : Result Type ID
2736 // Ops[1] : Constant size for x dimension.
2737 // Ops[2] : Constant size for y dimension.
2738 // Ops[3] : Constant size for z dimension.
2739 SPIRVOperandList Ops;
2740
2741 uint32_t XDimCstID =
2742 VMap[mdconst::extract<ConstantInt>(MD->getOperand(0))];
2743 uint32_t YDimCstID =
2744 VMap[mdconst::extract<ConstantInt>(MD->getOperand(1))];
2745 uint32_t ZDimCstID =
2746 VMap[mdconst::extract<ConstantInt>(MD->getOperand(2))];
2747
2748 InitializerID = nextID;
2749
David Neto257c3892018-04-11 13:19:45 -04002750 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2751 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002752
David Neto87846742018-04-11 17:36:22 -04002753 auto *Inst =
2754 new SPIRVInstruction(spv::OpConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002755 SPIRVInstList.push_back(Inst);
2756
2757 HasMDVec.push_back(true);
2758 } else {
2759 HasMDVec.push_back(false);
2760 }
2761 }
2762
2763 // Check all kernels have same definitions for work_group_size.
2764 bool HasMD = false;
2765 if (!HasMDVec.empty()) {
2766 HasMD = HasMDVec[0];
2767 for (uint32_t i = 1; i < HasMDVec.size(); i++) {
2768 if (HasMD != HasMDVec[i]) {
2769 llvm_unreachable(
2770 "Kernels should have consistent work group size definition");
2771 }
2772 }
2773 }
2774
2775 // If all kernels do not have metadata for reqd_work_group_size, generate
2776 // OpSpecConstants for x/y/z dimension.
2777 if (!HasMD) {
2778 //
2779 // Generate OpSpecConstants for x/y/z dimension.
2780 //
2781 // Ops[0] : Result Type ID
2782 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
2783 uint32_t XDimCstID = 0;
2784 uint32_t YDimCstID = 0;
2785 uint32_t ZDimCstID = 0;
2786
David Neto22f144c2017-06-12 14:26:21 -04002787 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04002788 uint32_t result_type_id =
2789 lookupType(Ty->getPointerElementType()->getSequentialElementType());
David Neto22f144c2017-06-12 14:26:21 -04002790
David Neto257c3892018-04-11 13:19:45 -04002791 // X Dimension
2792 Ops << MkId(result_type_id) << MkNum(1);
2793 XDimCstID = nextID++;
2794 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002795 new SPIRVInstruction(spv::OpSpecConstant, XDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002796
2797 // Y Dimension
2798 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002799 Ops << MkId(result_type_id) << MkNum(1);
2800 YDimCstID = nextID++;
2801 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002802 new SPIRVInstruction(spv::OpSpecConstant, YDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002803
2804 // Z Dimension
2805 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002806 Ops << MkId(result_type_id) << MkNum(1);
2807 ZDimCstID = nextID++;
2808 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002809 new SPIRVInstruction(spv::OpSpecConstant, ZDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002810
David Neto257c3892018-04-11 13:19:45 -04002811 BuiltinDimVec.push_back(XDimCstID);
2812 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002813 BuiltinDimVec.push_back(ZDimCstID);
2814
David Neto22f144c2017-06-12 14:26:21 -04002815 //
2816 // Generate OpSpecConstantComposite.
2817 //
2818 // Ops[0] : Result Type ID
2819 // Ops[1] : Constant size for x dimension.
2820 // Ops[2] : Constant size for y dimension.
2821 // Ops[3] : Constant size for z dimension.
2822 InitializerID = nextID;
2823
2824 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002825 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2826 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002827
David Neto87846742018-04-11 17:36:22 -04002828 auto *Inst =
2829 new SPIRVInstruction(spv::OpSpecConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002830 SPIRVInstList.push_back(Inst);
2831 }
2832 }
2833
David Neto22f144c2017-06-12 14:26:21 -04002834 VMap[&GV] = nextID;
2835
2836 //
2837 // Generate OpVariable.
2838 //
2839 // GIDOps[0] : Result Type ID
2840 // GIDOps[1] : Storage Class
2841 SPIRVOperandList Ops;
2842
David Neto85082642018-03-24 06:55:20 -07002843 const auto AS = PTy->getAddressSpace();
David Netoc6f3ab22018-04-06 18:02:31 -04002844 Ops << MkId(lookupType(Ty)) << MkNum(GetStorageClass(AS));
David Neto22f144c2017-06-12 14:26:21 -04002845
David Neto85082642018-03-24 06:55:20 -07002846 if (GV.hasInitializer()) {
2847 InitializerID = VMap[GV.getInitializer()];
David Neto22f144c2017-06-12 14:26:21 -04002848 }
2849
David Neto85082642018-03-24 06:55:20 -07002850 const bool module_scope_constant_external_init =
David Neto862b7d82018-06-14 18:48:37 -04002851 (AS == AddressSpace::Constant) && GV.hasInitializer() &&
David Neto85082642018-03-24 06:55:20 -07002852 clspv::Option::ModuleConstantsInStorageBuffer();
2853
2854 if (0 != InitializerID) {
2855 if (!module_scope_constant_external_init) {
2856 // Emit the ID of the intiializer as part of the variable definition.
David Netoc6f3ab22018-04-06 18:02:31 -04002857 Ops << MkId(InitializerID);
David Neto85082642018-03-24 06:55:20 -07002858 }
2859 }
2860 const uint32_t var_id = nextID++;
2861
David Neto87846742018-04-11 17:36:22 -04002862 auto *Inst = new SPIRVInstruction(spv::OpVariable, var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002863 SPIRVInstList.push_back(Inst);
2864
2865 // If we have a builtin.
2866 if (spv::BuiltInMax != BuiltinType) {
2867 // Find Insert Point for OpDecorate.
2868 auto DecoInsertPoint =
2869 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2870 [](SPIRVInstruction *Inst) -> bool {
2871 return Inst->getOpcode() != spv::OpDecorate &&
2872 Inst->getOpcode() != spv::OpMemberDecorate &&
2873 Inst->getOpcode() != spv::OpExtInstImport;
2874 });
2875 //
2876 // Generate OpDecorate.
2877 //
2878 // DOps[0] = Target ID
2879 // DOps[1] = Decoration (Builtin)
2880 // DOps[2] = BuiltIn ID
2881 uint32_t ResultID;
2882
2883 // WorkgroupSize is different, we decorate the constant composite that has
2884 // its value, rather than the variable that we use to access the value.
2885 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2886 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04002887 // Save both the value and variable IDs for later.
2888 WorkgroupSizeValueID = InitializerID;
2889 WorkgroupSizeVarID = VMap[&GV];
David Neto22f144c2017-06-12 14:26:21 -04002890 } else {
2891 ResultID = VMap[&GV];
2892 }
2893
2894 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002895 DOps << MkId(ResultID) << MkNum(spv::DecorationBuiltIn)
2896 << MkNum(BuiltinType);
David Neto22f144c2017-06-12 14:26:21 -04002897
David Neto87846742018-04-11 17:36:22 -04002898 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, DOps);
David Neto22f144c2017-06-12 14:26:21 -04002899 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
David Neto85082642018-03-24 06:55:20 -07002900 } else if (module_scope_constant_external_init) {
2901 // This module scope constant is initialized from a storage buffer with data
2902 // provided by the host at binding 0 of the next descriptor set.
David Neto78383442018-06-15 20:31:56 -04002903 const uint32_t descriptor_set = TakeDescriptorIndex(&M);
David Neto85082642018-03-24 06:55:20 -07002904
David Neto862b7d82018-06-14 18:48:37 -04002905 // Emit the intializer to the descriptor map file.
David Neto85082642018-03-24 06:55:20 -07002906 // Use "kind,buffer" to indicate storage buffer. We might want to expand
2907 // that later to other types, like uniform buffer.
alan-bakerf5e5f692018-11-27 08:33:24 -05002908 std::string hexbytes;
2909 llvm::raw_string_ostream str(hexbytes);
2910 clspv::ConstantEmitter(DL, str).Emit(GV.getInitializer());
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002911 version0::DescriptorMapEntry::ConstantData constant_data = {ArgKind::Buffer,
2912 str.str()};
2913 descriptorMapEntries->emplace_back(std::move(constant_data), descriptor_set,
2914 0);
David Neto85082642018-03-24 06:55:20 -07002915
2916 // Find Insert Point for OpDecorate.
2917 auto DecoInsertPoint =
2918 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2919 [](SPIRVInstruction *Inst) -> bool {
2920 return Inst->getOpcode() != spv::OpDecorate &&
2921 Inst->getOpcode() != spv::OpMemberDecorate &&
2922 Inst->getOpcode() != spv::OpExtInstImport;
2923 });
2924
David Neto257c3892018-04-11 13:19:45 -04002925 // OpDecorate %var Binding <binding>
David Neto85082642018-03-24 06:55:20 -07002926 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002927 DOps << MkId(var_id) << MkNum(spv::DecorationBinding) << MkNum(0);
2928 DecoInsertPoint = SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04002929 DecoInsertPoint, new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto85082642018-03-24 06:55:20 -07002930
2931 // OpDecorate %var DescriptorSet <descriptor_set>
2932 DOps.clear();
David Neto257c3892018-04-11 13:19:45 -04002933 DOps << MkId(var_id) << MkNum(spv::DecorationDescriptorSet)
2934 << MkNum(descriptor_set);
David Netoc6f3ab22018-04-06 18:02:31 -04002935 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04002936 new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto22f144c2017-06-12 14:26:21 -04002937 }
2938}
2939
David Netoc6f3ab22018-04-06 18:02:31 -04002940void SPIRVProducerPass::GenerateWorkgroupVars() {
2941 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
Alan Baker202c8c72018-08-13 13:47:44 -04002942 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2943 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002944 LocalArgInfo &info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002945
2946 // Generate OpVariable.
2947 //
2948 // GIDOps[0] : Result Type ID
2949 // GIDOps[1] : Storage Class
2950 SPIRVOperandList Ops;
2951 Ops << MkId(info.ptr_array_type_id) << MkNum(spv::StorageClassWorkgroup);
2952
2953 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002954 new SPIRVInstruction(spv::OpVariable, info.variable_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002955 }
2956}
2957
David Neto862b7d82018-06-14 18:48:37 -04002958void SPIRVProducerPass::GenerateDescriptorMapInfo(const DataLayout &DL,
2959 Function &F) {
David Netoc5fb5242018-07-30 13:28:31 -04002960 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2961 return;
2962 }
David Neto862b7d82018-06-14 18:48:37 -04002963 // Gather the list of resources that are used by this function's arguments.
2964 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
2965
alan-bakerf5e5f692018-11-27 08:33:24 -05002966 // TODO(alan-baker): This should become unnecessary by fixing the rest of the
2967 // flow to generate pod_ubo arguments earlier.
David Neto862b7d82018-06-14 18:48:37 -04002968 auto remap_arg_kind = [](StringRef argKind) {
alan-bakerf5e5f692018-11-27 08:33:24 -05002969 std::string kind =
2970 clspv::Option::PodArgsInUniformBuffer() && argKind.equals("pod")
2971 ? "pod_ubo"
2972 : argKind;
2973 return GetArgKindFromName(kind);
David Neto862b7d82018-06-14 18:48:37 -04002974 };
2975
2976 auto *fty = F.getType()->getPointerElementType();
2977 auto *func_ty = dyn_cast<FunctionType>(fty);
2978
2979 // If we've clustereed POD arguments, then argument details are in metadata.
2980 // If an argument maps to a resource variable, then get descriptor set and
2981 // binding from the resoure variable. Other info comes from the metadata.
2982 const auto *arg_map = F.getMetadata("kernel_arg_map");
2983 if (arg_map) {
2984 for (const auto &arg : arg_map->operands()) {
2985 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
Kévin PETITa353c832018-03-20 23:21:21 +00002986 assert(arg_node->getNumOperands() == 7);
David Neto862b7d82018-06-14 18:48:37 -04002987 const auto name =
2988 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
2989 const auto old_index =
2990 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
2991 // Remapped argument index
alan-bakerb6b09dc2018-11-08 16:59:28 -05002992 const size_t new_index = static_cast<size_t>(
2993 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04002994 const auto offset =
2995 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
Kévin PETITa353c832018-03-20 23:21:21 +00002996 const auto arg_size =
2997 dyn_extract<ConstantInt>(arg_node->getOperand(4))->getZExtValue();
David Neto862b7d82018-06-14 18:48:37 -04002998 const auto argKind = remap_arg_kind(
Kévin PETITa353c832018-03-20 23:21:21 +00002999 dyn_cast<MDString>(arg_node->getOperand(5))->getString());
David Neto862b7d82018-06-14 18:48:37 -04003000 const auto spec_id =
Kévin PETITa353c832018-03-20 23:21:21 +00003001 dyn_extract<ConstantInt>(arg_node->getOperand(6))->getSExtValue();
alan-bakerf5e5f692018-11-27 08:33:24 -05003002
3003 uint32_t descriptor_set = 0;
3004 uint32_t binding = 0;
3005 version0::DescriptorMapEntry::KernelArgData kernel_data = {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003006 F.getName(), name, static_cast<uint32_t>(old_index), argKind,
alan-bakerf5e5f692018-11-27 08:33:24 -05003007 static_cast<uint32_t>(spec_id),
3008 // This will be set below for pointer-to-local args.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003009 0, static_cast<uint32_t>(offset), 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 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003020 descriptorMapEntries->emplace_back(std::move(kernel_data), descriptor_set,
3021 binding);
David Neto862b7d82018-06-14 18:48:37 -04003022 }
3023 } else {
3024 // There is no argument map.
3025 // Take descriptor info from the resource variable calls.
Kévin PETITa353c832018-03-20 23:21:21 +00003026 // Take argument name and size from the arguments list.
David Neto862b7d82018-06-14 18:48:37 -04003027
3028 SmallVector<Argument *, 4> arguments;
3029 for (auto &arg : F.args()) {
3030 arguments.push_back(&arg);
3031 }
3032
3033 unsigned arg_index = 0;
3034 for (auto *info : resource_var_at_index) {
3035 if (info) {
Kévin PETITa353c832018-03-20 23:21:21 +00003036 auto arg = arguments[arg_index];
alan-bakerb6b09dc2018-11-08 16:59:28 -05003037 unsigned arg_size = 0;
Kévin PETITa353c832018-03-20 23:21:21 +00003038 if (info->arg_kind == clspv::ArgKind::Pod) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05003039 arg_size = static_cast<uint32_t>(DL.getTypeStoreSize(arg->getType()));
Kévin PETITa353c832018-03-20 23:21:21 +00003040 }
3041
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003042 // Local pointer arguments are unused in this case. Offset is always
3043 // zero.
alan-bakerf5e5f692018-11-27 08:33:24 -05003044 version0::DescriptorMapEntry::KernelArgData kernel_data = {
3045 F.getName(), arg->getName(),
3046 arg_index, remap_arg_kind(clspv::GetArgKindName(info->arg_kind)),
3047 0, 0,
3048 0, arg_size};
3049 descriptorMapEntries->emplace_back(std::move(kernel_data),
3050 info->descriptor_set, info->binding);
David Neto862b7d82018-06-14 18:48:37 -04003051 }
3052 arg_index++;
3053 }
3054 // Generate mappings for pointer-to-local arguments.
3055 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
3056 Argument *arg = arguments[arg_index];
Alan Baker202c8c72018-08-13 13:47:44 -04003057 auto where = LocalArgSpecIds.find(arg);
3058 if (where != LocalArgSpecIds.end()) {
3059 auto &local_arg_info = LocalSpecIdInfoMap[where->second];
alan-bakerf5e5f692018-11-27 08:33:24 -05003060 // Pod arguments members are unused in this case.
3061 version0::DescriptorMapEntry::KernelArgData kernel_data = {
3062 F.getName(),
3063 arg->getName(),
3064 arg_index,
3065 ArgKind::Local,
3066 static_cast<uint32_t>(local_arg_info.spec_id),
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003067 static_cast<uint32_t>(
3068 GetTypeAllocSize(local_arg_info.elem_type, DL)),
alan-bakerf5e5f692018-11-27 08:33:24 -05003069 0,
3070 0};
3071 // Pointer-to-local arguments do not utilize descriptor set and binding.
3072 descriptorMapEntries->emplace_back(std::move(kernel_data), 0, 0);
David Neto862b7d82018-06-14 18:48:37 -04003073 }
3074 }
3075 }
3076}
3077
David Neto22f144c2017-06-12 14:26:21 -04003078void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
3079 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3080 ValueMapType &VMap = getValueMap();
3081 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04003082 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
3083 auto &GlobalConstArgSet = getGlobalConstArgSet();
3084
3085 FunctionType *FTy = F.getFunctionType();
3086
3087 //
David Neto22f144c2017-06-12 14:26:21 -04003088 // Generate OPFunction.
3089 //
3090
3091 // FOps[0] : Result Type ID
3092 // FOps[1] : Function Control
3093 // FOps[2] : Function Type ID
3094 SPIRVOperandList FOps;
3095
3096 // Find SPIRV instruction for return type.
David Neto257c3892018-04-11 13:19:45 -04003097 FOps << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04003098
3099 // Check function attributes for SPIRV Function Control.
3100 uint32_t FuncControl = spv::FunctionControlMaskNone;
3101 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
3102 FuncControl |= spv::FunctionControlInlineMask;
3103 }
3104 if (F.hasFnAttribute(Attribute::NoInline)) {
3105 FuncControl |= spv::FunctionControlDontInlineMask;
3106 }
3107 // TODO: Check llvm attribute for Function Control Pure.
3108 if (F.hasFnAttribute(Attribute::ReadOnly)) {
3109 FuncControl |= spv::FunctionControlPureMask;
3110 }
3111 // TODO: Check llvm attribute for Function Control Const.
3112 if (F.hasFnAttribute(Attribute::ReadNone)) {
3113 FuncControl |= spv::FunctionControlConstMask;
3114 }
3115
David Neto257c3892018-04-11 13:19:45 -04003116 FOps << MkNum(FuncControl);
David Neto22f144c2017-06-12 14:26:21 -04003117
3118 uint32_t FTyID;
3119 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3120 SmallVector<Type *, 4> NewFuncParamTys;
3121 FunctionType *NewFTy =
3122 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
3123 FTyID = lookupType(NewFTy);
3124 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07003125 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04003126 if (GlobalConstFuncTyMap.count(FTy)) {
3127 FTyID = lookupType(GlobalConstFuncTyMap[FTy].first);
3128 } else {
3129 FTyID = lookupType(FTy);
3130 }
3131 }
3132
David Neto257c3892018-04-11 13:19:45 -04003133 FOps << MkId(FTyID);
David Neto22f144c2017-06-12 14:26:21 -04003134
3135 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3136 EntryPoints.push_back(std::make_pair(&F, nextID));
3137 }
3138
3139 VMap[&F] = nextID;
3140
David Neto482550a2018-03-24 05:21:07 -07003141 if (clspv::Option::ShowIDs()) {
David Netob05675d2018-02-16 12:37:49 -05003142 errs() << "Function " << F.getName() << " is " << nextID << "\n";
3143 }
David Neto22f144c2017-06-12 14:26:21 -04003144 // Generate SPIRV instruction for function.
David Neto87846742018-04-11 17:36:22 -04003145 auto *FuncInst = new SPIRVInstruction(spv::OpFunction, nextID++, FOps);
David Neto22f144c2017-06-12 14:26:21 -04003146 SPIRVInstList.push_back(FuncInst);
3147
3148 //
3149 // Generate OpFunctionParameter for Normal function.
3150 //
3151
3152 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
alan-bakere9308012019-03-15 10:25:13 -04003153
3154 // Find Insert Point for OpDecorate.
3155 auto DecoInsertPoint =
3156 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
3157 [](SPIRVInstruction *Inst) -> bool {
3158 return Inst->getOpcode() != spv::OpDecorate &&
3159 Inst->getOpcode() != spv::OpMemberDecorate &&
3160 Inst->getOpcode() != spv::OpExtInstImport;
3161 });
3162
David Neto22f144c2017-06-12 14:26:21 -04003163 // Iterate Argument for name instead of param type from function type.
3164 unsigned ArgIdx = 0;
3165 for (Argument &Arg : F.args()) {
alan-bakere9308012019-03-15 10:25:13 -04003166 uint32_t param_id = nextID++;
3167 VMap[&Arg] = param_id;
3168
3169 if (CalledWithCoherentResource(Arg)) {
3170 // If the arg is passed a coherent resource ever, then decorate this
3171 // parameter with Coherent too.
3172 SPIRVOperandList decoration_ops;
3173 decoration_ops << MkId(param_id) << MkNum(spv::DecorationCoherent);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003174 SPIRVInstList.insert(
3175 DecoInsertPoint,
3176 new SPIRVInstruction(spv::OpDecorate, decoration_ops));
alan-bakere9308012019-03-15 10:25:13 -04003177 }
David Neto22f144c2017-06-12 14:26:21 -04003178
3179 // ParamOps[0] : Result Type ID
3180 SPIRVOperandList ParamOps;
3181
3182 // Find SPIRV instruction for parameter type.
3183 uint32_t ParamTyID = lookupType(Arg.getType());
3184 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
3185 if (GlobalConstFuncTyMap.count(FTy)) {
3186 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
3187 Type *EleTy = PTy->getPointerElementType();
3188 Type *ArgTy =
3189 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
3190 ParamTyID = lookupType(ArgTy);
3191 GlobalConstArgSet.insert(&Arg);
3192 }
3193 }
3194 }
David Neto257c3892018-04-11 13:19:45 -04003195 ParamOps << MkId(ParamTyID);
David Neto22f144c2017-06-12 14:26:21 -04003196
3197 // Generate SPIRV instruction for parameter.
David Neto87846742018-04-11 17:36:22 -04003198 auto *ParamInst =
alan-bakere9308012019-03-15 10:25:13 -04003199 new SPIRVInstruction(spv::OpFunctionParameter, param_id, ParamOps);
David Neto22f144c2017-06-12 14:26:21 -04003200 SPIRVInstList.push_back(ParamInst);
3201
3202 ArgIdx++;
3203 }
3204 }
3205}
3206
alan-bakerb6b09dc2018-11-08 16:59:28 -05003207void SPIRVProducerPass::GenerateModuleInfo(Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04003208 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3209 EntryPointVecType &EntryPoints = getEntryPointVec();
3210 ValueMapType &VMap = getValueMap();
3211 ValueList &EntryPointInterfaces = getEntryPointInterfacesVec();
3212 uint32_t &ExtInstImportID = getOpExtInstImportID();
3213 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
3214
3215 // Set up insert point.
3216 auto InsertPoint = SPIRVInstList.begin();
3217
3218 //
3219 // Generate OpCapability
3220 //
3221 // TODO: Which llvm information is mapped to SPIRV Capapbility?
3222
3223 // Ops[0] = Capability
3224 SPIRVOperandList Ops;
3225
David Neto87846742018-04-11 17:36:22 -04003226 auto *CapInst =
3227 new SPIRVInstruction(spv::OpCapability, {MkNum(spv::CapabilityShader)});
David Neto22f144c2017-06-12 14:26:21 -04003228 SPIRVInstList.insert(InsertPoint, CapInst);
3229
3230 for (Type *Ty : getTypeList()) {
alan-bakerb39c8262019-03-08 14:03:37 -05003231 if (clspv::Option::Int8Support() && Ty->isIntegerTy(8)) {
3232 // Generate OpCapability for i8 type.
3233 SPIRVInstList.insert(InsertPoint,
3234 new SPIRVInstruction(spv::OpCapability,
3235 {MkNum(spv::CapabilityInt8)}));
3236 } else if (Ty->isIntegerTy(16)) {
David Neto22f144c2017-06-12 14:26:21 -04003237 // Generate OpCapability for i16 type.
David Neto87846742018-04-11 17:36:22 -04003238 SPIRVInstList.insert(InsertPoint,
3239 new SPIRVInstruction(spv::OpCapability,
3240 {MkNum(spv::CapabilityInt16)}));
David Neto22f144c2017-06-12 14:26:21 -04003241 } else if (Ty->isIntegerTy(64)) {
3242 // Generate OpCapability for i64 type.
David Neto87846742018-04-11 17:36:22 -04003243 SPIRVInstList.insert(InsertPoint,
3244 new SPIRVInstruction(spv::OpCapability,
3245 {MkNum(spv::CapabilityInt64)}));
David Neto22f144c2017-06-12 14:26:21 -04003246 } else if (Ty->isHalfTy()) {
3247 // Generate OpCapability for half type.
3248 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003249 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3250 {MkNum(spv::CapabilityFloat16)}));
David Neto22f144c2017-06-12 14:26:21 -04003251 } else if (Ty->isDoubleTy()) {
3252 // Generate OpCapability for double type.
3253 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003254 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3255 {MkNum(spv::CapabilityFloat64)}));
David Neto22f144c2017-06-12 14:26:21 -04003256 } else if (auto *STy = dyn_cast<StructType>(Ty)) {
3257 if (STy->isOpaque()) {
David Neto565571c2017-08-21 12:00:05 -04003258 if (STy->getName().equals("opencl.image2d_wo_t") ||
3259 STy->getName().equals("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04003260 // Generate OpCapability for write only image type.
3261 SPIRVInstList.insert(
3262 InsertPoint,
3263 new SPIRVInstruction(
David Neto87846742018-04-11 17:36:22 -04003264 spv::OpCapability,
3265 {MkNum(spv::CapabilityStorageImageWriteWithoutFormat)}));
David Neto22f144c2017-06-12 14:26:21 -04003266 }
3267 }
3268 }
3269 }
3270
David Neto5c22a252018-03-15 16:07:41 -04003271 { // OpCapability ImageQuery
3272 bool hasImageQuery = false;
3273 for (const char *imageQuery : {
3274 "_Z15get_image_width14ocl_image2d_ro",
3275 "_Z15get_image_width14ocl_image2d_wo",
3276 "_Z16get_image_height14ocl_image2d_ro",
3277 "_Z16get_image_height14ocl_image2d_wo",
3278 }) {
3279 if (module.getFunction(imageQuery)) {
3280 hasImageQuery = true;
3281 break;
3282 }
3283 }
3284 if (hasImageQuery) {
David Neto87846742018-04-11 17:36:22 -04003285 auto *ImageQueryCapInst = new SPIRVInstruction(
3286 spv::OpCapability, {MkNum(spv::CapabilityImageQuery)});
David Neto5c22a252018-03-15 16:07:41 -04003287 SPIRVInstList.insert(InsertPoint, ImageQueryCapInst);
3288 }
3289 }
3290
David Neto22f144c2017-06-12 14:26:21 -04003291 if (hasVariablePointers()) {
3292 //
David Neto22f144c2017-06-12 14:26:21 -04003293 // Generate OpCapability.
3294 //
3295 // Ops[0] = Capability
3296 //
3297 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003298 Ops << MkNum(spv::CapabilityVariablePointers);
David Neto22f144c2017-06-12 14:26:21 -04003299
David Neto87846742018-04-11 17:36:22 -04003300 SPIRVInstList.insert(InsertPoint,
3301 new SPIRVInstruction(spv::OpCapability, Ops));
alan-baker5b86ed72019-02-15 08:26:50 -05003302 } else if (hasVariablePointersStorageBuffer()) {
3303 //
3304 // Generate OpCapability.
3305 //
3306 // Ops[0] = Capability
3307 //
3308 Ops.clear();
3309 Ops << MkNum(spv::CapabilityVariablePointersStorageBuffer);
David Neto22f144c2017-06-12 14:26:21 -04003310
alan-baker5b86ed72019-02-15 08:26:50 -05003311 SPIRVInstList.insert(InsertPoint,
3312 new SPIRVInstruction(spv::OpCapability, Ops));
3313 }
3314
3315 // Always add the storage buffer extension
3316 {
David Neto22f144c2017-06-12 14:26:21 -04003317 //
3318 // Generate OpExtension.
3319 //
3320 // Ops[0] = Name (Literal String)
3321 //
alan-baker5b86ed72019-02-15 08:26:50 -05003322 auto *ExtensionInst = new SPIRVInstruction(
3323 spv::OpExtension, {MkString("SPV_KHR_storage_buffer_storage_class")});
3324 SPIRVInstList.insert(InsertPoint, ExtensionInst);
3325 }
David Neto22f144c2017-06-12 14:26:21 -04003326
alan-baker5b86ed72019-02-15 08:26:50 -05003327 if (hasVariablePointers() || hasVariablePointersStorageBuffer()) {
3328 //
3329 // Generate OpExtension.
3330 //
3331 // Ops[0] = Name (Literal String)
3332 //
3333 auto *ExtensionInst = new SPIRVInstruction(
3334 spv::OpExtension, {MkString("SPV_KHR_variable_pointers")});
3335 SPIRVInstList.insert(InsertPoint, ExtensionInst);
David Neto22f144c2017-06-12 14:26:21 -04003336 }
3337
3338 if (ExtInstImportID) {
3339 ++InsertPoint;
3340 }
3341
3342 //
3343 // Generate OpMemoryModel
3344 //
3345 // Memory model for Vulkan will always be GLSL450.
3346
3347 // Ops[0] = Addressing Model
3348 // Ops[1] = Memory Model
3349 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003350 Ops << MkNum(spv::AddressingModelLogical) << MkNum(spv::MemoryModelGLSL450);
David Neto22f144c2017-06-12 14:26:21 -04003351
David Neto87846742018-04-11 17:36:22 -04003352 auto *MemModelInst = new SPIRVInstruction(spv::OpMemoryModel, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003353 SPIRVInstList.insert(InsertPoint, MemModelInst);
3354
3355 //
3356 // Generate OpEntryPoint
3357 //
3358 for (auto EntryPoint : EntryPoints) {
3359 // Ops[0] = Execution Model
3360 // Ops[1] = EntryPoint ID
3361 // Ops[2] = Name (Literal String)
3362 // ...
3363 //
3364 // TODO: Do we need to consider Interface ID for forward references???
3365 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003366 const StringRef &name = EntryPoint.first->getName();
David Neto257c3892018-04-11 13:19:45 -04003367 Ops << MkNum(spv::ExecutionModelGLCompute) << MkId(EntryPoint.second)
3368 << MkString(name);
David Neto22f144c2017-06-12 14:26:21 -04003369
David Neto22f144c2017-06-12 14:26:21 -04003370 for (Value *Interface : EntryPointInterfaces) {
David Neto257c3892018-04-11 13:19:45 -04003371 Ops << MkId(VMap[Interface]);
David Neto22f144c2017-06-12 14:26:21 -04003372 }
3373
David Neto87846742018-04-11 17:36:22 -04003374 auto *EntryPointInst = new SPIRVInstruction(spv::OpEntryPoint, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003375 SPIRVInstList.insert(InsertPoint, EntryPointInst);
3376 }
3377
3378 for (auto EntryPoint : EntryPoints) {
3379 if (const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
3380 ->getMetadata("reqd_work_group_size")) {
3381
3382 if (!BuiltinDimVec.empty()) {
3383 llvm_unreachable(
3384 "Kernels should have consistent work group size definition");
3385 }
3386
3387 //
3388 // Generate OpExecutionMode
3389 //
3390
3391 // Ops[0] = Entry Point ID
3392 // Ops[1] = Execution Mode
3393 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
3394 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003395 Ops << MkId(EntryPoint.second) << MkNum(spv::ExecutionModeLocalSize);
David Neto22f144c2017-06-12 14:26:21 -04003396
3397 uint32_t XDim = static_cast<uint32_t>(
3398 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3399 uint32_t YDim = static_cast<uint32_t>(
3400 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3401 uint32_t ZDim = static_cast<uint32_t>(
3402 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3403
David Neto257c3892018-04-11 13:19:45 -04003404 Ops << MkNum(XDim) << MkNum(YDim) << MkNum(ZDim);
David Neto22f144c2017-06-12 14:26:21 -04003405
David Neto87846742018-04-11 17:36:22 -04003406 auto *ExecModeInst = new SPIRVInstruction(spv::OpExecutionMode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003407 SPIRVInstList.insert(InsertPoint, ExecModeInst);
3408 }
3409 }
3410
3411 //
3412 // Generate OpSource.
3413 //
3414 // Ops[0] = SourceLanguage ID
3415 // Ops[1] = Version (LiteralNum)
3416 //
3417 Ops.clear();
Kévin Petit0fc88042019-04-09 23:25:02 +01003418 if (clspv::Option::CPlusPlus()) {
3419 Ops << MkNum(spv::SourceLanguageOpenCL_CPP) << MkNum(100);
3420 } else {
3421 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(120);
3422 }
David Neto22f144c2017-06-12 14:26:21 -04003423
David Neto87846742018-04-11 17:36:22 -04003424 auto *OpenSourceInst = new SPIRVInstruction(spv::OpSource, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003425 SPIRVInstList.insert(InsertPoint, OpenSourceInst);
3426
3427 if (!BuiltinDimVec.empty()) {
3428 //
3429 // Generate OpDecorates for x/y/z dimension.
3430 //
3431 // Ops[0] = Target ID
3432 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04003433 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04003434
3435 // X Dimension
3436 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003437 Ops << MkId(BuiltinDimVec[0]) << MkNum(spv::DecorationSpecId) << MkNum(0);
David Neto87846742018-04-11 17:36:22 -04003438 SPIRVInstList.insert(InsertPoint,
3439 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003440
3441 // Y Dimension
3442 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003443 Ops << MkId(BuiltinDimVec[1]) << MkNum(spv::DecorationSpecId) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04003444 SPIRVInstList.insert(InsertPoint,
3445 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003446
3447 // Z Dimension
3448 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003449 Ops << MkId(BuiltinDimVec[2]) << MkNum(spv::DecorationSpecId) << MkNum(2);
David Neto87846742018-04-11 17:36:22 -04003450 SPIRVInstList.insert(InsertPoint,
3451 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003452 }
3453}
3454
David Netob6e2e062018-04-25 10:32:06 -04003455void SPIRVProducerPass::GenerateEntryPointInitialStores() {
3456 // Work around a driver bug. Initializers on Private variables might not
3457 // work. So the start of the kernel should store the initializer value to the
3458 // variables. Yes, *every* entry point pays this cost if *any* entry point
3459 // uses this builtin. At this point I judge this to be an acceptable tradeoff
3460 // of complexity vs. runtime, for a broken driver.
alan-bakerb6b09dc2018-11-08 16:59:28 -05003461 // TODO(dneto): Remove this at some point once fixed drivers are widely
3462 // available.
David Netob6e2e062018-04-25 10:32:06 -04003463 if (WorkgroupSizeVarID) {
3464 assert(WorkgroupSizeValueID);
3465
3466 SPIRVOperandList Ops;
3467 Ops << MkId(WorkgroupSizeVarID) << MkId(WorkgroupSizeValueID);
3468
3469 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
3470 getSPIRVInstList().push_back(Inst);
3471 }
3472}
3473
David Neto22f144c2017-06-12 14:26:21 -04003474void SPIRVProducerPass::GenerateFuncBody(Function &F) {
3475 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3476 ValueMapType &VMap = getValueMap();
3477
David Netob6e2e062018-04-25 10:32:06 -04003478 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04003479
3480 for (BasicBlock &BB : F) {
3481 // Register BasicBlock to ValueMap.
3482 VMap[&BB] = nextID;
3483
3484 //
3485 // Generate OpLabel for Basic Block.
3486 //
3487 SPIRVOperandList Ops;
David Neto87846742018-04-11 17:36:22 -04003488 auto *Inst = new SPIRVInstruction(spv::OpLabel, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003489 SPIRVInstList.push_back(Inst);
3490
David Neto6dcd4712017-06-23 11:06:47 -04003491 // OpVariable instructions must come first.
3492 for (Instruction &I : BB) {
alan-baker5b86ed72019-02-15 08:26:50 -05003493 if (auto *alloca = dyn_cast<AllocaInst>(&I)) {
3494 // Allocating a pointer requires variable pointers.
3495 if (alloca->getAllocatedType()->isPointerTy()) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003496 setVariablePointersCapabilities(
3497 alloca->getAllocatedType()->getPointerAddressSpace());
alan-baker5b86ed72019-02-15 08:26:50 -05003498 }
David Neto6dcd4712017-06-23 11:06:47 -04003499 GenerateInstruction(I);
3500 }
3501 }
3502
David Neto22f144c2017-06-12 14:26:21 -04003503 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04003504 if (clspv::Option::HackInitializers()) {
3505 GenerateEntryPointInitialStores();
3506 }
David Neto22f144c2017-06-12 14:26:21 -04003507 }
3508
3509 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003510 if (!isa<AllocaInst>(I)) {
3511 GenerateInstruction(I);
3512 }
David Neto22f144c2017-06-12 14:26:21 -04003513 }
3514 }
3515}
3516
3517spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3518 const std::map<CmpInst::Predicate, spv::Op> Map = {
3519 {CmpInst::ICMP_EQ, spv::OpIEqual},
3520 {CmpInst::ICMP_NE, spv::OpINotEqual},
3521 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3522 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3523 {CmpInst::ICMP_ULT, spv::OpULessThan},
3524 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3525 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3526 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3527 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3528 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3529 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3530 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3531 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3532 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3533 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3534 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3535 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3536 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3537 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3538 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3539 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3540 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3541
3542 assert(0 != Map.count(I->getPredicate()));
3543
3544 return Map.at(I->getPredicate());
3545}
3546
3547spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3548 const std::map<unsigned, spv::Op> Map{
3549 {Instruction::Trunc, spv::OpUConvert},
3550 {Instruction::ZExt, spv::OpUConvert},
3551 {Instruction::SExt, spv::OpSConvert},
3552 {Instruction::FPToUI, spv::OpConvertFToU},
3553 {Instruction::FPToSI, spv::OpConvertFToS},
3554 {Instruction::UIToFP, spv::OpConvertUToF},
3555 {Instruction::SIToFP, spv::OpConvertSToF},
3556 {Instruction::FPTrunc, spv::OpFConvert},
3557 {Instruction::FPExt, spv::OpFConvert},
3558 {Instruction::BitCast, spv::OpBitcast}};
3559
3560 assert(0 != Map.count(I.getOpcode()));
3561
3562 return Map.at(I.getOpcode());
3563}
3564
3565spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
Kévin Petit24272b62018-10-18 19:16:12 +00003566 if (I.getType()->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003567 switch (I.getOpcode()) {
3568 default:
3569 break;
3570 case Instruction::Or:
3571 return spv::OpLogicalOr;
3572 case Instruction::And:
3573 return spv::OpLogicalAnd;
3574 case Instruction::Xor:
3575 return spv::OpLogicalNotEqual;
3576 }
3577 }
3578
alan-bakerb6b09dc2018-11-08 16:59:28 -05003579 const std::map<unsigned, spv::Op> Map{
David Neto22f144c2017-06-12 14:26:21 -04003580 {Instruction::Add, spv::OpIAdd},
3581 {Instruction::FAdd, spv::OpFAdd},
3582 {Instruction::Sub, spv::OpISub},
3583 {Instruction::FSub, spv::OpFSub},
3584 {Instruction::Mul, spv::OpIMul},
3585 {Instruction::FMul, spv::OpFMul},
3586 {Instruction::UDiv, spv::OpUDiv},
3587 {Instruction::SDiv, spv::OpSDiv},
3588 {Instruction::FDiv, spv::OpFDiv},
3589 {Instruction::URem, spv::OpUMod},
3590 {Instruction::SRem, spv::OpSRem},
3591 {Instruction::FRem, spv::OpFRem},
3592 {Instruction::Or, spv::OpBitwiseOr},
3593 {Instruction::Xor, spv::OpBitwiseXor},
3594 {Instruction::And, spv::OpBitwiseAnd},
3595 {Instruction::Shl, spv::OpShiftLeftLogical},
3596 {Instruction::LShr, spv::OpShiftRightLogical},
3597 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3598
3599 assert(0 != Map.count(I.getOpcode()));
3600
3601 return Map.at(I.getOpcode());
3602}
3603
3604void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
3605 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3606 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04003607 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
3608 LLVMContext &Context = I.getParent()->getParent()->getParent()->getContext();
3609
3610 // Register Instruction to ValueMap.
3611 if (0 == VMap[&I]) {
3612 VMap[&I] = nextID;
3613 }
3614
3615 switch (I.getOpcode()) {
3616 default: {
3617 if (Instruction::isCast(I.getOpcode())) {
3618 //
3619 // Generate SPIRV instructions for cast operators.
3620 //
3621
David Netod2de94a2017-08-28 17:27:47 -04003622 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003623 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003624 auto toI8 = Ty == Type::getInt8Ty(Context);
3625 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003626 // Handle zext, sext and uitofp with i1 type specially.
3627 if ((I.getOpcode() == Instruction::ZExt ||
3628 I.getOpcode() == Instruction::SExt ||
3629 I.getOpcode() == Instruction::UIToFP) &&
alan-bakerb6b09dc2018-11-08 16:59:28 -05003630 OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003631 //
3632 // Generate OpSelect.
3633 //
3634
3635 // Ops[0] = Result Type ID
3636 // Ops[1] = Condition ID
3637 // Ops[2] = True Constant ID
3638 // Ops[3] = False Constant ID
3639 SPIRVOperandList Ops;
3640
David Neto257c3892018-04-11 13:19:45 -04003641 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003642
David Neto22f144c2017-06-12 14:26:21 -04003643 uint32_t CondID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003644 Ops << MkId(CondID);
David Neto22f144c2017-06-12 14:26:21 -04003645
3646 uint32_t TrueID = 0;
3647 if (I.getOpcode() == Instruction::ZExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00003648 TrueID = VMap[ConstantInt::get(I.getType(), 1)];
David Neto22f144c2017-06-12 14:26:21 -04003649 } else if (I.getOpcode() == Instruction::SExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00003650 TrueID = VMap[ConstantInt::getSigned(I.getType(), -1)];
David Neto22f144c2017-06-12 14:26:21 -04003651 } else {
3652 TrueID = VMap[ConstantFP::get(Context, APFloat(1.0f))];
3653 }
David Neto257c3892018-04-11 13:19:45 -04003654 Ops << MkId(TrueID);
David Neto22f144c2017-06-12 14:26:21 -04003655
3656 uint32_t FalseID = 0;
3657 if (I.getOpcode() == Instruction::ZExt) {
3658 FalseID = VMap[Constant::getNullValue(I.getType())];
3659 } else if (I.getOpcode() == Instruction::SExt) {
3660 FalseID = VMap[Constant::getNullValue(I.getType())];
3661 } else {
3662 FalseID = VMap[ConstantFP::get(Context, APFloat(0.0f))];
3663 }
David Neto257c3892018-04-11 13:19:45 -04003664 Ops << MkId(FalseID);
David Neto22f144c2017-06-12 14:26:21 -04003665
David Neto87846742018-04-11 17:36:22 -04003666 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003667 SPIRVInstList.push_back(Inst);
alan-bakerb39c8262019-03-08 14:03:37 -05003668 } else if (!clspv::Option::Int8Support() &&
3669 I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
David Netod2de94a2017-08-28 17:27:47 -04003670 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3671 // 8 bits.
3672 // Before:
3673 // %result = trunc i32 %a to i8
3674 // After
3675 // %result = OpBitwiseAnd %uint %a %uint_255
3676
3677 SPIRVOperandList Ops;
3678
David Neto257c3892018-04-11 13:19:45 -04003679 Ops << MkId(lookupType(OpTy)) << MkId(VMap[I.getOperand(0)]);
David Netod2de94a2017-08-28 17:27:47 -04003680
3681 Type *UintTy = Type::getInt32Ty(Context);
3682 uint32_t MaskID = VMap[ConstantInt::get(UintTy, 255)];
David Neto257c3892018-04-11 13:19:45 -04003683 Ops << MkId(MaskID);
David Netod2de94a2017-08-28 17:27:47 -04003684
David Neto87846742018-04-11 17:36:22 -04003685 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Netod2de94a2017-08-28 17:27:47 -04003686 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003687 } else {
3688 // Ops[0] = Result Type ID
3689 // Ops[1] = Source Value ID
3690 SPIRVOperandList Ops;
3691
David Neto257c3892018-04-11 13:19:45 -04003692 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003693
David Neto87846742018-04-11 17:36:22 -04003694 auto *Inst = new SPIRVInstruction(GetSPIRVCastOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003695 SPIRVInstList.push_back(Inst);
3696 }
3697 } else if (isa<BinaryOperator>(I)) {
3698 //
3699 // Generate SPIRV instructions for binary operators.
3700 //
3701
3702 // Handle xor with i1 type specially.
3703 if (I.getOpcode() == Instruction::Xor &&
3704 I.getType() == Type::getInt1Ty(Context) &&
Kévin Petit24272b62018-10-18 19:16:12 +00003705 ((isa<ConstantInt>(I.getOperand(0)) &&
3706 !cast<ConstantInt>(I.getOperand(0))->isZero()) ||
3707 (isa<ConstantInt>(I.getOperand(1)) &&
3708 !cast<ConstantInt>(I.getOperand(1))->isZero()))) {
David Neto22f144c2017-06-12 14:26:21 -04003709 //
3710 // Generate OpLogicalNot.
3711 //
3712 // Ops[0] = Result Type ID
3713 // Ops[1] = Operand
3714 SPIRVOperandList Ops;
3715
David Neto257c3892018-04-11 13:19:45 -04003716 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003717
3718 Value *CondV = I.getOperand(0);
3719 if (isa<Constant>(I.getOperand(0))) {
3720 CondV = I.getOperand(1);
3721 }
David Neto257c3892018-04-11 13:19:45 -04003722 Ops << MkId(VMap[CondV]);
David Neto22f144c2017-06-12 14:26:21 -04003723
David Neto87846742018-04-11 17:36:22 -04003724 auto *Inst = new SPIRVInstruction(spv::OpLogicalNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003725 SPIRVInstList.push_back(Inst);
3726 } else {
3727 // Ops[0] = Result Type ID
3728 // Ops[1] = Operand 0
3729 // Ops[2] = Operand 1
3730 SPIRVOperandList Ops;
3731
David Neto257c3892018-04-11 13:19:45 -04003732 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
3733 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003734
David Neto87846742018-04-11 17:36:22 -04003735 auto *Inst =
3736 new SPIRVInstruction(GetSPIRVBinaryOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003737 SPIRVInstList.push_back(Inst);
3738 }
3739 } else {
3740 I.print(errs());
3741 llvm_unreachable("Unsupported instruction???");
3742 }
3743 break;
3744 }
3745 case Instruction::GetElementPtr: {
3746 auto &GlobalConstArgSet = getGlobalConstArgSet();
3747
3748 //
3749 // Generate OpAccessChain.
3750 //
3751 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
3752
3753 //
3754 // Generate OpAccessChain.
3755 //
3756
3757 // Ops[0] = Result Type ID
3758 // Ops[1] = Base ID
3759 // Ops[2] ... Ops[n] = Indexes ID
3760 SPIRVOperandList Ops;
3761
alan-bakerb6b09dc2018-11-08 16:59:28 -05003762 PointerType *ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04003763 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
3764 GlobalConstArgSet.count(GEP->getPointerOperand())) {
3765 // Use pointer type with private address space for global constant.
3766 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04003767 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04003768 }
David Neto257c3892018-04-11 13:19:45 -04003769
3770 Ops << MkId(lookupType(ResultType));
David Neto22f144c2017-06-12 14:26:21 -04003771
David Neto862b7d82018-06-14 18:48:37 -04003772 // Generate the base pointer.
3773 Ops << MkId(VMap[GEP->getPointerOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04003774
David Neto862b7d82018-06-14 18:48:37 -04003775 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04003776
3777 //
3778 // Follows below rules for gep.
3779 //
David Neto862b7d82018-06-14 18:48:37 -04003780 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
3781 // first index.
David Neto22f144c2017-06-12 14:26:21 -04003782 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
3783 // first index.
3784 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
3785 // use gep's first index.
3786 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
3787 // gep's first index.
3788 //
3789 spv::Op Opcode = spv::OpAccessChain;
3790 unsigned offset = 0;
3791 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04003792 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04003793 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04003794 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04003795 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04003796 }
David Neto862b7d82018-06-14 18:48:37 -04003797 } else {
David Neto22f144c2017-06-12 14:26:21 -04003798 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04003799 }
3800
3801 if (Opcode == spv::OpPtrAccessChain) {
David Neto1a1a0582017-07-07 12:01:44 -04003802 // Do we need to generate ArrayStride? Check against the GEP result type
3803 // rather than the pointer type of the base because when indexing into
3804 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
3805 // for something else in the SPIR-V.
3806 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
alan-baker5b86ed72019-02-15 08:26:50 -05003807 auto address_space = ResultType->getAddressSpace();
3808 setVariablePointersCapabilities(address_space);
3809 switch (GetStorageClass(address_space)) {
Alan Bakerfcda9482018-10-02 17:09:59 -04003810 case spv::StorageClassStorageBuffer:
3811 case spv::StorageClassUniform:
David Neto1a1a0582017-07-07 12:01:44 -04003812 // Save the need to generate an ArrayStride decoration. But defer
3813 // generation until later, so we only make one decoration.
David Neto85082642018-03-24 06:55:20 -07003814 getTypesNeedingArrayStride().insert(ResultType);
Alan Bakerfcda9482018-10-02 17:09:59 -04003815 break;
3816 default:
3817 break;
David Neto1a1a0582017-07-07 12:01:44 -04003818 }
David Neto22f144c2017-06-12 14:26:21 -04003819 }
3820
3821 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
David Neto257c3892018-04-11 13:19:45 -04003822 Ops << MkId(VMap[*II]);
David Neto22f144c2017-06-12 14:26:21 -04003823 }
3824
David Neto87846742018-04-11 17:36:22 -04003825 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003826 SPIRVInstList.push_back(Inst);
3827 break;
3828 }
3829 case Instruction::ExtractValue: {
3830 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3831 // Ops[0] = Result Type ID
3832 // Ops[1] = Composite ID
3833 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3834 SPIRVOperandList Ops;
3835
David Neto257c3892018-04-11 13:19:45 -04003836 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003837
3838 uint32_t CompositeID = VMap[EVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003839 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003840
3841 for (auto &Index : EVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003842 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003843 }
3844
David Neto87846742018-04-11 17:36:22 -04003845 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003846 SPIRVInstList.push_back(Inst);
3847 break;
3848 }
3849 case Instruction::InsertValue: {
3850 InsertValueInst *IVI = cast<InsertValueInst>(&I);
3851 // Ops[0] = Result Type ID
3852 // Ops[1] = Object ID
3853 // Ops[2] = Composite ID
3854 // Ops[3] ... Ops[n] = Indexes (Literal Number)
3855 SPIRVOperandList Ops;
3856
3857 uint32_t ResTyID = lookupType(I.getType());
David Neto257c3892018-04-11 13:19:45 -04003858 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04003859
3860 uint32_t ObjectID = VMap[IVI->getInsertedValueOperand()];
David Neto257c3892018-04-11 13:19:45 -04003861 Ops << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04003862
3863 uint32_t CompositeID = VMap[IVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003864 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003865
3866 for (auto &Index : IVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003867 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003868 }
3869
David Neto87846742018-04-11 17:36:22 -04003870 auto *Inst = new SPIRVInstruction(spv::OpCompositeInsert, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003871 SPIRVInstList.push_back(Inst);
3872 break;
3873 }
3874 case Instruction::Select: {
3875 //
3876 // Generate OpSelect.
3877 //
3878
3879 // Ops[0] = Result Type ID
3880 // Ops[1] = Condition ID
3881 // Ops[2] = True Constant ID
3882 // Ops[3] = False Constant ID
3883 SPIRVOperandList Ops;
3884
3885 // Find SPIRV instruction for parameter type.
3886 auto Ty = I.getType();
3887 if (Ty->isPointerTy()) {
3888 auto PointeeTy = Ty->getPointerElementType();
3889 if (PointeeTy->isStructTy() &&
3890 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
3891 Ty = PointeeTy;
alan-baker5b86ed72019-02-15 08:26:50 -05003892 } else {
3893 // Selecting between pointers requires variable pointers.
3894 setVariablePointersCapabilities(Ty->getPointerAddressSpace());
3895 if (!hasVariablePointers() && !selectFromSameObject(&I)) {
3896 setVariablePointers(true);
3897 }
David Neto22f144c2017-06-12 14:26:21 -04003898 }
3899 }
3900
David Neto257c3892018-04-11 13:19:45 -04003901 Ops << MkId(lookupType(Ty)) << MkId(VMap[I.getOperand(0)])
3902 << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003903
David Neto87846742018-04-11 17:36:22 -04003904 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003905 SPIRVInstList.push_back(Inst);
3906 break;
3907 }
3908 case Instruction::ExtractElement: {
3909 // Handle <4 x i8> type manually.
3910 Type *CompositeTy = I.getOperand(0)->getType();
3911 if (is4xi8vec(CompositeTy)) {
3912 //
3913 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
3914 // <4 x i8>.
3915 //
3916
3917 //
3918 // Generate OpShiftRightLogical
3919 //
3920 // Ops[0] = Result Type ID
3921 // Ops[1] = Operand 0
3922 // Ops[2] = Operand 1
3923 //
3924 SPIRVOperandList Ops;
3925
David Neto257c3892018-04-11 13:19:45 -04003926 Ops << MkId(lookupType(CompositeTy));
David Neto22f144c2017-06-12 14:26:21 -04003927
3928 uint32_t Op0ID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003929 Ops << MkId(Op0ID);
David Neto22f144c2017-06-12 14:26:21 -04003930
3931 uint32_t Op1ID = 0;
3932 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
3933 // Handle constant index.
3934 uint64_t Idx = CI->getZExtValue();
3935 Value *ShiftAmount =
3936 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3937 Op1ID = VMap[ShiftAmount];
3938 } else {
3939 // Handle variable index.
3940 SPIRVOperandList TmpOps;
3941
David Neto257c3892018-04-11 13:19:45 -04003942 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3943 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003944
3945 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003946 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003947
3948 Op1ID = nextID;
3949
David Neto87846742018-04-11 17:36:22 -04003950 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003951 SPIRVInstList.push_back(TmpInst);
3952 }
David Neto257c3892018-04-11 13:19:45 -04003953 Ops << MkId(Op1ID);
David Neto22f144c2017-06-12 14:26:21 -04003954
3955 uint32_t ShiftID = nextID;
3956
David Neto87846742018-04-11 17:36:22 -04003957 auto *Inst =
3958 new SPIRVInstruction(spv::OpShiftRightLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003959 SPIRVInstList.push_back(Inst);
3960
3961 //
3962 // Generate OpBitwiseAnd
3963 //
3964 // Ops[0] = Result Type ID
3965 // Ops[1] = Operand 0
3966 // Ops[2] = Operand 1
3967 //
3968 Ops.clear();
3969
David Neto257c3892018-04-11 13:19:45 -04003970 Ops << MkId(lookupType(CompositeTy)) << MkId(ShiftID);
David Neto22f144c2017-06-12 14:26:21 -04003971
3972 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
David Neto257c3892018-04-11 13:19:45 -04003973 Ops << MkId(VMap[CstFF]);
David Neto22f144c2017-06-12 14:26:21 -04003974
David Neto9b2d6252017-09-06 15:47:37 -04003975 // Reset mapping for this value to the result of the bitwise and.
3976 VMap[&I] = nextID;
3977
David Neto87846742018-04-11 17:36:22 -04003978 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003979 SPIRVInstList.push_back(Inst);
3980 break;
3981 }
3982
3983 // Ops[0] = Result Type ID
3984 // Ops[1] = Composite ID
3985 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3986 SPIRVOperandList Ops;
3987
David Neto257c3892018-04-11 13:19:45 -04003988 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003989
3990 spv::Op Opcode = spv::OpCompositeExtract;
3991 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
David Neto257c3892018-04-11 13:19:45 -04003992 Ops << MkNum(static_cast<uint32_t>(CI->getZExtValue()));
David Neto22f144c2017-06-12 14:26:21 -04003993 } else {
David Neto257c3892018-04-11 13:19:45 -04003994 Ops << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003995 Opcode = spv::OpVectorExtractDynamic;
3996 }
3997
David Neto87846742018-04-11 17:36:22 -04003998 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003999 SPIRVInstList.push_back(Inst);
4000 break;
4001 }
4002 case Instruction::InsertElement: {
4003 // Handle <4 x i8> type manually.
4004 Type *CompositeTy = I.getOperand(0)->getType();
4005 if (is4xi8vec(CompositeTy)) {
4006 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
4007 uint32_t CstFFID = VMap[CstFF];
4008
4009 uint32_t ShiftAmountID = 0;
4010 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
4011 // Handle constant index.
4012 uint64_t Idx = CI->getZExtValue();
4013 Value *ShiftAmount =
4014 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
4015 ShiftAmountID = VMap[ShiftAmount];
4016 } else {
4017 // Handle variable index.
4018 SPIRVOperandList TmpOps;
4019
David Neto257c3892018-04-11 13:19:45 -04004020 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
4021 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004022
4023 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04004024 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04004025
4026 ShiftAmountID = nextID;
4027
David Neto87846742018-04-11 17:36:22 -04004028 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004029 SPIRVInstList.push_back(TmpInst);
4030 }
4031
4032 //
4033 // Generate mask operations.
4034 //
4035
4036 // ShiftLeft mask according to index of insertelement.
4037 SPIRVOperandList Ops;
4038
David Neto257c3892018-04-11 13:19:45 -04004039 const uint32_t ResTyID = lookupType(CompositeTy);
4040 Ops << MkId(ResTyID) << MkId(CstFFID) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004041
4042 uint32_t MaskID = nextID;
4043
David Neto87846742018-04-11 17:36:22 -04004044 auto *Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004045 SPIRVInstList.push_back(Inst);
4046
4047 // Inverse mask.
4048 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004049 Ops << MkId(ResTyID) << MkId(MaskID);
David Neto22f144c2017-06-12 14:26:21 -04004050
4051 uint32_t InvMaskID = nextID;
4052
David Neto87846742018-04-11 17:36:22 -04004053 Inst = new SPIRVInstruction(spv::OpNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004054 SPIRVInstList.push_back(Inst);
4055
4056 // Apply mask.
4057 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004058 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(0)]) << MkId(InvMaskID);
David Neto22f144c2017-06-12 14:26:21 -04004059
4060 uint32_t OrgValID = nextID;
4061
David Neto87846742018-04-11 17:36:22 -04004062 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004063 SPIRVInstList.push_back(Inst);
4064
4065 // Create correct value according to index of insertelement.
4066 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05004067 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(1)])
4068 << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004069
4070 uint32_t InsertValID = nextID;
4071
David Neto87846742018-04-11 17:36:22 -04004072 Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004073 SPIRVInstList.push_back(Inst);
4074
4075 // Insert value to original value.
4076 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004077 Ops << MkId(ResTyID) << MkId(OrgValID) << MkId(InsertValID);
David Neto22f144c2017-06-12 14:26:21 -04004078
David Netoa394f392017-08-26 20:45:29 -04004079 VMap[&I] = nextID;
4080
David Neto87846742018-04-11 17:36:22 -04004081 Inst = new SPIRVInstruction(spv::OpBitwiseOr, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004082 SPIRVInstList.push_back(Inst);
4083
4084 break;
4085 }
4086
David Neto22f144c2017-06-12 14:26:21 -04004087 SPIRVOperandList Ops;
4088
James Priced26efea2018-06-09 23:28:32 +01004089 // Ops[0] = Result Type ID
4090 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004091
4092 spv::Op Opcode = spv::OpCompositeInsert;
4093 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04004094 const auto value = CI->getZExtValue();
4095 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01004096 // Ops[1] = Object ID
4097 // Ops[2] = Composite ID
4098 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004099 Ops << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(0)])
James Priced26efea2018-06-09 23:28:32 +01004100 << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004101 } else {
James Priced26efea2018-06-09 23:28:32 +01004102 // Ops[1] = Composite ID
4103 // Ops[2] = Object ID
4104 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004105 Ops << MkId(VMap[I.getOperand(0)]) << MkId(VMap[I.getOperand(1)])
James Priced26efea2018-06-09 23:28:32 +01004106 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004107 Opcode = spv::OpVectorInsertDynamic;
4108 }
4109
David Neto87846742018-04-11 17:36:22 -04004110 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004111 SPIRVInstList.push_back(Inst);
4112 break;
4113 }
4114 case Instruction::ShuffleVector: {
4115 // Ops[0] = Result Type ID
4116 // Ops[1] = Vector 1 ID
4117 // Ops[2] = Vector 2 ID
4118 // Ops[3] ... Ops[n] = Components (Literal Number)
4119 SPIRVOperandList Ops;
4120
David Neto257c3892018-04-11 13:19:45 -04004121 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4122 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004123
4124 uint64_t NumElements = 0;
4125 if (Constant *Cst = dyn_cast<Constant>(I.getOperand(2))) {
4126 NumElements = cast<VectorType>(Cst->getType())->getNumElements();
4127
4128 if (Cst->isNullValue()) {
4129 for (unsigned i = 0; i < NumElements; i++) {
David Neto257c3892018-04-11 13:19:45 -04004130 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04004131 }
4132 } else if (const ConstantDataSequential *CDS =
4133 dyn_cast<ConstantDataSequential>(Cst)) {
4134 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
4135 std::vector<uint32_t> LiteralNum;
David Neto257c3892018-04-11 13:19:45 -04004136 const auto value = CDS->getElementAsInteger(i);
4137 assert(value <= UINT32_MAX);
4138 Ops << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004139 }
4140 } else if (const ConstantVector *CV = dyn_cast<ConstantVector>(Cst)) {
4141 for (unsigned i = 0; i < CV->getNumOperands(); i++) {
4142 auto Op = CV->getOperand(i);
4143
4144 uint32_t literal = 0;
4145
4146 if (auto CI = dyn_cast<ConstantInt>(Op)) {
4147 literal = static_cast<uint32_t>(CI->getZExtValue());
4148 } else if (auto UI = dyn_cast<UndefValue>(Op)) {
4149 literal = 0xFFFFFFFFu;
4150 } else {
4151 Op->print(errs());
4152 llvm_unreachable("Unsupported element in ConstantVector!");
4153 }
4154
David Neto257c3892018-04-11 13:19:45 -04004155 Ops << MkNum(literal);
David Neto22f144c2017-06-12 14:26:21 -04004156 }
4157 } else {
4158 Cst->print(errs());
4159 llvm_unreachable("Unsupported constant mask in ShuffleVector!");
4160 }
4161 }
4162
David Neto87846742018-04-11 17:36:22 -04004163 auto *Inst = new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004164 SPIRVInstList.push_back(Inst);
4165 break;
4166 }
4167 case Instruction::ICmp:
4168 case Instruction::FCmp: {
4169 CmpInst *CmpI = cast<CmpInst>(&I);
4170
David Netod4ca2e62017-07-06 18:47:35 -04004171 // Pointer equality is invalid.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004172 Type *ArgTy = CmpI->getOperand(0)->getType();
David Netod4ca2e62017-07-06 18:47:35 -04004173 if (isa<PointerType>(ArgTy)) {
4174 CmpI->print(errs());
4175 std::string name = I.getParent()->getParent()->getName();
4176 errs()
4177 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4178 << "in function " << name << "\n";
4179 llvm_unreachable("Pointer equality check is invalid");
4180 break;
4181 }
4182
David Neto257c3892018-04-11 13:19:45 -04004183 // Ops[0] = Result Type ID
4184 // Ops[1] = Operand 1 ID
4185 // Ops[2] = Operand 2 ID
4186 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004187
David Neto257c3892018-04-11 13:19:45 -04004188 Ops << MkId(lookupType(CmpI->getType())) << MkId(VMap[CmpI->getOperand(0)])
4189 << MkId(VMap[CmpI->getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004190
4191 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
David Neto87846742018-04-11 17:36:22 -04004192 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004193 SPIRVInstList.push_back(Inst);
4194 break;
4195 }
4196 case Instruction::Br: {
4197 // Branch instrucion is deferred because it needs label's ID. Record slot's
4198 // location on SPIRVInstructionList.
4199 DeferredInsts.push_back(
4200 std::make_tuple(&I, --SPIRVInstList.end(), 0 /* No id */));
4201 break;
4202 }
4203 case Instruction::Switch: {
4204 I.print(errs());
4205 llvm_unreachable("Unsupported instruction???");
4206 break;
4207 }
4208 case Instruction::IndirectBr: {
4209 I.print(errs());
4210 llvm_unreachable("Unsupported instruction???");
4211 break;
4212 }
4213 case Instruction::PHI: {
4214 // Branch instrucion is deferred because it needs label's ID. Record slot's
4215 // location on SPIRVInstructionList.
4216 DeferredInsts.push_back(
4217 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4218 break;
4219 }
4220 case Instruction::Alloca: {
4221 //
4222 // Generate OpVariable.
4223 //
4224 // Ops[0] : Result Type ID
4225 // Ops[1] : Storage Class
4226 SPIRVOperandList Ops;
4227
David Neto257c3892018-04-11 13:19:45 -04004228 Ops << MkId(lookupType(I.getType())) << MkNum(spv::StorageClassFunction);
David Neto22f144c2017-06-12 14:26:21 -04004229
David Neto87846742018-04-11 17:36:22 -04004230 auto *Inst = new SPIRVInstruction(spv::OpVariable, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004231 SPIRVInstList.push_back(Inst);
4232 break;
4233 }
4234 case Instruction::Load: {
4235 LoadInst *LD = cast<LoadInst>(&I);
4236 //
4237 // Generate OpLoad.
4238 //
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04004239
alan-baker5b86ed72019-02-15 08:26:50 -05004240 if (LD->getType()->isPointerTy()) {
4241 // Loading a pointer requires variable pointers.
4242 setVariablePointersCapabilities(LD->getType()->getPointerAddressSpace());
4243 }
David Neto22f144c2017-06-12 14:26:21 -04004244
David Neto0a2f98d2017-09-15 19:38:40 -04004245 uint32_t ResTyID = lookupType(LD->getType());
David Netoa60b00b2017-09-15 16:34:09 -04004246 uint32_t PointerID = VMap[LD->getPointerOperand()];
4247
4248 // This is a hack to work around what looks like a driver bug.
4249 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004250 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4251 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004252 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004253 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004254 // Generate a bitwise-and of the original value with itself.
4255 // We should have been able to get away with just an OpCopyObject,
4256 // but we need something more complex to get past certain driver bugs.
4257 // This is ridiculous, but necessary.
4258 // TODO(dneto): Revisit this once drivers fix their bugs.
4259
4260 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004261 Ops << MkId(ResTyID) << MkId(WorkgroupSizeValueID)
4262 << MkId(WorkgroupSizeValueID);
David Neto0a2f98d2017-09-15 19:38:40 -04004263
David Neto87846742018-04-11 17:36:22 -04004264 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto0a2f98d2017-09-15 19:38:40 -04004265 SPIRVInstList.push_back(Inst);
David Netoa60b00b2017-09-15 16:34:09 -04004266 break;
4267 }
4268
4269 // This is the normal path. Generate a load.
4270
David Neto22f144c2017-06-12 14:26:21 -04004271 // Ops[0] = Result Type ID
4272 // Ops[1] = Pointer ID
4273 // Ops[2] ... Ops[n] = Optional Memory Access
4274 //
4275 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004276
David Neto22f144c2017-06-12 14:26:21 -04004277 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004278 Ops << MkId(ResTyID) << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04004279
David Neto87846742018-04-11 17:36:22 -04004280 auto *Inst = new SPIRVInstruction(spv::OpLoad, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004281 SPIRVInstList.push_back(Inst);
4282 break;
4283 }
4284 case Instruction::Store: {
4285 StoreInst *ST = cast<StoreInst>(&I);
4286 //
4287 // Generate OpStore.
4288 //
4289
alan-baker5b86ed72019-02-15 08:26:50 -05004290 if (ST->getValueOperand()->getType()->isPointerTy()) {
4291 // Storing a pointer requires variable pointers.
4292 setVariablePointersCapabilities(
4293 ST->getValueOperand()->getType()->getPointerAddressSpace());
4294 }
4295
David Neto22f144c2017-06-12 14:26:21 -04004296 // Ops[0] = Pointer ID
4297 // Ops[1] = Object ID
4298 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4299 //
4300 // TODO: Do we need to implement Optional Memory Access???
David Neto257c3892018-04-11 13:19:45 -04004301 SPIRVOperandList Ops;
4302 Ops << MkId(VMap[ST->getPointerOperand()])
4303 << MkId(VMap[ST->getValueOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004304
David Neto87846742018-04-11 17:36:22 -04004305 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004306 SPIRVInstList.push_back(Inst);
4307 break;
4308 }
4309 case Instruction::AtomicCmpXchg: {
4310 I.print(errs());
4311 llvm_unreachable("Unsupported instruction???");
4312 break;
4313 }
4314 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004315 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4316
4317 spv::Op opcode;
4318
4319 switch (AtomicRMW->getOperation()) {
4320 default:
4321 I.print(errs());
4322 llvm_unreachable("Unsupported instruction???");
4323 case llvm::AtomicRMWInst::Add:
4324 opcode = spv::OpAtomicIAdd;
4325 break;
4326 case llvm::AtomicRMWInst::Sub:
4327 opcode = spv::OpAtomicISub;
4328 break;
4329 case llvm::AtomicRMWInst::Xchg:
4330 opcode = spv::OpAtomicExchange;
4331 break;
4332 case llvm::AtomicRMWInst::Min:
4333 opcode = spv::OpAtomicSMin;
4334 break;
4335 case llvm::AtomicRMWInst::Max:
4336 opcode = spv::OpAtomicSMax;
4337 break;
4338 case llvm::AtomicRMWInst::UMin:
4339 opcode = spv::OpAtomicUMin;
4340 break;
4341 case llvm::AtomicRMWInst::UMax:
4342 opcode = spv::OpAtomicUMax;
4343 break;
4344 case llvm::AtomicRMWInst::And:
4345 opcode = spv::OpAtomicAnd;
4346 break;
4347 case llvm::AtomicRMWInst::Or:
4348 opcode = spv::OpAtomicOr;
4349 break;
4350 case llvm::AtomicRMWInst::Xor:
4351 opcode = spv::OpAtomicXor;
4352 break;
4353 }
4354
4355 //
4356 // Generate OpAtomic*.
4357 //
4358 SPIRVOperandList Ops;
4359
David Neto257c3892018-04-11 13:19:45 -04004360 Ops << MkId(lookupType(I.getType()))
4361 << MkId(VMap[AtomicRMW->getPointerOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004362
4363 auto IntTy = Type::getInt32Ty(I.getContext());
Neil Henning39672102017-09-29 14:33:13 +01004364 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
David Neto257c3892018-04-11 13:19:45 -04004365 Ops << MkId(VMap[ConstantScopeDevice]);
Neil Henning39672102017-09-29 14:33:13 +01004366
4367 const auto ConstantMemorySemantics = ConstantInt::get(
4368 IntTy, spv::MemorySemanticsUniformMemoryMask |
4369 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto257c3892018-04-11 13:19:45 -04004370 Ops << MkId(VMap[ConstantMemorySemantics]);
Neil Henning39672102017-09-29 14:33:13 +01004371
David Neto257c3892018-04-11 13:19:45 -04004372 Ops << MkId(VMap[AtomicRMW->getValOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004373
4374 VMap[&I] = nextID;
4375
David Neto87846742018-04-11 17:36:22 -04004376 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
Neil Henning39672102017-09-29 14:33:13 +01004377 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004378 break;
4379 }
4380 case Instruction::Fence: {
4381 I.print(errs());
4382 llvm_unreachable("Unsupported instruction???");
4383 break;
4384 }
4385 case Instruction::Call: {
4386 CallInst *Call = dyn_cast<CallInst>(&I);
4387 Function *Callee = Call->getCalledFunction();
4388
Alan Baker202c8c72018-08-13 13:47:44 -04004389 if (Callee->getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004390 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
4391 // Generate an OpLoad
4392 SPIRVOperandList Ops;
4393 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004394
David Neto862b7d82018-06-14 18:48:37 -04004395 Ops << MkId(lookupType(Call->getType()->getPointerElementType()))
4396 << MkId(ResourceVarDeferredLoadCalls[Call]);
4397
4398 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
4399 SPIRVInstList.push_back(Inst);
4400 VMap[Call] = load_id;
4401 break;
4402
4403 } else {
4404 // This maps to an OpVariable we've already generated.
4405 // No code is generated for the call.
4406 }
4407 break;
alan-bakerb6b09dc2018-11-08 16:59:28 -05004408 } else if (Callee->getName().startswith(
4409 clspv::WorkgroupAccessorFunction())) {
Alan Baker202c8c72018-08-13 13:47:44 -04004410 // Don't codegen an instruction here, but instead map this call directly
4411 // to the workgroup variable id.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004412 int spec_id = static_cast<int>(
4413 cast<ConstantInt>(Call->getOperand(0))->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04004414 const auto &info = LocalSpecIdInfoMap[spec_id];
4415 VMap[Call] = info.variable_id;
4416 break;
David Neto862b7d82018-06-14 18:48:37 -04004417 }
4418
4419 // Sampler initializers become a load of the corresponding sampler.
4420
Kévin Petitdf71de32019-04-09 14:09:50 +01004421 if (Callee->getName().equals(clspv::LiteralSamplerFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004422 // Map this to a load from the variable.
4423 const auto index_into_sampler_map =
4424 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4425
4426 // Generate an OpLoad
David Neto22f144c2017-06-12 14:26:21 -04004427 SPIRVOperandList Ops;
David Neto862b7d82018-06-14 18:48:37 -04004428 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004429
David Neto257c3892018-04-11 13:19:45 -04004430 Ops << MkId(lookupType(SamplerTy->getPointerElementType()))
alan-bakerb6b09dc2018-11-08 16:59:28 -05004431 << MkId(SamplerMapIndexToIDMap[static_cast<unsigned>(
4432 index_into_sampler_map)]);
David Neto22f144c2017-06-12 14:26:21 -04004433
David Neto862b7d82018-06-14 18:48:37 -04004434 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004435 SPIRVInstList.push_back(Inst);
David Neto862b7d82018-06-14 18:48:37 -04004436 VMap[Call] = load_id;
David Neto22f144c2017-06-12 14:26:21 -04004437 break;
4438 }
4439
Kévin Petit349c9502019-03-28 17:24:14 +00004440 // Handle SPIR-V intrinsics
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04004441 spv::Op opcode =
4442 StringSwitch<spv::Op>(Callee->getName())
4443 .Case("spirv.atomic_add", spv::OpAtomicIAdd)
4444 .Case("spirv.atomic_sub", spv::OpAtomicISub)
4445 .Case("spirv.atomic_exchange", spv::OpAtomicExchange)
4446 .Case("spirv.atomic_inc", spv::OpAtomicIIncrement)
4447 .Case("spirv.atomic_dec", spv::OpAtomicIDecrement)
4448 .Case("spirv.atomic_compare_exchange", spv::OpAtomicCompareExchange)
4449 .Case("spirv.atomic_umin", spv::OpAtomicUMin)
4450 .Case("spirv.atomic_smin", spv::OpAtomicSMin)
4451 .Case("spirv.atomic_umax", spv::OpAtomicUMax)
4452 .Case("spirv.atomic_smax", spv::OpAtomicSMax)
4453 .Case("spirv.atomic_and", spv::OpAtomicAnd)
4454 .Case("spirv.atomic_or", spv::OpAtomicOr)
4455 .Case("spirv.atomic_xor", spv::OpAtomicXor)
4456 .Case("__spirv_control_barrier", spv::OpControlBarrier)
4457 .Case("__spirv_memory_barrier", spv::OpMemoryBarrier)
4458 .StartsWith("spirv.store_null", spv::OpStore)
4459 .StartsWith("__spirv_isinf", spv::OpIsInf)
4460 .StartsWith("__spirv_isnan", spv::OpIsNan)
4461 .StartsWith("__spirv_allDv", spv::OpAll)
4462 .StartsWith("__spirv_anyDv", spv::OpAny)
4463 .Default(spv::OpNop);
David Neto22f144c2017-06-12 14:26:21 -04004464
Kévin Petit617a76d2019-04-04 13:54:16 +01004465 // If the switch above didn't have an entry maybe the intrinsic
4466 // is using the name mangling logic.
4467 bool usesMangler = false;
4468 if (opcode == spv::OpNop) {
4469 if (Callee->getName().startswith(clspv::SPIRVOpIntrinsicFunction())) {
4470 auto OpCst = cast<ConstantInt>(Call->getOperand(0));
4471 opcode = static_cast<spv::Op>(OpCst->getZExtValue());
4472 usesMangler = true;
4473 }
4474 }
4475
Kévin Petit349c9502019-03-28 17:24:14 +00004476 if (opcode != spv::OpNop) {
4477
David Neto22f144c2017-06-12 14:26:21 -04004478 SPIRVOperandList Ops;
4479
Kévin Petit349c9502019-03-28 17:24:14 +00004480 if (!I.getType()->isVoidTy()) {
4481 Ops << MkId(lookupType(I.getType()));
4482 }
David Neto22f144c2017-06-12 14:26:21 -04004483
Kévin Petit617a76d2019-04-04 13:54:16 +01004484 unsigned firstOperand = usesMangler ? 1 : 0;
4485 for (unsigned i = firstOperand; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004486 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004487 }
4488
Kévin Petit349c9502019-03-28 17:24:14 +00004489 if (!I.getType()->isVoidTy()) {
4490 VMap[&I] = nextID;
Kévin Petit8a560882019-03-21 15:24:34 +00004491 }
4492
Kévin Petit349c9502019-03-28 17:24:14 +00004493 SPIRVInstruction *Inst;
4494 if (!I.getType()->isVoidTy()) {
4495 Inst = new SPIRVInstruction(opcode, nextID++, Ops);
4496 } else {
4497 Inst = new SPIRVInstruction(opcode, Ops);
4498 }
Kévin Petit8a560882019-03-21 15:24:34 +00004499 SPIRVInstList.push_back(Inst);
4500 break;
4501 }
4502
David Neto22f144c2017-06-12 14:26:21 -04004503 if (Callee->getName().startswith("_Z3dot")) {
4504 // If the argument is a vector type, generate OpDot
4505 if (Call->getArgOperand(0)->getType()->isVectorTy()) {
4506 //
4507 // Generate OpDot.
4508 //
4509 SPIRVOperandList Ops;
4510
David Neto257c3892018-04-11 13:19:45 -04004511 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004512
4513 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004514 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004515 }
4516
4517 VMap[&I] = nextID;
4518
David Neto87846742018-04-11 17:36:22 -04004519 auto *Inst = new SPIRVInstruction(spv::OpDot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004520 SPIRVInstList.push_back(Inst);
4521 } else {
4522 //
4523 // Generate OpFMul.
4524 //
4525 SPIRVOperandList Ops;
4526
David Neto257c3892018-04-11 13:19:45 -04004527 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004528
4529 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004530 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004531 }
4532
4533 VMap[&I] = nextID;
4534
David Neto87846742018-04-11 17:36:22 -04004535 auto *Inst = new SPIRVInstruction(spv::OpFMul, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004536 SPIRVInstList.push_back(Inst);
4537 }
4538 break;
4539 }
4540
David Neto8505ebf2017-10-13 18:50:50 -04004541 if (Callee->getName().startswith("_Z4fmod")) {
4542 // OpenCL fmod(x,y) is x - y * trunc(x/y)
4543 // The sign for a non-zero result is taken from x.
4544 // (Try an example.)
4545 // So translate to OpFRem
4546
4547 SPIRVOperandList Ops;
4548
David Neto257c3892018-04-11 13:19:45 -04004549 Ops << MkId(lookupType(I.getType()));
David Neto8505ebf2017-10-13 18:50:50 -04004550
4551 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004552 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto8505ebf2017-10-13 18:50:50 -04004553 }
4554
4555 VMap[&I] = nextID;
4556
David Neto87846742018-04-11 17:36:22 -04004557 auto *Inst = new SPIRVInstruction(spv::OpFRem, nextID++, Ops);
David Neto8505ebf2017-10-13 18:50:50 -04004558 SPIRVInstList.push_back(Inst);
4559 break;
4560 }
4561
David Neto22f144c2017-06-12 14:26:21 -04004562 // spirv.copy_memory.* intrinsics become OpMemoryMemory's.
4563 if (Callee->getName().startswith("spirv.copy_memory")) {
4564 //
4565 // Generate OpCopyMemory.
4566 //
4567
4568 // Ops[0] = Dst ID
4569 // Ops[1] = Src ID
4570 // Ops[2] = Memory Access
4571 // Ops[3] = Alignment
4572
4573 auto IsVolatile =
4574 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
4575
4576 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
4577 : spv::MemoryAccessMaskNone;
4578
4579 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
4580
4581 auto Alignment =
4582 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4583
David Neto257c3892018-04-11 13:19:45 -04004584 SPIRVOperandList Ops;
4585 Ops << MkId(VMap[Call->getArgOperand(0)])
4586 << MkId(VMap[Call->getArgOperand(1)]) << MkNum(MemoryAccess)
4587 << MkNum(static_cast<uint32_t>(Alignment));
David Neto22f144c2017-06-12 14:26:21 -04004588
David Neto87846742018-04-11 17:36:22 -04004589 auto *Inst = new SPIRVInstruction(spv::OpCopyMemory, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004590
4591 SPIRVInstList.push_back(Inst);
4592
4593 break;
4594 }
4595
David Neto22f144c2017-06-12 14:26:21 -04004596 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
4597 // Additionally, OpTypeSampledImage is generated.
4598 if (Callee->getName().equals(
4599 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
4600 Callee->getName().equals(
4601 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
4602 //
4603 // Generate OpSampledImage.
4604 //
4605 // Ops[0] = Result Type ID
4606 // Ops[1] = Image ID
4607 // Ops[2] = Sampler ID
4608 //
4609 SPIRVOperandList Ops;
4610
4611 Value *Image = Call->getArgOperand(0);
4612 Value *Sampler = Call->getArgOperand(1);
4613 Value *Coordinate = Call->getArgOperand(2);
4614
4615 TypeMapType &OpImageTypeMap = getImageTypeMap();
4616 Type *ImageTy = Image->getType()->getPointerElementType();
4617 uint32_t ImageTyID = OpImageTypeMap[ImageTy];
David Neto22f144c2017-06-12 14:26:21 -04004618 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004619 uint32_t SamplerID = VMap[Sampler];
David Neto257c3892018-04-11 13:19:45 -04004620
4621 Ops << MkId(ImageTyID) << MkId(ImageID) << MkId(SamplerID);
David Neto22f144c2017-06-12 14:26:21 -04004622
4623 uint32_t SampledImageID = nextID;
4624
David Neto87846742018-04-11 17:36:22 -04004625 auto *Inst = new SPIRVInstruction(spv::OpSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004626 SPIRVInstList.push_back(Inst);
4627
4628 //
4629 // Generate OpImageSampleExplicitLod.
4630 //
4631 // Ops[0] = Result Type ID
4632 // Ops[1] = Sampled Image ID
4633 // Ops[2] = Coordinate ID
4634 // Ops[3] = Image Operands Type ID
4635 // Ops[4] ... Ops[n] = Operands ID
4636 //
4637 Ops.clear();
4638
David Neto257c3892018-04-11 13:19:45 -04004639 Ops << MkId(lookupType(Call->getType())) << MkId(SampledImageID)
4640 << MkId(VMap[Coordinate]) << MkNum(spv::ImageOperandsLodMask);
David Neto22f144c2017-06-12 14:26:21 -04004641
4642 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
David Neto257c3892018-04-11 13:19:45 -04004643 Ops << MkId(VMap[CstFP0]);
David Neto22f144c2017-06-12 14:26:21 -04004644
4645 VMap[&I] = nextID;
4646
David Neto87846742018-04-11 17:36:22 -04004647 Inst = new SPIRVInstruction(spv::OpImageSampleExplicitLod, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004648 SPIRVInstList.push_back(Inst);
4649 break;
4650 }
4651
4652 // write_imagef is mapped to OpImageWrite.
4653 if (Callee->getName().equals(
4654 "_Z12write_imagef14ocl_image2d_woDv2_iDv4_f") ||
4655 Callee->getName().equals(
4656 "_Z12write_imagef14ocl_image3d_woDv4_iDv4_f")) {
4657 //
4658 // Generate OpImageWrite.
4659 //
4660 // Ops[0] = Image ID
4661 // Ops[1] = Coordinate ID
4662 // Ops[2] = Texel ID
4663 // Ops[3] = (Optional) Image Operands Type (Literal Number)
4664 // Ops[4] ... Ops[n] = (Optional) Operands ID
4665 //
4666 SPIRVOperandList Ops;
4667
4668 Value *Image = Call->getArgOperand(0);
4669 Value *Coordinate = Call->getArgOperand(1);
4670 Value *Texel = Call->getArgOperand(2);
4671
4672 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004673 uint32_t CoordinateID = VMap[Coordinate];
David Neto22f144c2017-06-12 14:26:21 -04004674 uint32_t TexelID = VMap[Texel];
David Neto257c3892018-04-11 13:19:45 -04004675 Ops << MkId(ImageID) << MkId(CoordinateID) << MkId(TexelID);
David Neto22f144c2017-06-12 14:26:21 -04004676
David Neto87846742018-04-11 17:36:22 -04004677 auto *Inst = new SPIRVInstruction(spv::OpImageWrite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004678 SPIRVInstList.push_back(Inst);
4679 break;
4680 }
4681
David Neto5c22a252018-03-15 16:07:41 -04004682 // get_image_width is mapped to OpImageQuerySize
4683 if (Callee->getName().equals("_Z15get_image_width14ocl_image2d_ro") ||
4684 Callee->getName().equals("_Z15get_image_width14ocl_image2d_wo") ||
4685 Callee->getName().equals("_Z16get_image_height14ocl_image2d_ro") ||
4686 Callee->getName().equals("_Z16get_image_height14ocl_image2d_wo")) {
4687 //
4688 // Generate OpImageQuerySize, then pull out the right component.
4689 // Assume 2D image for now.
4690 //
4691 // Ops[0] = Image ID
4692 //
4693 // %sizes = OpImageQuerySizes %uint2 %im
4694 // %result = OpCompositeExtract %uint %sizes 0-or-1
4695 SPIRVOperandList Ops;
4696
4697 // Implement:
4698 // %sizes = OpImageQuerySizes %uint2 %im
4699 uint32_t SizesTypeID =
4700 TypeMap[VectorType::get(Type::getInt32Ty(Context), 2)];
David Neto5c22a252018-03-15 16:07:41 -04004701 Value *Image = Call->getArgOperand(0);
4702 uint32_t ImageID = VMap[Image];
David Neto257c3892018-04-11 13:19:45 -04004703 Ops << MkId(SizesTypeID) << MkId(ImageID);
David Neto5c22a252018-03-15 16:07:41 -04004704
4705 uint32_t SizesID = nextID++;
David Neto87846742018-04-11 17:36:22 -04004706 auto *QueryInst =
4707 new SPIRVInstruction(spv::OpImageQuerySize, SizesID, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004708 SPIRVInstList.push_back(QueryInst);
4709
4710 // Reset value map entry since we generated an intermediate instruction.
4711 VMap[&I] = nextID;
4712
4713 // Implement:
4714 // %result = OpCompositeExtract %uint %sizes 0-or-1
4715 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004716 Ops << MkId(TypeMap[I.getType()]) << MkId(SizesID);
David Neto5c22a252018-03-15 16:07:41 -04004717
4718 uint32_t component = Callee->getName().contains("height") ? 1 : 0;
David Neto257c3892018-04-11 13:19:45 -04004719 Ops << MkNum(component);
David Neto5c22a252018-03-15 16:07:41 -04004720
David Neto87846742018-04-11 17:36:22 -04004721 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004722 SPIRVInstList.push_back(Inst);
4723 break;
4724 }
4725
David Neto22f144c2017-06-12 14:26:21 -04004726 // Call instrucion is deferred because it needs function's ID. Record
4727 // slot's location on SPIRVInstructionList.
4728 DeferredInsts.push_back(
4729 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4730
David Neto3fbb4072017-10-16 11:28:14 -04004731 // Check whether the implementation of this call uses an extended
4732 // instruction plus one more value-producing instruction. If so, then
4733 // reserve the id for the extra value-producing slot.
4734 glsl::ExtInst EInst = getIndirectExtInstEnum(Callee->getName());
4735 if (EInst != kGlslExtInstBad) {
4736 // Reserve a spot for the extra value.
David Neto4d02a532017-09-17 12:57:44 -04004737 // Increase nextID.
David Neto22f144c2017-06-12 14:26:21 -04004738 VMap[&I] = nextID;
4739 nextID++;
4740 }
4741 break;
4742 }
4743 case Instruction::Ret: {
4744 unsigned NumOps = I.getNumOperands();
4745 if (NumOps == 0) {
4746 //
4747 // Generate OpReturn.
4748 //
David Neto87846742018-04-11 17:36:22 -04004749 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpReturn, {}));
David Neto22f144c2017-06-12 14:26:21 -04004750 } else {
4751 //
4752 // Generate OpReturnValue.
4753 //
4754
4755 // Ops[0] = Return Value ID
4756 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004757
4758 Ops << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004759
David Neto87846742018-04-11 17:36:22 -04004760 auto *Inst = new SPIRVInstruction(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004761 SPIRVInstList.push_back(Inst);
4762 break;
4763 }
4764 break;
4765 }
4766 }
4767}
4768
4769void SPIRVProducerPass::GenerateFuncEpilogue() {
4770 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4771
4772 //
4773 // Generate OpFunctionEnd
4774 //
4775
David Neto87846742018-04-11 17:36:22 -04004776 auto *Inst = new SPIRVInstruction(spv::OpFunctionEnd, {});
David Neto22f144c2017-06-12 14:26:21 -04004777 SPIRVInstList.push_back(Inst);
4778}
4779
4780bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
alan-bakerb39c8262019-03-08 14:03:37 -05004781 // Don't specialize <4 x i8> if i8 is generally supported.
4782 if (clspv::Option::Int8Support())
4783 return false;
4784
David Neto22f144c2017-06-12 14:26:21 -04004785 LLVMContext &Context = Ty->getContext();
4786 if (Ty->isVectorTy()) {
4787 if (Ty->getVectorElementType() == Type::getInt8Ty(Context) &&
4788 Ty->getVectorNumElements() == 4) {
4789 return true;
4790 }
4791 }
4792
4793 return false;
4794}
4795
David Neto257c3892018-04-11 13:19:45 -04004796uint32_t SPIRVProducerPass::GetI32Zero() {
4797 if (0 == constant_i32_zero_id_) {
4798 llvm_unreachable("Requesting a 32-bit integer constant but it is not "
4799 "defined in the SPIR-V module");
4800 }
4801 return constant_i32_zero_id_;
4802}
4803
David Neto22f144c2017-06-12 14:26:21 -04004804void SPIRVProducerPass::HandleDeferredInstruction() {
4805 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4806 ValueMapType &VMap = getValueMap();
4807 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4808
4809 for (auto DeferredInst = DeferredInsts.rbegin();
4810 DeferredInst != DeferredInsts.rend(); ++DeferredInst) {
4811 Value *Inst = std::get<0>(*DeferredInst);
4812 SPIRVInstructionList::iterator InsertPoint = ++std::get<1>(*DeferredInst);
4813 if (InsertPoint != SPIRVInstList.end()) {
4814 while ((*InsertPoint)->getOpcode() == spv::OpPhi) {
4815 ++InsertPoint;
4816 }
4817 }
4818
4819 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
4820 // Check whether basic block, which has this branch instruction, is loop
4821 // header or not. If it is loop header, generate OpLoopMerge and
4822 // OpBranchConditional.
4823 Function *Func = Br->getParent()->getParent();
4824 DominatorTree &DT =
4825 getAnalysis<DominatorTreeWrapperPass>(*Func).getDomTree();
4826 const LoopInfo &LI =
4827 getAnalysis<LoopInfoWrapperPass>(*Func).getLoopInfo();
4828
4829 BasicBlock *BrBB = Br->getParent();
4830 if (LI.isLoopHeader(BrBB)) {
4831 Value *ContinueBB = nullptr;
4832 Value *MergeBB = nullptr;
4833
4834 Loop *L = LI.getLoopFor(BrBB);
4835 MergeBB = L->getExitBlock();
4836 if (!MergeBB) {
4837 // StructurizeCFG pass converts CFG into triangle shape and the cfg
4838 // has regions with single entry/exit. As a result, loop should not
4839 // have multiple exits.
4840 llvm_unreachable("Loop has multiple exits???");
4841 }
4842
4843 if (L->isLoopLatch(BrBB)) {
4844 ContinueBB = BrBB;
4845 } else {
4846 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
4847 // block.
4848 BasicBlock *Header = L->getHeader();
4849 BasicBlock *Latch = L->getLoopLatch();
4850 for (BasicBlock *BB : L->blocks()) {
4851 if (BB == Header) {
4852 continue;
4853 }
4854
4855 // Check whether block dominates block with back-edge.
4856 if (DT.dominates(BB, Latch)) {
4857 ContinueBB = BB;
4858 }
4859 }
4860
4861 if (!ContinueBB) {
4862 llvm_unreachable("Wrong continue block from loop");
4863 }
4864 }
4865
4866 //
4867 // Generate OpLoopMerge.
4868 //
4869 // Ops[0] = Merge Block ID
4870 // Ops[1] = Continue Target ID
4871 // Ops[2] = Selection Control
4872 SPIRVOperandList Ops;
4873
4874 // StructurizeCFG pass already manipulated CFG. Just use false block of
4875 // branch instruction as merge block.
4876 uint32_t MergeBBID = VMap[MergeBB];
David Neto22f144c2017-06-12 14:26:21 -04004877 uint32_t ContinueBBID = VMap[ContinueBB];
David Neto257c3892018-04-11 13:19:45 -04004878 Ops << MkId(MergeBBID) << MkId(ContinueBBID)
4879 << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004880
David Neto87846742018-04-11 17:36:22 -04004881 auto *MergeInst = new SPIRVInstruction(spv::OpLoopMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004882 SPIRVInstList.insert(InsertPoint, MergeInst);
4883
4884 } else if (Br->isConditional()) {
4885 bool HasBackEdge = false;
4886
4887 for (unsigned i = 0; i < Br->getNumSuccessors(); i++) {
4888 if (LI.isLoopHeader(Br->getSuccessor(i))) {
4889 HasBackEdge = true;
4890 }
4891 }
4892 if (!HasBackEdge) {
4893 //
4894 // Generate OpSelectionMerge.
4895 //
4896 // Ops[0] = Merge Block ID
4897 // Ops[1] = Selection Control
4898 SPIRVOperandList Ops;
4899
4900 // StructurizeCFG pass already manipulated CFG. Just use false block
4901 // of branch instruction as merge block.
4902 uint32_t MergeBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004903 Ops << MkId(MergeBBID) << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004904
David Neto87846742018-04-11 17:36:22 -04004905 auto *MergeInst = new SPIRVInstruction(spv::OpSelectionMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004906 SPIRVInstList.insert(InsertPoint, MergeInst);
4907 }
4908 }
4909
4910 if (Br->isConditional()) {
4911 //
4912 // Generate OpBranchConditional.
4913 //
4914 // Ops[0] = Condition ID
4915 // Ops[1] = True Label ID
4916 // Ops[2] = False Label ID
4917 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
4918 SPIRVOperandList Ops;
4919
4920 uint32_t CondID = VMap[Br->getCondition()];
David Neto22f144c2017-06-12 14:26:21 -04004921 uint32_t TrueBBID = VMap[Br->getSuccessor(0)];
David Neto22f144c2017-06-12 14:26:21 -04004922 uint32_t FalseBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004923
4924 Ops << MkId(CondID) << MkId(TrueBBID) << MkId(FalseBBID);
David Neto22f144c2017-06-12 14:26:21 -04004925
David Neto87846742018-04-11 17:36:22 -04004926 auto *BrInst = new SPIRVInstruction(spv::OpBranchConditional, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004927 SPIRVInstList.insert(InsertPoint, BrInst);
4928 } else {
4929 //
4930 // Generate OpBranch.
4931 //
4932 // Ops[0] = Target Label ID
4933 SPIRVOperandList Ops;
4934
4935 uint32_t TargetID = VMap[Br->getSuccessor(0)];
David Neto257c3892018-04-11 13:19:45 -04004936 Ops << MkId(TargetID);
David Neto22f144c2017-06-12 14:26:21 -04004937
David Neto87846742018-04-11 17:36:22 -04004938 SPIRVInstList.insert(InsertPoint,
4939 new SPIRVInstruction(spv::OpBranch, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004940 }
4941 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
alan-baker5b86ed72019-02-15 08:26:50 -05004942 if (PHI->getType()->isPointerTy()) {
4943 // OpPhi on pointers requires variable pointers.
4944 setVariablePointersCapabilities(
4945 PHI->getType()->getPointerAddressSpace());
4946 if (!hasVariablePointers() && !selectFromSameObject(PHI)) {
4947 setVariablePointers(true);
4948 }
4949 }
4950
David Neto22f144c2017-06-12 14:26:21 -04004951 //
4952 // Generate OpPhi.
4953 //
4954 // Ops[0] = Result Type ID
4955 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
4956 SPIRVOperandList Ops;
4957
David Neto257c3892018-04-11 13:19:45 -04004958 Ops << MkId(lookupType(PHI->getType()));
David Neto22f144c2017-06-12 14:26:21 -04004959
David Neto22f144c2017-06-12 14:26:21 -04004960 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
4961 uint32_t VarID = VMap[PHI->getIncomingValue(i)];
David Neto22f144c2017-06-12 14:26:21 -04004962 uint32_t ParentID = VMap[PHI->getIncomingBlock(i)];
David Neto257c3892018-04-11 13:19:45 -04004963 Ops << MkId(VarID) << MkId(ParentID);
David Neto22f144c2017-06-12 14:26:21 -04004964 }
4965
4966 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04004967 InsertPoint,
4968 new SPIRVInstruction(spv::OpPhi, std::get<2>(*DeferredInst), Ops));
David Neto22f144c2017-06-12 14:26:21 -04004969 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
4970 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04004971 auto callee_name = Callee->getName();
4972 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04004973
4974 if (EInst) {
4975 uint32_t &ExtInstImportID = getOpExtInstImportID();
4976
4977 //
4978 // Generate OpExtInst.
4979 //
4980
4981 // Ops[0] = Result Type ID
4982 // Ops[1] = Set ID (OpExtInstImport ID)
4983 // Ops[2] = Instruction Number (Literal Number)
4984 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
4985 SPIRVOperandList Ops;
4986
David Neto862b7d82018-06-14 18:48:37 -04004987 Ops << MkId(lookupType(Call->getType())) << MkId(ExtInstImportID)
4988 << MkNum(EInst);
David Neto22f144c2017-06-12 14:26:21 -04004989
David Neto22f144c2017-06-12 14:26:21 -04004990 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
4991 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004992 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004993 }
4994
David Neto87846742018-04-11 17:36:22 -04004995 auto *ExtInst = new SPIRVInstruction(spv::OpExtInst,
4996 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04004997 SPIRVInstList.insert(InsertPoint, ExtInst);
4998
David Neto3fbb4072017-10-16 11:28:14 -04004999 const auto IndirectExtInst = getIndirectExtInstEnum(callee_name);
5000 if (IndirectExtInst != kGlslExtInstBad) {
5001 // Generate one more instruction that uses the result of the extended
5002 // instruction. Its result id is one more than the id of the
5003 // extended instruction.
David Neto22f144c2017-06-12 14:26:21 -04005004 LLVMContext &Context =
5005 Call->getParent()->getParent()->getParent()->getContext();
David Neto22f144c2017-06-12 14:26:21 -04005006
David Neto3fbb4072017-10-16 11:28:14 -04005007 auto generate_extra_inst = [this, &Context, &Call, &DeferredInst,
5008 &VMap, &SPIRVInstList, &InsertPoint](
5009 spv::Op opcode, Constant *constant) {
5010 //
5011 // Generate instruction like:
5012 // result = opcode constant <extinst-result>
5013 //
5014 // Ops[0] = Result Type ID
5015 // Ops[1] = Operand 0 ;; the constant, suitably splatted
5016 // Ops[2] = Operand 1 ;; the result of the extended instruction
5017 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04005018
David Neto3fbb4072017-10-16 11:28:14 -04005019 Type *resultTy = Call->getType();
David Neto257c3892018-04-11 13:19:45 -04005020 Ops << MkId(lookupType(resultTy));
David Neto3fbb4072017-10-16 11:28:14 -04005021
5022 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
5023 constant = ConstantVector::getSplat(
5024 static_cast<unsigned>(vectorTy->getNumElements()), constant);
5025 }
David Neto257c3892018-04-11 13:19:45 -04005026 Ops << MkId(VMap[constant]) << MkId(std::get<2>(*DeferredInst));
David Neto3fbb4072017-10-16 11:28:14 -04005027
5028 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005029 InsertPoint, new SPIRVInstruction(
5030 opcode, std::get<2>(*DeferredInst) + 1, Ops));
David Neto3fbb4072017-10-16 11:28:14 -04005031 };
5032
5033 switch (IndirectExtInst) {
5034 case glsl::ExtInstFindUMsb: // Implementing clz
5035 generate_extra_inst(
5036 spv::OpISub, ConstantInt::get(Type::getInt32Ty(Context), 31));
5037 break;
5038 case glsl::ExtInstAcos: // Implementing acospi
5039 case glsl::ExtInstAsin: // Implementing asinpi
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005040 case glsl::ExtInstAtan: // Implementing atanpi
David Neto3fbb4072017-10-16 11:28:14 -04005041 case glsl::ExtInstAtan2: // Implementing atan2pi
5042 generate_extra_inst(
5043 spv::OpFMul,
5044 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
5045 break;
5046
5047 default:
5048 assert(false && "internally inconsistent");
David Neto4d02a532017-09-17 12:57:44 -04005049 }
David Neto22f144c2017-06-12 14:26:21 -04005050 }
David Neto3fbb4072017-10-16 11:28:14 -04005051
alan-bakerb39c8262019-03-08 14:03:37 -05005052 } else if (callee_name.startswith("_Z8popcount")) {
David Neto22f144c2017-06-12 14:26:21 -04005053 //
5054 // Generate OpBitCount
5055 //
5056 // Ops[0] = Result Type ID
5057 // Ops[1] = Base ID
David Neto257c3892018-04-11 13:19:45 -04005058 SPIRVOperandList Ops;
5059 Ops << MkId(lookupType(Call->getType()))
5060 << MkId(VMap[Call->getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04005061
5062 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005063 InsertPoint, new SPIRVInstruction(spv::OpBitCount,
David Neto22f144c2017-06-12 14:26:21 -04005064 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005065
David Neto862b7d82018-06-14 18:48:37 -04005066 } else if (callee_name.startswith(kCompositeConstructFunctionPrefix)) {
David Netoab03f432017-11-03 17:00:44 -04005067
5068 // Generate an OpCompositeConstruct
5069 SPIRVOperandList Ops;
5070
5071 // The result type.
David Neto257c3892018-04-11 13:19:45 -04005072 Ops << MkId(lookupType(Call->getType()));
David Netoab03f432017-11-03 17:00:44 -04005073
5074 for (Use &use : Call->arg_operands()) {
David Neto257c3892018-04-11 13:19:45 -04005075 Ops << MkId(VMap[use.get()]);
David Netoab03f432017-11-03 17:00:44 -04005076 }
5077
5078 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005079 InsertPoint, new SPIRVInstruction(spv::OpCompositeConstruct,
5080 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005081
Alan Baker202c8c72018-08-13 13:47:44 -04005082 } else if (callee_name.startswith(clspv::ResourceAccessorFunction())) {
5083
5084 // We have already mapped the call's result value to an ID.
5085 // Don't generate any code now.
5086
5087 } else if (callee_name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04005088
5089 // We have already mapped the call's result value to an ID.
5090 // Don't generate any code now.
5091
David Neto22f144c2017-06-12 14:26:21 -04005092 } else {
alan-baker5b86ed72019-02-15 08:26:50 -05005093 if (Call->getType()->isPointerTy()) {
5094 // Functions returning pointers require variable pointers.
5095 setVariablePointersCapabilities(
5096 Call->getType()->getPointerAddressSpace());
5097 }
5098
David Neto22f144c2017-06-12 14:26:21 -04005099 //
5100 // Generate OpFunctionCall.
5101 //
5102
5103 // Ops[0] = Result Type ID
5104 // Ops[1] = Callee Function ID
5105 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
5106 SPIRVOperandList Ops;
5107
David Neto862b7d82018-06-14 18:48:37 -04005108 Ops << MkId(lookupType(Call->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005109
5110 uint32_t CalleeID = VMap[Callee];
David Neto43568eb2017-10-13 18:25:25 -04005111 if (CalleeID == 0) {
5112 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04005113 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04005114 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
5115 // causes an infinite loop. Instead, go ahead and generate
5116 // the bad function call. A validator will catch the 0-Id.
5117 // llvm_unreachable("Can't translate function call");
5118 }
David Neto22f144c2017-06-12 14:26:21 -04005119
David Neto257c3892018-04-11 13:19:45 -04005120 Ops << MkId(CalleeID);
David Neto22f144c2017-06-12 14:26:21 -04005121
David Neto22f144c2017-06-12 14:26:21 -04005122 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5123 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
alan-baker5b86ed72019-02-15 08:26:50 -05005124 auto *operand = Call->getOperand(i);
5125 if (operand->getType()->isPointerTy()) {
5126 auto sc =
5127 GetStorageClass(operand->getType()->getPointerAddressSpace());
5128 if (sc == spv::StorageClassStorageBuffer) {
5129 // Passing SSBO by reference requires variable pointers storage
5130 // buffer.
5131 setVariablePointersStorageBuffer(true);
5132 } else if (sc == spv::StorageClassWorkgroup) {
5133 // Workgroup references require variable pointers if they are not
5134 // memory object declarations.
5135 if (auto *operand_call = dyn_cast<CallInst>(operand)) {
5136 // Workgroup accessor represents a variable reference.
5137 if (!operand_call->getCalledFunction()->getName().startswith(
5138 clspv::WorkgroupAccessorFunction()))
5139 setVariablePointers(true);
5140 } else {
5141 // Arguments are function parameters.
5142 if (!isa<Argument>(operand))
5143 setVariablePointers(true);
5144 }
5145 }
5146 }
5147 Ops << MkId(VMap[operand]);
David Neto22f144c2017-06-12 14:26:21 -04005148 }
5149
David Neto87846742018-04-11 17:36:22 -04005150 auto *CallInst = new SPIRVInstruction(spv::OpFunctionCall,
5151 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005152 SPIRVInstList.insert(InsertPoint, CallInst);
5153 }
5154 }
5155 }
5156}
5157
David Neto1a1a0582017-07-07 12:01:44 -04005158void SPIRVProducerPass::HandleDeferredDecorations(const DataLayout &DL) {
Alan Baker202c8c72018-08-13 13:47:44 -04005159 if (getTypesNeedingArrayStride().empty() && LocalArgSpecIds.empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04005160 return;
David Netoc6f3ab22018-04-06 18:02:31 -04005161 }
David Neto1a1a0582017-07-07 12:01:44 -04005162
5163 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto1a1a0582017-07-07 12:01:44 -04005164
5165 // Find an iterator pointing just past the last decoration.
5166 bool seen_decorations = false;
5167 auto DecoInsertPoint =
5168 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
5169 [&seen_decorations](SPIRVInstruction *Inst) -> bool {
5170 const bool is_decoration =
5171 Inst->getOpcode() == spv::OpDecorate ||
5172 Inst->getOpcode() == spv::OpMemberDecorate;
5173 if (is_decoration) {
5174 seen_decorations = true;
5175 return false;
5176 } else {
5177 return seen_decorations;
5178 }
5179 });
5180
David Netoc6f3ab22018-04-06 18:02:31 -04005181 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
5182 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07005183 for (auto *type : getTypesNeedingArrayStride()) {
5184 Type *elemTy = nullptr;
5185 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
5186 elemTy = ptrTy->getElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005187 } else if (auto *arrayTy = dyn_cast<ArrayType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005188 elemTy = arrayTy->getArrayElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005189 } else if (auto *seqTy = dyn_cast<SequentialType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005190 elemTy = seqTy->getSequentialElementType();
5191 } else {
5192 errs() << "Unhandled strided type " << *type << "\n";
5193 llvm_unreachable("Unhandled strided type");
5194 }
David Neto1a1a0582017-07-07 12:01:44 -04005195
5196 // Ops[0] = Target ID
5197 // Ops[1] = Decoration (ArrayStride)
5198 // Ops[2] = Stride number (Literal Number)
5199 SPIRVOperandList Ops;
5200
David Neto85082642018-03-24 06:55:20 -07005201 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Alan Bakerfcda9482018-10-02 17:09:59 -04005202 const uint32_t stride = static_cast<uint32_t>(GetTypeAllocSize(elemTy, DL));
David Neto257c3892018-04-11 13:19:45 -04005203
5204 Ops << MkId(lookupType(type)) << MkNum(spv::DecorationArrayStride)
5205 << MkNum(stride);
David Neto1a1a0582017-07-07 12:01:44 -04005206
David Neto87846742018-04-11 17:36:22 -04005207 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto1a1a0582017-07-07 12:01:44 -04005208 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
5209 }
David Netoc6f3ab22018-04-06 18:02:31 -04005210
5211 // Emit SpecId decorations targeting the array size value.
Alan Baker202c8c72018-08-13 13:47:44 -04005212 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
5213 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005214 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04005215 SPIRVOperandList Ops;
5216 Ops << MkId(arg_info.array_size_id) << MkNum(spv::DecorationSpecId)
5217 << MkNum(arg_info.spec_id);
5218 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04005219 new SPIRVInstruction(spv::OpDecorate, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04005220 }
David Neto1a1a0582017-07-07 12:01:44 -04005221}
5222
David Neto22f144c2017-06-12 14:26:21 -04005223glsl::ExtInst SPIRVProducerPass::getExtInstEnum(StringRef Name) {
5224 return StringSwitch<glsl::ExtInst>(Name)
alan-bakerb39c8262019-03-08 14:03:37 -05005225 .Case("_Z3absc", glsl::ExtInst::ExtInstSAbs)
5226 .Case("_Z3absDv2_c", glsl::ExtInst::ExtInstSAbs)
5227 .Case("_Z3absDv3_c", glsl::ExtInst::ExtInstSAbs)
5228 .Case("_Z3absDv4_c", glsl::ExtInst::ExtInstSAbs)
Kévin Petit2444e9b2018-11-09 14:14:37 +00005229 .Case("_Z3abss", glsl::ExtInst::ExtInstSAbs)
5230 .Case("_Z3absDv2_s", glsl::ExtInst::ExtInstSAbs)
5231 .Case("_Z3absDv3_s", glsl::ExtInst::ExtInstSAbs)
5232 .Case("_Z3absDv4_s", glsl::ExtInst::ExtInstSAbs)
David Neto22f144c2017-06-12 14:26:21 -04005233 .Case("_Z3absi", glsl::ExtInst::ExtInstSAbs)
5234 .Case("_Z3absDv2_i", glsl::ExtInst::ExtInstSAbs)
5235 .Case("_Z3absDv3_i", glsl::ExtInst::ExtInstSAbs)
5236 .Case("_Z3absDv4_i", glsl::ExtInst::ExtInstSAbs)
Kévin Petit2444e9b2018-11-09 14:14:37 +00005237 .Case("_Z3absl", glsl::ExtInst::ExtInstSAbs)
5238 .Case("_Z3absDv2_l", glsl::ExtInst::ExtInstSAbs)
5239 .Case("_Z3absDv3_l", glsl::ExtInst::ExtInstSAbs)
5240 .Case("_Z3absDv4_l", glsl::ExtInst::ExtInstSAbs)
alan-bakerb39c8262019-03-08 14:03:37 -05005241 .Case("_Z5clampccc", glsl::ExtInst::ExtInstSClamp)
5242 .Case("_Z5clampDv2_cS_S_", glsl::ExtInst::ExtInstSClamp)
5243 .Case("_Z5clampDv3_cS_S_", glsl::ExtInst::ExtInstSClamp)
5244 .Case("_Z5clampDv4_cS_S_", glsl::ExtInst::ExtInstSClamp)
5245 .Case("_Z5clamphhh", glsl::ExtInst::ExtInstUClamp)
5246 .Case("_Z5clampDv2_hS_S_", glsl::ExtInst::ExtInstUClamp)
5247 .Case("_Z5clampDv3_hS_S_", glsl::ExtInst::ExtInstUClamp)
5248 .Case("_Z5clampDv4_hS_S_", glsl::ExtInst::ExtInstUClamp)
Kévin Petit495255d2019-03-06 13:56:48 +00005249 .Case("_Z5clampsss", glsl::ExtInst::ExtInstSClamp)
5250 .Case("_Z5clampDv2_sS_S_", glsl::ExtInst::ExtInstSClamp)
5251 .Case("_Z5clampDv3_sS_S_", glsl::ExtInst::ExtInstSClamp)
5252 .Case("_Z5clampDv4_sS_S_", glsl::ExtInst::ExtInstSClamp)
5253 .Case("_Z5clampttt", glsl::ExtInst::ExtInstUClamp)
5254 .Case("_Z5clampDv2_tS_S_", glsl::ExtInst::ExtInstUClamp)
5255 .Case("_Z5clampDv3_tS_S_", glsl::ExtInst::ExtInstUClamp)
5256 .Case("_Z5clampDv4_tS_S_", glsl::ExtInst::ExtInstUClamp)
David Neto22f144c2017-06-12 14:26:21 -04005257 .Case("_Z5clampiii", glsl::ExtInst::ExtInstSClamp)
5258 .Case("_Z5clampDv2_iS_S_", glsl::ExtInst::ExtInstSClamp)
5259 .Case("_Z5clampDv3_iS_S_", glsl::ExtInst::ExtInstSClamp)
5260 .Case("_Z5clampDv4_iS_S_", glsl::ExtInst::ExtInstSClamp)
5261 .Case("_Z5clampjjj", glsl::ExtInst::ExtInstUClamp)
5262 .Case("_Z5clampDv2_jS_S_", glsl::ExtInst::ExtInstUClamp)
5263 .Case("_Z5clampDv3_jS_S_", glsl::ExtInst::ExtInstUClamp)
5264 .Case("_Z5clampDv4_jS_S_", glsl::ExtInst::ExtInstUClamp)
Kévin Petit495255d2019-03-06 13:56:48 +00005265 .Case("_Z5clamplll", glsl::ExtInst::ExtInstSClamp)
5266 .Case("_Z5clampDv2_lS_S_", glsl::ExtInst::ExtInstSClamp)
5267 .Case("_Z5clampDv3_lS_S_", glsl::ExtInst::ExtInstSClamp)
5268 .Case("_Z5clampDv4_lS_S_", glsl::ExtInst::ExtInstSClamp)
5269 .Case("_Z5clampmmm", glsl::ExtInst::ExtInstUClamp)
5270 .Case("_Z5clampDv2_mS_S_", glsl::ExtInst::ExtInstUClamp)
5271 .Case("_Z5clampDv3_mS_S_", glsl::ExtInst::ExtInstUClamp)
5272 .Case("_Z5clampDv4_mS_S_", glsl::ExtInst::ExtInstUClamp)
David Neto22f144c2017-06-12 14:26:21 -04005273 .Case("_Z5clampfff", glsl::ExtInst::ExtInstFClamp)
5274 .Case("_Z5clampDv2_fS_S_", glsl::ExtInst::ExtInstFClamp)
5275 .Case("_Z5clampDv3_fS_S_", glsl::ExtInst::ExtInstFClamp)
5276 .Case("_Z5clampDv4_fS_S_", glsl::ExtInst::ExtInstFClamp)
alan-bakerb39c8262019-03-08 14:03:37 -05005277 .Case("_Z3maxcc", glsl::ExtInst::ExtInstSMax)
5278 .Case("_Z3maxDv2_cS_", glsl::ExtInst::ExtInstSMax)
5279 .Case("_Z3maxDv3_cS_", glsl::ExtInst::ExtInstSMax)
5280 .Case("_Z3maxDv4_cS_", glsl::ExtInst::ExtInstSMax)
5281 .Case("_Z3maxhh", glsl::ExtInst::ExtInstUMax)
5282 .Case("_Z3maxDv2_hS_", glsl::ExtInst::ExtInstUMax)
5283 .Case("_Z3maxDv3_hS_", glsl::ExtInst::ExtInstUMax)
5284 .Case("_Z3maxDv4_hS_", glsl::ExtInst::ExtInstUMax)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005285 .Case("_Z3maxss", glsl::ExtInst::ExtInstSMax)
5286 .Case("_Z3maxDv2_sS_", glsl::ExtInst::ExtInstSMax)
5287 .Case("_Z3maxDv3_sS_", glsl::ExtInst::ExtInstSMax)
5288 .Case("_Z3maxDv4_sS_", glsl::ExtInst::ExtInstSMax)
5289 .Case("_Z3maxtt", glsl::ExtInst::ExtInstUMax)
5290 .Case("_Z3maxDv2_tS_", glsl::ExtInst::ExtInstUMax)
5291 .Case("_Z3maxDv3_tS_", glsl::ExtInst::ExtInstUMax)
5292 .Case("_Z3maxDv4_tS_", glsl::ExtInst::ExtInstUMax)
David Neto22f144c2017-06-12 14:26:21 -04005293 .Case("_Z3maxii", glsl::ExtInst::ExtInstSMax)
5294 .Case("_Z3maxDv2_iS_", glsl::ExtInst::ExtInstSMax)
5295 .Case("_Z3maxDv3_iS_", glsl::ExtInst::ExtInstSMax)
5296 .Case("_Z3maxDv4_iS_", glsl::ExtInst::ExtInstSMax)
5297 .Case("_Z3maxjj", glsl::ExtInst::ExtInstUMax)
5298 .Case("_Z3maxDv2_jS_", glsl::ExtInst::ExtInstUMax)
5299 .Case("_Z3maxDv3_jS_", glsl::ExtInst::ExtInstUMax)
5300 .Case("_Z3maxDv4_jS_", glsl::ExtInst::ExtInstUMax)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005301 .Case("_Z3maxll", glsl::ExtInst::ExtInstSMax)
5302 .Case("_Z3maxDv2_lS_", glsl::ExtInst::ExtInstSMax)
5303 .Case("_Z3maxDv3_lS_", glsl::ExtInst::ExtInstSMax)
5304 .Case("_Z3maxDv4_lS_", glsl::ExtInst::ExtInstSMax)
5305 .Case("_Z3maxmm", glsl::ExtInst::ExtInstUMax)
5306 .Case("_Z3maxDv2_mS_", glsl::ExtInst::ExtInstUMax)
5307 .Case("_Z3maxDv3_mS_", glsl::ExtInst::ExtInstUMax)
5308 .Case("_Z3maxDv4_mS_", glsl::ExtInst::ExtInstUMax)
David Neto22f144c2017-06-12 14:26:21 -04005309 .Case("_Z3maxff", glsl::ExtInst::ExtInstFMax)
5310 .Case("_Z3maxDv2_fS_", glsl::ExtInst::ExtInstFMax)
5311 .Case("_Z3maxDv3_fS_", glsl::ExtInst::ExtInstFMax)
5312 .Case("_Z3maxDv4_fS_", glsl::ExtInst::ExtInstFMax)
5313 .StartsWith("_Z4fmax", glsl::ExtInst::ExtInstFMax)
alan-bakerb39c8262019-03-08 14:03:37 -05005314 .Case("_Z3mincc", glsl::ExtInst::ExtInstSMin)
5315 .Case("_Z3minDv2_cS_", glsl::ExtInst::ExtInstSMin)
5316 .Case("_Z3minDv3_cS_", glsl::ExtInst::ExtInstSMin)
5317 .Case("_Z3minDv4_cS_", glsl::ExtInst::ExtInstSMin)
5318 .Case("_Z3minhh", glsl::ExtInst::ExtInstUMin)
5319 .Case("_Z3minDv2_hS_", glsl::ExtInst::ExtInstUMin)
5320 .Case("_Z3minDv3_hS_", glsl::ExtInst::ExtInstUMin)
5321 .Case("_Z3minDv4_hS_", glsl::ExtInst::ExtInstUMin)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005322 .Case("_Z3minss", glsl::ExtInst::ExtInstSMin)
5323 .Case("_Z3minDv2_sS_", glsl::ExtInst::ExtInstSMin)
5324 .Case("_Z3minDv3_sS_", glsl::ExtInst::ExtInstSMin)
5325 .Case("_Z3minDv4_sS_", glsl::ExtInst::ExtInstSMin)
5326 .Case("_Z3mintt", glsl::ExtInst::ExtInstUMin)
5327 .Case("_Z3minDv2_tS_", glsl::ExtInst::ExtInstUMin)
5328 .Case("_Z3minDv3_tS_", glsl::ExtInst::ExtInstUMin)
5329 .Case("_Z3minDv4_tS_", glsl::ExtInst::ExtInstUMin)
David Neto22f144c2017-06-12 14:26:21 -04005330 .Case("_Z3minii", glsl::ExtInst::ExtInstSMin)
5331 .Case("_Z3minDv2_iS_", glsl::ExtInst::ExtInstSMin)
5332 .Case("_Z3minDv3_iS_", glsl::ExtInst::ExtInstSMin)
5333 .Case("_Z3minDv4_iS_", glsl::ExtInst::ExtInstSMin)
5334 .Case("_Z3minjj", glsl::ExtInst::ExtInstUMin)
5335 .Case("_Z3minDv2_jS_", glsl::ExtInst::ExtInstUMin)
5336 .Case("_Z3minDv3_jS_", glsl::ExtInst::ExtInstUMin)
5337 .Case("_Z3minDv4_jS_", glsl::ExtInst::ExtInstUMin)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005338 .Case("_Z3minll", glsl::ExtInst::ExtInstSMin)
5339 .Case("_Z3minDv2_lS_", glsl::ExtInst::ExtInstSMin)
5340 .Case("_Z3minDv3_lS_", glsl::ExtInst::ExtInstSMin)
5341 .Case("_Z3minDv4_lS_", glsl::ExtInst::ExtInstSMin)
5342 .Case("_Z3minmm", glsl::ExtInst::ExtInstUMin)
5343 .Case("_Z3minDv2_mS_", glsl::ExtInst::ExtInstUMin)
5344 .Case("_Z3minDv3_mS_", glsl::ExtInst::ExtInstUMin)
5345 .Case("_Z3minDv4_mS_", glsl::ExtInst::ExtInstUMin)
David Neto22f144c2017-06-12 14:26:21 -04005346 .Case("_Z3minff", glsl::ExtInst::ExtInstFMin)
5347 .Case("_Z3minDv2_fS_", glsl::ExtInst::ExtInstFMin)
5348 .Case("_Z3minDv3_fS_", glsl::ExtInst::ExtInstFMin)
5349 .Case("_Z3minDv4_fS_", glsl::ExtInst::ExtInstFMin)
5350 .StartsWith("_Z4fmin", glsl::ExtInst::ExtInstFMin)
5351 .StartsWith("_Z7degrees", glsl::ExtInst::ExtInstDegrees)
5352 .StartsWith("_Z7radians", glsl::ExtInst::ExtInstRadians)
5353 .StartsWith("_Z3mix", glsl::ExtInst::ExtInstFMix)
5354 .StartsWith("_Z4acos", glsl::ExtInst::ExtInstAcos)
5355 .StartsWith("_Z5acosh", glsl::ExtInst::ExtInstAcosh)
5356 .StartsWith("_Z4asin", glsl::ExtInst::ExtInstAsin)
5357 .StartsWith("_Z5asinh", glsl::ExtInst::ExtInstAsinh)
5358 .StartsWith("_Z4atan", glsl::ExtInst::ExtInstAtan)
5359 .StartsWith("_Z5atan2", glsl::ExtInst::ExtInstAtan2)
5360 .StartsWith("_Z5atanh", glsl::ExtInst::ExtInstAtanh)
5361 .StartsWith("_Z4ceil", glsl::ExtInst::ExtInstCeil)
5362 .StartsWith("_Z3sin", glsl::ExtInst::ExtInstSin)
5363 .StartsWith("_Z4sinh", glsl::ExtInst::ExtInstSinh)
5364 .StartsWith("_Z8half_sin", glsl::ExtInst::ExtInstSin)
5365 .StartsWith("_Z10native_sin", glsl::ExtInst::ExtInstSin)
5366 .StartsWith("_Z3cos", glsl::ExtInst::ExtInstCos)
5367 .StartsWith("_Z4cosh", glsl::ExtInst::ExtInstCosh)
5368 .StartsWith("_Z8half_cos", glsl::ExtInst::ExtInstCos)
5369 .StartsWith("_Z10native_cos", glsl::ExtInst::ExtInstCos)
5370 .StartsWith("_Z3tan", glsl::ExtInst::ExtInstTan)
5371 .StartsWith("_Z4tanh", glsl::ExtInst::ExtInstTanh)
5372 .StartsWith("_Z8half_tan", glsl::ExtInst::ExtInstTan)
5373 .StartsWith("_Z10native_tan", glsl::ExtInst::ExtInstTan)
5374 .StartsWith("_Z3exp", glsl::ExtInst::ExtInstExp)
5375 .StartsWith("_Z8half_exp", glsl::ExtInst::ExtInstExp)
5376 .StartsWith("_Z10native_exp", glsl::ExtInst::ExtInstExp)
5377 .StartsWith("_Z4exp2", glsl::ExtInst::ExtInstExp2)
5378 .StartsWith("_Z9half_exp2", glsl::ExtInst::ExtInstExp2)
5379 .StartsWith("_Z11native_exp2", glsl::ExtInst::ExtInstExp2)
5380 .StartsWith("_Z3log", glsl::ExtInst::ExtInstLog)
5381 .StartsWith("_Z8half_log", glsl::ExtInst::ExtInstLog)
5382 .StartsWith("_Z10native_log", glsl::ExtInst::ExtInstLog)
5383 .StartsWith("_Z4log2", glsl::ExtInst::ExtInstLog2)
5384 .StartsWith("_Z9half_log2", glsl::ExtInst::ExtInstLog2)
5385 .StartsWith("_Z11native_log2", glsl::ExtInst::ExtInstLog2)
5386 .StartsWith("_Z4fabs", glsl::ExtInst::ExtInstFAbs)
kpet3458e942018-10-03 14:35:21 +01005387 .StartsWith("_Z3fma", glsl::ExtInst::ExtInstFma)
David Neto22f144c2017-06-12 14:26:21 -04005388 .StartsWith("_Z5floor", glsl::ExtInst::ExtInstFloor)
5389 .StartsWith("_Z5ldexp", glsl::ExtInst::ExtInstLdexp)
5390 .StartsWith("_Z3pow", glsl::ExtInst::ExtInstPow)
5391 .StartsWith("_Z4powr", glsl::ExtInst::ExtInstPow)
5392 .StartsWith("_Z9half_powr", glsl::ExtInst::ExtInstPow)
5393 .StartsWith("_Z11native_powr", glsl::ExtInst::ExtInstPow)
5394 .StartsWith("_Z5round", glsl::ExtInst::ExtInstRound)
5395 .StartsWith("_Z4sqrt", glsl::ExtInst::ExtInstSqrt)
5396 .StartsWith("_Z9half_sqrt", glsl::ExtInst::ExtInstSqrt)
5397 .StartsWith("_Z11native_sqrt", glsl::ExtInst::ExtInstSqrt)
5398 .StartsWith("_Z5rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5399 .StartsWith("_Z10half_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5400 .StartsWith("_Z12native_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5401 .StartsWith("_Z5trunc", glsl::ExtInst::ExtInstTrunc)
5402 .StartsWith("_Z5frexp", glsl::ExtInst::ExtInstFrexp)
5403 .StartsWith("_Z4sign", glsl::ExtInst::ExtInstFSign)
5404 .StartsWith("_Z6length", glsl::ExtInst::ExtInstLength)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005405 .StartsWith("_Z11fast_length", glsl::ExtInst::ExtInstLength)
David Neto22f144c2017-06-12 14:26:21 -04005406 .StartsWith("_Z8distance", glsl::ExtInst::ExtInstDistance)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005407 .StartsWith("_Z13fast_distance", glsl::ExtInst::ExtInstDistance)
David Netoe9a03512017-10-16 10:08:27 -04005408 .StartsWith("_Z4step", glsl::ExtInst::ExtInstStep)
kpet6fd2a262018-10-03 14:48:01 +01005409 .StartsWith("_Z10smoothstep", glsl::ExtInst::ExtInstSmoothStep)
David Neto22f144c2017-06-12 14:26:21 -04005410 .Case("_Z5crossDv3_fS_", glsl::ExtInst::ExtInstCross)
5411 .StartsWith("_Z9normalize", glsl::ExtInst::ExtInstNormalize)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005412 .StartsWith("_Z14fast_normalize", glsl::ExtInst::ExtInstNormalize)
David Neto22f144c2017-06-12 14:26:21 -04005413 .StartsWith("llvm.fmuladd.", glsl::ExtInst::ExtInstFma)
5414 .Case("spirv.unpack.v2f16", glsl::ExtInst::ExtInstUnpackHalf2x16)
5415 .Case("spirv.pack.v2f16", glsl::ExtInst::ExtInstPackHalf2x16)
David Neto62653202017-10-16 19:05:18 -04005416 .Case("clspv.fract.f", glsl::ExtInst::ExtInstFract)
5417 .Case("clspv.fract.v2f", glsl::ExtInst::ExtInstFract)
5418 .Case("clspv.fract.v3f", glsl::ExtInst::ExtInstFract)
5419 .Case("clspv.fract.v4f", glsl::ExtInst::ExtInstFract)
David Neto3fbb4072017-10-16 11:28:14 -04005420 .Default(kGlslExtInstBad);
5421}
5422
5423glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(StringRef Name) {
5424 // Check indirect cases.
5425 return StringSwitch<glsl::ExtInst>(Name)
5426 .StartsWith("_Z3clz", glsl::ExtInst::ExtInstFindUMsb)
5427 // Use exact match on float arg because these need a multiply
5428 // of a constant of the right floating point type.
5429 .Case("_Z6acospif", glsl::ExtInst::ExtInstAcos)
5430 .Case("_Z6acospiDv2_f", glsl::ExtInst::ExtInstAcos)
5431 .Case("_Z6acospiDv3_f", glsl::ExtInst::ExtInstAcos)
5432 .Case("_Z6acospiDv4_f", glsl::ExtInst::ExtInstAcos)
5433 .Case("_Z6asinpif", glsl::ExtInst::ExtInstAsin)
5434 .Case("_Z6asinpiDv2_f", glsl::ExtInst::ExtInstAsin)
5435 .Case("_Z6asinpiDv3_f", glsl::ExtInst::ExtInstAsin)
5436 .Case("_Z6asinpiDv4_f", glsl::ExtInst::ExtInstAsin)
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005437 .Case("_Z6atanpif", glsl::ExtInst::ExtInstAtan)
5438 .Case("_Z6atanpiDv2_f", glsl::ExtInst::ExtInstAtan)
5439 .Case("_Z6atanpiDv3_f", glsl::ExtInst::ExtInstAtan)
5440 .Case("_Z6atanpiDv4_f", glsl::ExtInst::ExtInstAtan)
David Neto3fbb4072017-10-16 11:28:14 -04005441 .Case("_Z7atan2piff", glsl::ExtInst::ExtInstAtan2)
5442 .Case("_Z7atan2piDv2_fS_", glsl::ExtInst::ExtInstAtan2)
5443 .Case("_Z7atan2piDv3_fS_", glsl::ExtInst::ExtInstAtan2)
5444 .Case("_Z7atan2piDv4_fS_", glsl::ExtInst::ExtInstAtan2)
5445 .Default(kGlslExtInstBad);
5446}
5447
alan-bakerb6b09dc2018-11-08 16:59:28 -05005448glsl::ExtInst
5449SPIRVProducerPass::getDirectOrIndirectExtInstEnum(StringRef Name) {
David Neto3fbb4072017-10-16 11:28:14 -04005450 auto direct = getExtInstEnum(Name);
5451 if (direct != kGlslExtInstBad)
5452 return direct;
5453 return getIndirectExtInstEnum(Name);
David Neto22f144c2017-06-12 14:26:21 -04005454}
5455
5456void SPIRVProducerPass::PrintResID(SPIRVInstruction *Inst) {
5457 out << "%" << Inst->getResultID();
5458}
5459
5460void SPIRVProducerPass::PrintOpcode(SPIRVInstruction *Inst) {
5461 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5462 out << "\t" << spv::getOpName(Opcode);
5463}
5464
5465void SPIRVProducerPass::PrintOperand(SPIRVOperand *Op) {
5466 SPIRVOperandType OpTy = Op->getType();
5467 switch (OpTy) {
5468 default: {
5469 llvm_unreachable("Unsupported SPIRV Operand Type???");
5470 break;
5471 }
5472 case SPIRVOperandType::NUMBERID: {
5473 out << "%" << Op->getNumID();
5474 break;
5475 }
5476 case SPIRVOperandType::LITERAL_STRING: {
5477 out << "\"" << Op->getLiteralStr() << "\"";
5478 break;
5479 }
5480 case SPIRVOperandType::LITERAL_INTEGER: {
5481 // TODO: Handle LiteralNum carefully.
Kévin Petite7d0cce2018-10-31 12:38:56 +00005482 auto Words = Op->getLiteralNum();
5483 auto NumWords = Words.size();
5484
5485 if (NumWords == 1) {
5486 out << Words[0];
5487 } else if (NumWords == 2) {
5488 uint64_t Val = (static_cast<uint64_t>(Words[1]) << 32) | Words[0];
5489 out << Val;
5490 } else {
5491 llvm_unreachable("Handle printing arbitrary precision integer literals.");
David Neto22f144c2017-06-12 14:26:21 -04005492 }
5493 break;
5494 }
5495 case SPIRVOperandType::LITERAL_FLOAT: {
5496 // TODO: Handle LiteralNum carefully.
5497 for (auto Word : Op->getLiteralNum()) {
5498 APFloat APF = APFloat(APFloat::IEEEsingle(), APInt(32, Word));
5499 SmallString<8> Str;
5500 APF.toString(Str, 6, 2);
5501 out << Str;
5502 }
5503 break;
5504 }
5505 }
5506}
5507
5508void SPIRVProducerPass::PrintCapability(SPIRVOperand *Op) {
5509 spv::Capability Cap = static_cast<spv::Capability>(Op->getNumID());
5510 out << spv::getCapabilityName(Cap);
5511}
5512
5513void SPIRVProducerPass::PrintExtInst(SPIRVOperand *Op) {
5514 auto LiteralNum = Op->getLiteralNum();
5515 glsl::ExtInst Ext = static_cast<glsl::ExtInst>(LiteralNum[0]);
5516 out << glsl::getExtInstName(Ext);
5517}
5518
5519void SPIRVProducerPass::PrintAddrModel(SPIRVOperand *Op) {
5520 spv::AddressingModel AddrModel =
5521 static_cast<spv::AddressingModel>(Op->getNumID());
5522 out << spv::getAddressingModelName(AddrModel);
5523}
5524
5525void SPIRVProducerPass::PrintMemModel(SPIRVOperand *Op) {
5526 spv::MemoryModel MemModel = static_cast<spv::MemoryModel>(Op->getNumID());
5527 out << spv::getMemoryModelName(MemModel);
5528}
5529
5530void SPIRVProducerPass::PrintExecModel(SPIRVOperand *Op) {
5531 spv::ExecutionModel ExecModel =
5532 static_cast<spv::ExecutionModel>(Op->getNumID());
5533 out << spv::getExecutionModelName(ExecModel);
5534}
5535
5536void SPIRVProducerPass::PrintExecMode(SPIRVOperand *Op) {
5537 spv::ExecutionMode ExecMode = static_cast<spv::ExecutionMode>(Op->getNumID());
5538 out << spv::getExecutionModeName(ExecMode);
5539}
5540
5541void SPIRVProducerPass::PrintSourceLanguage(SPIRVOperand *Op) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005542 spv::SourceLanguage SourceLang =
5543 static_cast<spv::SourceLanguage>(Op->getNumID());
David Neto22f144c2017-06-12 14:26:21 -04005544 out << spv::getSourceLanguageName(SourceLang);
5545}
5546
5547void SPIRVProducerPass::PrintFuncCtrl(SPIRVOperand *Op) {
5548 spv::FunctionControlMask FuncCtrl =
5549 static_cast<spv::FunctionControlMask>(Op->getNumID());
5550 out << spv::getFunctionControlName(FuncCtrl);
5551}
5552
5553void SPIRVProducerPass::PrintStorageClass(SPIRVOperand *Op) {
5554 spv::StorageClass StClass = static_cast<spv::StorageClass>(Op->getNumID());
5555 out << getStorageClassName(StClass);
5556}
5557
5558void SPIRVProducerPass::PrintDecoration(SPIRVOperand *Op) {
5559 spv::Decoration Deco = static_cast<spv::Decoration>(Op->getNumID());
5560 out << getDecorationName(Deco);
5561}
5562
5563void SPIRVProducerPass::PrintBuiltIn(SPIRVOperand *Op) {
5564 spv::BuiltIn BIn = static_cast<spv::BuiltIn>(Op->getNumID());
5565 out << getBuiltInName(BIn);
5566}
5567
5568void SPIRVProducerPass::PrintSelectionControl(SPIRVOperand *Op) {
5569 spv::SelectionControlMask BIn =
5570 static_cast<spv::SelectionControlMask>(Op->getNumID());
5571 out << getSelectionControlName(BIn);
5572}
5573
5574void SPIRVProducerPass::PrintLoopControl(SPIRVOperand *Op) {
5575 spv::LoopControlMask BIn = static_cast<spv::LoopControlMask>(Op->getNumID());
5576 out << getLoopControlName(BIn);
5577}
5578
5579void SPIRVProducerPass::PrintDimensionality(SPIRVOperand *Op) {
5580 spv::Dim DIM = static_cast<spv::Dim>(Op->getNumID());
5581 out << getDimName(DIM);
5582}
5583
5584void SPIRVProducerPass::PrintImageFormat(SPIRVOperand *Op) {
5585 spv::ImageFormat Format = static_cast<spv::ImageFormat>(Op->getNumID());
5586 out << getImageFormatName(Format);
5587}
5588
5589void SPIRVProducerPass::PrintMemoryAccess(SPIRVOperand *Op) {
5590 out << spv::getMemoryAccessName(
5591 static_cast<spv::MemoryAccessMask>(Op->getNumID()));
5592}
5593
5594void SPIRVProducerPass::PrintImageOperandsType(SPIRVOperand *Op) {
5595 auto LiteralNum = Op->getLiteralNum();
5596 spv::ImageOperandsMask Type =
5597 static_cast<spv::ImageOperandsMask>(LiteralNum[0]);
5598 out << getImageOperandsName(Type);
5599}
5600
5601void SPIRVProducerPass::WriteSPIRVAssembly() {
5602 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5603
5604 for (auto Inst : SPIRVInstList) {
5605 SPIRVOperandList Ops = Inst->getOperands();
5606 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5607
5608 switch (Opcode) {
5609 default: {
5610 llvm_unreachable("Unsupported SPIRV instruction");
5611 break;
5612 }
5613 case spv::OpCapability: {
5614 // Ops[0] = Capability
5615 PrintOpcode(Inst);
5616 out << " ";
5617 PrintCapability(Ops[0]);
5618 out << "\n";
5619 break;
5620 }
5621 case spv::OpMemoryModel: {
5622 // Ops[0] = Addressing Model
5623 // Ops[1] = Memory Model
5624 PrintOpcode(Inst);
5625 out << " ";
5626 PrintAddrModel(Ops[0]);
5627 out << " ";
5628 PrintMemModel(Ops[1]);
5629 out << "\n";
5630 break;
5631 }
5632 case spv::OpEntryPoint: {
5633 // Ops[0] = Execution Model
5634 // Ops[1] = EntryPoint ID
5635 // Ops[2] = Name (Literal String)
5636 // Ops[3] ... Ops[n] = Interface ID
5637 PrintOpcode(Inst);
5638 out << " ";
5639 PrintExecModel(Ops[0]);
5640 for (uint32_t i = 1; i < Ops.size(); i++) {
5641 out << " ";
5642 PrintOperand(Ops[i]);
5643 }
5644 out << "\n";
5645 break;
5646 }
5647 case spv::OpExecutionMode: {
5648 // Ops[0] = Entry Point ID
5649 // Ops[1] = Execution Mode
5650 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
5651 PrintOpcode(Inst);
5652 out << " ";
5653 PrintOperand(Ops[0]);
5654 out << " ";
5655 PrintExecMode(Ops[1]);
5656 for (uint32_t i = 2; i < Ops.size(); i++) {
5657 out << " ";
5658 PrintOperand(Ops[i]);
5659 }
5660 out << "\n";
5661 break;
5662 }
5663 case spv::OpSource: {
5664 // Ops[0] = SourceLanguage ID
5665 // Ops[1] = Version (LiteralNum)
5666 PrintOpcode(Inst);
5667 out << " ";
5668 PrintSourceLanguage(Ops[0]);
5669 out << " ";
5670 PrintOperand(Ops[1]);
5671 out << "\n";
5672 break;
5673 }
5674 case spv::OpDecorate: {
5675 // Ops[0] = Target ID
5676 // Ops[1] = Decoration (Block or BufferBlock)
5677 // Ops[2] ... Ops[n] = Optional literals according to Decoration
5678 PrintOpcode(Inst);
5679 out << " ";
5680 PrintOperand(Ops[0]);
5681 out << " ";
5682 PrintDecoration(Ops[1]);
5683 // Handle BuiltIn OpDecorate specially.
5684 if (Ops[1]->getNumID() == spv::DecorationBuiltIn) {
5685 out << " ";
5686 PrintBuiltIn(Ops[2]);
5687 } else {
5688 for (uint32_t i = 2; i < Ops.size(); i++) {
5689 out << " ";
5690 PrintOperand(Ops[i]);
5691 }
5692 }
5693 out << "\n";
5694 break;
5695 }
5696 case spv::OpMemberDecorate: {
5697 // Ops[0] = Structure Type ID
5698 // Ops[1] = Member Index(Literal Number)
5699 // Ops[2] = Decoration
5700 // Ops[3] ... Ops[n] = Optional literals according to Decoration
5701 PrintOpcode(Inst);
5702 out << " ";
5703 PrintOperand(Ops[0]);
5704 out << " ";
5705 PrintOperand(Ops[1]);
5706 out << " ";
5707 PrintDecoration(Ops[2]);
5708 for (uint32_t i = 3; i < Ops.size(); i++) {
5709 out << " ";
5710 PrintOperand(Ops[i]);
5711 }
5712 out << "\n";
5713 break;
5714 }
5715 case spv::OpTypePointer: {
5716 // Ops[0] = Storage Class
5717 // Ops[1] = Element Type ID
5718 PrintResID(Inst);
5719 out << " = ";
5720 PrintOpcode(Inst);
5721 out << " ";
5722 PrintStorageClass(Ops[0]);
5723 out << " ";
5724 PrintOperand(Ops[1]);
5725 out << "\n";
5726 break;
5727 }
5728 case spv::OpTypeImage: {
5729 // Ops[0] = Sampled Type ID
5730 // Ops[1] = Dim ID
5731 // Ops[2] = Depth (Literal Number)
5732 // Ops[3] = Arrayed (Literal Number)
5733 // Ops[4] = MS (Literal Number)
5734 // Ops[5] = Sampled (Literal Number)
5735 // Ops[6] = Image Format ID
5736 PrintResID(Inst);
5737 out << " = ";
5738 PrintOpcode(Inst);
5739 out << " ";
5740 PrintOperand(Ops[0]);
5741 out << " ";
5742 PrintDimensionality(Ops[1]);
5743 out << " ";
5744 PrintOperand(Ops[2]);
5745 out << " ";
5746 PrintOperand(Ops[3]);
5747 out << " ";
5748 PrintOperand(Ops[4]);
5749 out << " ";
5750 PrintOperand(Ops[5]);
5751 out << " ";
5752 PrintImageFormat(Ops[6]);
5753 out << "\n";
5754 break;
5755 }
5756 case spv::OpFunction: {
5757 // Ops[0] : Result Type ID
5758 // Ops[1] : Function Control
5759 // Ops[2] : Function Type ID
5760 PrintResID(Inst);
5761 out << " = ";
5762 PrintOpcode(Inst);
5763 out << " ";
5764 PrintOperand(Ops[0]);
5765 out << " ";
5766 PrintFuncCtrl(Ops[1]);
5767 out << " ";
5768 PrintOperand(Ops[2]);
5769 out << "\n";
5770 break;
5771 }
5772 case spv::OpSelectionMerge: {
5773 // Ops[0] = Merge Block ID
5774 // Ops[1] = Selection Control
5775 PrintOpcode(Inst);
5776 out << " ";
5777 PrintOperand(Ops[0]);
5778 out << " ";
5779 PrintSelectionControl(Ops[1]);
5780 out << "\n";
5781 break;
5782 }
5783 case spv::OpLoopMerge: {
5784 // Ops[0] = Merge Block ID
5785 // Ops[1] = Continue Target ID
5786 // Ops[2] = Selection Control
5787 PrintOpcode(Inst);
5788 out << " ";
5789 PrintOperand(Ops[0]);
5790 out << " ";
5791 PrintOperand(Ops[1]);
5792 out << " ";
5793 PrintLoopControl(Ops[2]);
5794 out << "\n";
5795 break;
5796 }
5797 case spv::OpImageSampleExplicitLod: {
5798 // Ops[0] = Result Type ID
5799 // Ops[1] = Sampled Image ID
5800 // Ops[2] = Coordinate ID
5801 // Ops[3] = Image Operands Type ID
5802 // Ops[4] ... Ops[n] = Operands ID
5803 PrintResID(Inst);
5804 out << " = ";
5805 PrintOpcode(Inst);
5806 for (uint32_t i = 0; i < 3; i++) {
5807 out << " ";
5808 PrintOperand(Ops[i]);
5809 }
5810 out << " ";
5811 PrintImageOperandsType(Ops[3]);
5812 for (uint32_t i = 4; i < Ops.size(); i++) {
5813 out << " ";
5814 PrintOperand(Ops[i]);
5815 }
5816 out << "\n";
5817 break;
5818 }
5819 case spv::OpVariable: {
5820 // Ops[0] : Result Type ID
5821 // Ops[1] : Storage Class
5822 // Ops[2] ... Ops[n] = Initializer IDs
5823 PrintResID(Inst);
5824 out << " = ";
5825 PrintOpcode(Inst);
5826 out << " ";
5827 PrintOperand(Ops[0]);
5828 out << " ";
5829 PrintStorageClass(Ops[1]);
5830 for (uint32_t i = 2; i < Ops.size(); i++) {
5831 out << " ";
5832 PrintOperand(Ops[i]);
5833 }
5834 out << "\n";
5835 break;
5836 }
5837 case spv::OpExtInst: {
5838 // Ops[0] = Result Type ID
5839 // Ops[1] = Set ID (OpExtInstImport ID)
5840 // Ops[2] = Instruction Number (Literal Number)
5841 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5842 PrintResID(Inst);
5843 out << " = ";
5844 PrintOpcode(Inst);
5845 out << " ";
5846 PrintOperand(Ops[0]);
5847 out << " ";
5848 PrintOperand(Ops[1]);
5849 out << " ";
5850 PrintExtInst(Ops[2]);
5851 for (uint32_t i = 3; i < Ops.size(); i++) {
5852 out << " ";
5853 PrintOperand(Ops[i]);
5854 }
5855 out << "\n";
5856 break;
5857 }
5858 case spv::OpCopyMemory: {
5859 // Ops[0] = Addressing Model
5860 // Ops[1] = Memory Model
5861 PrintOpcode(Inst);
5862 out << " ";
5863 PrintOperand(Ops[0]);
5864 out << " ";
5865 PrintOperand(Ops[1]);
5866 out << " ";
5867 PrintMemoryAccess(Ops[2]);
5868 out << " ";
5869 PrintOperand(Ops[3]);
5870 out << "\n";
5871 break;
5872 }
5873 case spv::OpExtension:
5874 case spv::OpControlBarrier:
5875 case spv::OpMemoryBarrier:
5876 case spv::OpBranch:
5877 case spv::OpBranchConditional:
5878 case spv::OpStore:
5879 case spv::OpImageWrite:
5880 case spv::OpReturnValue:
5881 case spv::OpReturn:
5882 case spv::OpFunctionEnd: {
5883 PrintOpcode(Inst);
5884 for (uint32_t i = 0; i < Ops.size(); i++) {
5885 out << " ";
5886 PrintOperand(Ops[i]);
5887 }
5888 out << "\n";
5889 break;
5890 }
5891 case spv::OpExtInstImport:
5892 case spv::OpTypeRuntimeArray:
5893 case spv::OpTypeStruct:
5894 case spv::OpTypeSampler:
5895 case spv::OpTypeSampledImage:
5896 case spv::OpTypeInt:
5897 case spv::OpTypeFloat:
5898 case spv::OpTypeArray:
5899 case spv::OpTypeVector:
5900 case spv::OpTypeBool:
5901 case spv::OpTypeVoid:
5902 case spv::OpTypeFunction:
5903 case spv::OpFunctionParameter:
5904 case spv::OpLabel:
5905 case spv::OpPhi:
5906 case spv::OpLoad:
5907 case spv::OpSelect:
5908 case spv::OpAccessChain:
5909 case spv::OpPtrAccessChain:
5910 case spv::OpInBoundsAccessChain:
5911 case spv::OpUConvert:
5912 case spv::OpSConvert:
5913 case spv::OpConvertFToU:
5914 case spv::OpConvertFToS:
5915 case spv::OpConvertUToF:
5916 case spv::OpConvertSToF:
5917 case spv::OpFConvert:
5918 case spv::OpConvertPtrToU:
5919 case spv::OpConvertUToPtr:
5920 case spv::OpBitcast:
5921 case spv::OpIAdd:
5922 case spv::OpFAdd:
5923 case spv::OpISub:
5924 case spv::OpFSub:
5925 case spv::OpIMul:
5926 case spv::OpFMul:
5927 case spv::OpUDiv:
5928 case spv::OpSDiv:
5929 case spv::OpFDiv:
5930 case spv::OpUMod:
5931 case spv::OpSRem:
5932 case spv::OpFRem:
Kévin Petit8a560882019-03-21 15:24:34 +00005933 case spv::OpUMulExtended:
5934 case spv::OpSMulExtended:
David Neto22f144c2017-06-12 14:26:21 -04005935 case spv::OpBitwiseOr:
5936 case spv::OpBitwiseXor:
5937 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005938 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005939 case spv::OpShiftLeftLogical:
5940 case spv::OpShiftRightLogical:
5941 case spv::OpShiftRightArithmetic:
5942 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04005943 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04005944 case spv::OpCompositeExtract:
5945 case spv::OpVectorExtractDynamic:
5946 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04005947 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04005948 case spv::OpVectorInsertDynamic:
5949 case spv::OpVectorShuffle:
5950 case spv::OpIEqual:
5951 case spv::OpINotEqual:
5952 case spv::OpUGreaterThan:
5953 case spv::OpUGreaterThanEqual:
5954 case spv::OpULessThan:
5955 case spv::OpULessThanEqual:
5956 case spv::OpSGreaterThan:
5957 case spv::OpSGreaterThanEqual:
5958 case spv::OpSLessThan:
5959 case spv::OpSLessThanEqual:
5960 case spv::OpFOrdEqual:
5961 case spv::OpFOrdGreaterThan:
5962 case spv::OpFOrdGreaterThanEqual:
5963 case spv::OpFOrdLessThan:
5964 case spv::OpFOrdLessThanEqual:
5965 case spv::OpFOrdNotEqual:
5966 case spv::OpFUnordEqual:
5967 case spv::OpFUnordGreaterThan:
5968 case spv::OpFUnordGreaterThanEqual:
5969 case spv::OpFUnordLessThan:
5970 case spv::OpFUnordLessThanEqual:
5971 case spv::OpFUnordNotEqual:
5972 case spv::OpSampledImage:
5973 case spv::OpFunctionCall:
5974 case spv::OpConstantTrue:
5975 case spv::OpConstantFalse:
5976 case spv::OpConstant:
5977 case spv::OpSpecConstant:
5978 case spv::OpConstantComposite:
5979 case spv::OpSpecConstantComposite:
5980 case spv::OpConstantNull:
5981 case spv::OpLogicalOr:
5982 case spv::OpLogicalAnd:
5983 case spv::OpLogicalNot:
5984 case spv::OpLogicalNotEqual:
5985 case spv::OpUndef:
5986 case spv::OpIsInf:
5987 case spv::OpIsNan:
5988 case spv::OpAny:
5989 case spv::OpAll:
David Neto5c22a252018-03-15 16:07:41 -04005990 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04005991 case spv::OpAtomicIAdd:
5992 case spv::OpAtomicISub:
5993 case spv::OpAtomicExchange:
5994 case spv::OpAtomicIIncrement:
5995 case spv::OpAtomicIDecrement:
5996 case spv::OpAtomicCompareExchange:
5997 case spv::OpAtomicUMin:
5998 case spv::OpAtomicSMin:
5999 case spv::OpAtomicUMax:
6000 case spv::OpAtomicSMax:
6001 case spv::OpAtomicAnd:
6002 case spv::OpAtomicOr:
6003 case spv::OpAtomicXor:
6004 case spv::OpDot: {
6005 PrintResID(Inst);
6006 out << " = ";
6007 PrintOpcode(Inst);
6008 for (uint32_t i = 0; i < Ops.size(); i++) {
6009 out << " ";
6010 PrintOperand(Ops[i]);
6011 }
6012 out << "\n";
6013 break;
6014 }
6015 }
6016 }
6017}
6018
6019void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04006020 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04006021}
6022
6023void SPIRVProducerPass::WriteResultID(SPIRVInstruction *Inst) {
6024 WriteOneWord(Inst->getResultID());
6025}
6026
6027void SPIRVProducerPass::WriteWordCountAndOpcode(SPIRVInstruction *Inst) {
6028 // High 16 bit : Word Count
6029 // Low 16 bit : Opcode
6030 uint32_t Word = Inst->getOpcode();
David Netoee2660d2018-06-28 16:31:29 -04006031 const uint32_t count = Inst->getWordCount();
6032 if (count > 65535) {
6033 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
6034 llvm_unreachable("Word count too high");
6035 }
David Neto22f144c2017-06-12 14:26:21 -04006036 Word |= Inst->getWordCount() << 16;
6037 WriteOneWord(Word);
6038}
6039
6040void SPIRVProducerPass::WriteOperand(SPIRVOperand *Op) {
6041 SPIRVOperandType OpTy = Op->getType();
6042 switch (OpTy) {
6043 default: {
6044 llvm_unreachable("Unsupported SPIRV Operand Type???");
6045 break;
6046 }
6047 case SPIRVOperandType::NUMBERID: {
6048 WriteOneWord(Op->getNumID());
6049 break;
6050 }
6051 case SPIRVOperandType::LITERAL_STRING: {
6052 std::string Str = Op->getLiteralStr();
6053 const char *Data = Str.c_str();
6054 size_t WordSize = Str.size() / 4;
6055 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
6056 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
6057 }
6058
6059 uint32_t Remainder = Str.size() % 4;
6060 uint32_t LastWord = 0;
6061 if (Remainder) {
6062 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
6063 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
6064 }
6065 }
6066
6067 WriteOneWord(LastWord);
6068 break;
6069 }
6070 case SPIRVOperandType::LITERAL_INTEGER:
6071 case SPIRVOperandType::LITERAL_FLOAT: {
6072 auto LiteralNum = Op->getLiteralNum();
6073 // TODO: Handle LiteranNum carefully.
6074 for (auto Word : LiteralNum) {
6075 WriteOneWord(Word);
6076 }
6077 break;
6078 }
6079 }
6080}
6081
6082void SPIRVProducerPass::WriteSPIRVBinary() {
6083 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
6084
6085 for (auto Inst : SPIRVInstList) {
David Netoc6f3ab22018-04-06 18:02:31 -04006086 SPIRVOperandList Ops{Inst->getOperands()};
David Neto22f144c2017-06-12 14:26:21 -04006087 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
6088
6089 switch (Opcode) {
6090 default: {
David Neto5c22a252018-03-15 16:07:41 -04006091 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04006092 llvm_unreachable("Unsupported SPIRV instruction");
6093 break;
6094 }
6095 case spv::OpCapability:
6096 case spv::OpExtension:
6097 case spv::OpMemoryModel:
6098 case spv::OpEntryPoint:
6099 case spv::OpExecutionMode:
6100 case spv::OpSource:
6101 case spv::OpDecorate:
6102 case spv::OpMemberDecorate:
6103 case spv::OpBranch:
6104 case spv::OpBranchConditional:
6105 case spv::OpSelectionMerge:
6106 case spv::OpLoopMerge:
6107 case spv::OpStore:
6108 case spv::OpImageWrite:
6109 case spv::OpReturnValue:
6110 case spv::OpControlBarrier:
6111 case spv::OpMemoryBarrier:
6112 case spv::OpReturn:
6113 case spv::OpFunctionEnd:
6114 case spv::OpCopyMemory: {
6115 WriteWordCountAndOpcode(Inst);
6116 for (uint32_t i = 0; i < Ops.size(); i++) {
6117 WriteOperand(Ops[i]);
6118 }
6119 break;
6120 }
6121 case spv::OpTypeBool:
6122 case spv::OpTypeVoid:
6123 case spv::OpTypeSampler:
6124 case spv::OpLabel:
6125 case spv::OpExtInstImport:
6126 case spv::OpTypePointer:
6127 case spv::OpTypeRuntimeArray:
6128 case spv::OpTypeStruct:
6129 case spv::OpTypeImage:
6130 case spv::OpTypeSampledImage:
6131 case spv::OpTypeInt:
6132 case spv::OpTypeFloat:
6133 case spv::OpTypeArray:
6134 case spv::OpTypeVector:
6135 case spv::OpTypeFunction: {
6136 WriteWordCountAndOpcode(Inst);
6137 WriteResultID(Inst);
6138 for (uint32_t i = 0; i < Ops.size(); i++) {
6139 WriteOperand(Ops[i]);
6140 }
6141 break;
6142 }
6143 case spv::OpFunction:
6144 case spv::OpFunctionParameter:
6145 case spv::OpAccessChain:
6146 case spv::OpPtrAccessChain:
6147 case spv::OpInBoundsAccessChain:
6148 case spv::OpUConvert:
6149 case spv::OpSConvert:
6150 case spv::OpConvertFToU:
6151 case spv::OpConvertFToS:
6152 case spv::OpConvertUToF:
6153 case spv::OpConvertSToF:
6154 case spv::OpFConvert:
6155 case spv::OpConvertPtrToU:
6156 case spv::OpConvertUToPtr:
6157 case spv::OpBitcast:
6158 case spv::OpIAdd:
6159 case spv::OpFAdd:
6160 case spv::OpISub:
6161 case spv::OpFSub:
6162 case spv::OpIMul:
6163 case spv::OpFMul:
6164 case spv::OpUDiv:
6165 case spv::OpSDiv:
6166 case spv::OpFDiv:
6167 case spv::OpUMod:
6168 case spv::OpSRem:
6169 case spv::OpFRem:
Kévin Petit8a560882019-03-21 15:24:34 +00006170 case spv::OpUMulExtended:
6171 case spv::OpSMulExtended:
David Neto22f144c2017-06-12 14:26:21 -04006172 case spv::OpBitwiseOr:
6173 case spv::OpBitwiseXor:
6174 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04006175 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04006176 case spv::OpShiftLeftLogical:
6177 case spv::OpShiftRightLogical:
6178 case spv::OpShiftRightArithmetic:
6179 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04006180 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04006181 case spv::OpCompositeExtract:
6182 case spv::OpVectorExtractDynamic:
6183 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04006184 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04006185 case spv::OpVectorInsertDynamic:
6186 case spv::OpVectorShuffle:
6187 case spv::OpIEqual:
6188 case spv::OpINotEqual:
6189 case spv::OpUGreaterThan:
6190 case spv::OpUGreaterThanEqual:
6191 case spv::OpULessThan:
6192 case spv::OpULessThanEqual:
6193 case spv::OpSGreaterThan:
6194 case spv::OpSGreaterThanEqual:
6195 case spv::OpSLessThan:
6196 case spv::OpSLessThanEqual:
6197 case spv::OpFOrdEqual:
6198 case spv::OpFOrdGreaterThan:
6199 case spv::OpFOrdGreaterThanEqual:
6200 case spv::OpFOrdLessThan:
6201 case spv::OpFOrdLessThanEqual:
6202 case spv::OpFOrdNotEqual:
6203 case spv::OpFUnordEqual:
6204 case spv::OpFUnordGreaterThan:
6205 case spv::OpFUnordGreaterThanEqual:
6206 case spv::OpFUnordLessThan:
6207 case spv::OpFUnordLessThanEqual:
6208 case spv::OpFUnordNotEqual:
6209 case spv::OpExtInst:
6210 case spv::OpIsInf:
6211 case spv::OpIsNan:
6212 case spv::OpAny:
6213 case spv::OpAll:
6214 case spv::OpUndef:
6215 case spv::OpConstantNull:
6216 case spv::OpLogicalOr:
6217 case spv::OpLogicalAnd:
6218 case spv::OpLogicalNot:
6219 case spv::OpLogicalNotEqual:
6220 case spv::OpConstantComposite:
6221 case spv::OpSpecConstantComposite:
6222 case spv::OpConstantTrue:
6223 case spv::OpConstantFalse:
6224 case spv::OpConstant:
6225 case spv::OpSpecConstant:
6226 case spv::OpVariable:
6227 case spv::OpFunctionCall:
6228 case spv::OpSampledImage:
6229 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04006230 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04006231 case spv::OpSelect:
6232 case spv::OpPhi:
6233 case spv::OpLoad:
6234 case spv::OpAtomicIAdd:
6235 case spv::OpAtomicISub:
6236 case spv::OpAtomicExchange:
6237 case spv::OpAtomicIIncrement:
6238 case spv::OpAtomicIDecrement:
6239 case spv::OpAtomicCompareExchange:
6240 case spv::OpAtomicUMin:
6241 case spv::OpAtomicSMin:
6242 case spv::OpAtomicUMax:
6243 case spv::OpAtomicSMax:
6244 case spv::OpAtomicAnd:
6245 case spv::OpAtomicOr:
6246 case spv::OpAtomicXor:
6247 case spv::OpDot: {
6248 WriteWordCountAndOpcode(Inst);
6249 WriteOperand(Ops[0]);
6250 WriteResultID(Inst);
6251 for (uint32_t i = 1; i < Ops.size(); i++) {
6252 WriteOperand(Ops[i]);
6253 }
6254 break;
6255 }
6256 }
6257 }
6258}
Alan Baker9bf93fb2018-08-28 16:59:26 -04006259
alan-bakerb6b09dc2018-11-08 16:59:28 -05006260bool SPIRVProducerPass::IsTypeNullable(const Type *type) const {
Alan Baker9bf93fb2018-08-28 16:59:26 -04006261 switch (type->getTypeID()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05006262 case Type::HalfTyID:
6263 case Type::FloatTyID:
6264 case Type::DoubleTyID:
6265 case Type::IntegerTyID:
6266 case Type::VectorTyID:
6267 return true;
6268 case Type::PointerTyID: {
6269 const PointerType *pointer_type = cast<PointerType>(type);
6270 if (pointer_type->getPointerAddressSpace() !=
6271 AddressSpace::UniformConstant) {
6272 auto pointee_type = pointer_type->getPointerElementType();
6273 if (pointee_type->isStructTy() &&
6274 cast<StructType>(pointee_type)->isOpaque()) {
6275 // Images and samplers are not nullable.
6276 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04006277 }
Alan Baker9bf93fb2018-08-28 16:59:26 -04006278 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05006279 return true;
6280 }
6281 case Type::ArrayTyID:
6282 return IsTypeNullable(cast<CompositeType>(type)->getTypeAtIndex(0u));
6283 case Type::StructTyID: {
6284 const StructType *struct_type = cast<StructType>(type);
6285 // Images and samplers are not nullable.
6286 if (struct_type->isOpaque())
Alan Baker9bf93fb2018-08-28 16:59:26 -04006287 return false;
alan-bakerb6b09dc2018-11-08 16:59:28 -05006288 for (const auto element : struct_type->elements()) {
6289 if (!IsTypeNullable(element))
6290 return false;
6291 }
6292 return true;
6293 }
6294 default:
6295 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04006296 }
6297}
Alan Bakerfcda9482018-10-02 17:09:59 -04006298
6299void SPIRVProducerPass::PopulateUBOTypeMaps(Module &module) {
6300 if (auto *offsets_md =
6301 module.getNamedMetadata(clspv::RemappedTypeOffsetMetadataName())) {
6302 // Metdata is stored as key-value pair operands. The first element of each
6303 // operand is the type and the second is a vector of offsets.
6304 for (const auto *operand : offsets_md->operands()) {
6305 const auto *pair = cast<MDTuple>(operand);
6306 auto *type =
6307 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
6308 const auto *offset_vector = cast<MDTuple>(pair->getOperand(1));
6309 std::vector<uint32_t> offsets;
6310 for (const Metadata *offset_md : offset_vector->operands()) {
6311 const auto *constant_md = cast<ConstantAsMetadata>(offset_md);
alan-bakerb6b09dc2018-11-08 16:59:28 -05006312 offsets.push_back(static_cast<uint32_t>(
6313 cast<ConstantInt>(constant_md->getValue())->getZExtValue()));
Alan Bakerfcda9482018-10-02 17:09:59 -04006314 }
6315 RemappedUBOTypeOffsets.insert(std::make_pair(type, offsets));
6316 }
6317 }
6318
6319 if (auto *sizes_md =
6320 module.getNamedMetadata(clspv::RemappedTypeSizesMetadataName())) {
6321 // Metadata is stored as key-value pair operands. The first element of each
6322 // operand is the type and the second is a triple of sizes: type size in
6323 // bits, store size and alloc size.
6324 for (const auto *operand : sizes_md->operands()) {
6325 const auto *pair = cast<MDTuple>(operand);
6326 auto *type =
6327 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
6328 const auto *size_triple = cast<MDTuple>(pair->getOperand(1));
6329 uint64_t type_size_in_bits =
6330 cast<ConstantInt>(
6331 cast<ConstantAsMetadata>(size_triple->getOperand(0))->getValue())
6332 ->getZExtValue();
6333 uint64_t type_store_size =
6334 cast<ConstantInt>(
6335 cast<ConstantAsMetadata>(size_triple->getOperand(1))->getValue())
6336 ->getZExtValue();
6337 uint64_t type_alloc_size =
6338 cast<ConstantInt>(
6339 cast<ConstantAsMetadata>(size_triple->getOperand(2))->getValue())
6340 ->getZExtValue();
6341 RemappedUBOTypeSizes.insert(std::make_pair(
6342 type, std::make_tuple(type_size_in_bits, type_store_size,
6343 type_alloc_size)));
6344 }
6345 }
6346}
6347
6348uint64_t SPIRVProducerPass::GetTypeSizeInBits(Type *type,
6349 const DataLayout &DL) {
6350 auto iter = RemappedUBOTypeSizes.find(type);
6351 if (iter != RemappedUBOTypeSizes.end()) {
6352 return std::get<0>(iter->second);
6353 }
6354
6355 return DL.getTypeSizeInBits(type);
6356}
6357
6358uint64_t SPIRVProducerPass::GetTypeStoreSize(Type *type, const DataLayout &DL) {
6359 auto iter = RemappedUBOTypeSizes.find(type);
6360 if (iter != RemappedUBOTypeSizes.end()) {
6361 return std::get<1>(iter->second);
6362 }
6363
6364 return DL.getTypeStoreSize(type);
6365}
6366
6367uint64_t SPIRVProducerPass::GetTypeAllocSize(Type *type, const DataLayout &DL) {
6368 auto iter = RemappedUBOTypeSizes.find(type);
6369 if (iter != RemappedUBOTypeSizes.end()) {
6370 return std::get<2>(iter->second);
6371 }
6372
6373 return DL.getTypeAllocSize(type);
6374}
alan-baker5b86ed72019-02-15 08:26:50 -05006375
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04006376void SPIRVProducerPass::setVariablePointersCapabilities(
6377 unsigned address_space) {
alan-baker5b86ed72019-02-15 08:26:50 -05006378 if (GetStorageClass(address_space) == spv::StorageClassStorageBuffer) {
6379 setVariablePointersStorageBuffer(true);
6380 } else {
6381 setVariablePointers(true);
6382 }
6383}
6384
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04006385Value *SPIRVProducerPass::GetBasePointer(Value *v) {
alan-baker5b86ed72019-02-15 08:26:50 -05006386 if (auto *gep = dyn_cast<GetElementPtrInst>(v)) {
6387 return GetBasePointer(gep->getPointerOperand());
6388 }
6389
6390 // Conservatively return |v|.
6391 return v;
6392}
6393
6394bool SPIRVProducerPass::sameResource(Value *lhs, Value *rhs) const {
6395 if (auto *lhs_call = dyn_cast<CallInst>(lhs)) {
6396 if (auto *rhs_call = dyn_cast<CallInst>(rhs)) {
6397 if (lhs_call->getCalledFunction()->getName().startswith(
6398 clspv::ResourceAccessorFunction()) &&
6399 rhs_call->getCalledFunction()->getName().startswith(
6400 clspv::ResourceAccessorFunction())) {
6401 // For resource accessors, match descriptor set and binding.
6402 if (lhs_call->getOperand(0) == rhs_call->getOperand(0) &&
6403 lhs_call->getOperand(1) == rhs_call->getOperand(1))
6404 return true;
6405 } else if (lhs_call->getCalledFunction()->getName().startswith(
6406 clspv::WorkgroupAccessorFunction()) &&
6407 rhs_call->getCalledFunction()->getName().startswith(
6408 clspv::WorkgroupAccessorFunction())) {
6409 // For workgroup resources, match spec id.
6410 if (lhs_call->getOperand(0) == rhs_call->getOperand(0))
6411 return true;
6412 }
6413 }
6414 }
6415
6416 return false;
6417}
6418
6419bool SPIRVProducerPass::selectFromSameObject(Instruction *inst) {
6420 assert(inst->getType()->isPointerTy());
6421 assert(GetStorageClass(inst->getType()->getPointerAddressSpace()) ==
6422 spv::StorageClassStorageBuffer);
6423 const bool hack_undef = clspv::Option::HackUndef();
6424 if (auto *select = dyn_cast<SelectInst>(inst)) {
6425 auto *true_base = GetBasePointer(select->getTrueValue());
6426 auto *false_base = GetBasePointer(select->getFalseValue());
6427
6428 if (true_base == false_base)
6429 return true;
6430
6431 // If either the true or false operand is a null, then we satisfy the same
6432 // object constraint.
6433 if (auto *true_cst = dyn_cast<Constant>(true_base)) {
6434 if (true_cst->isNullValue() || (hack_undef && isa<UndefValue>(true_base)))
6435 return true;
6436 }
6437
6438 if (auto *false_cst = dyn_cast<Constant>(false_base)) {
6439 if (false_cst->isNullValue() ||
6440 (hack_undef && isa<UndefValue>(false_base)))
6441 return true;
6442 }
6443
6444 if (sameResource(true_base, false_base))
6445 return true;
6446 } else if (auto *phi = dyn_cast<PHINode>(inst)) {
6447 Value *value = nullptr;
6448 bool ok = true;
6449 for (unsigned i = 0; ok && i != phi->getNumIncomingValues(); ++i) {
6450 auto *base = GetBasePointer(phi->getIncomingValue(i));
6451 // Null values satisfy the constraint of selecting of selecting from the
6452 // same object.
6453 if (!value) {
6454 if (auto *cst = dyn_cast<Constant>(base)) {
6455 if (!cst->isNullValue() && !(hack_undef && isa<UndefValue>(base)))
6456 value = base;
6457 } else {
6458 value = base;
6459 }
6460 } else if (base != value) {
6461 if (auto *base_cst = dyn_cast<Constant>(base)) {
6462 if (base_cst->isNullValue() || (hack_undef && isa<UndefValue>(base)))
6463 continue;
6464 }
6465
6466 if (sameResource(value, base))
6467 continue;
6468
6469 // Values don't represent the same base.
6470 ok = false;
6471 }
6472 }
6473
6474 return ok;
6475 }
6476
6477 // Conservatively return false.
6478 return false;
6479}
alan-bakere9308012019-03-15 10:25:13 -04006480
6481bool SPIRVProducerPass::CalledWithCoherentResource(Argument &Arg) {
6482 if (!Arg.getType()->isPointerTy() ||
6483 Arg.getType()->getPointerAddressSpace() != clspv::AddressSpace::Global) {
6484 // Only SSBOs need to be annotated as coherent.
6485 return false;
6486 }
6487
6488 DenseSet<Value *> visited;
6489 std::vector<Value *> stack;
6490 for (auto *U : Arg.getParent()->users()) {
6491 if (auto *call = dyn_cast<CallInst>(U)) {
6492 stack.push_back(call->getOperand(Arg.getArgNo()));
6493 }
6494 }
6495
6496 while (!stack.empty()) {
6497 Value *v = stack.back();
6498 stack.pop_back();
6499
6500 if (!visited.insert(v).second)
6501 continue;
6502
6503 auto *resource_call = dyn_cast<CallInst>(v);
6504 if (resource_call &&
6505 resource_call->getCalledFunction()->getName().startswith(
6506 clspv::ResourceAccessorFunction())) {
6507 // If this is a resource accessor function, check if the coherent operand
6508 // is set.
6509 const auto coherent =
6510 unsigned(dyn_cast<ConstantInt>(resource_call->getArgOperand(5))
6511 ->getZExtValue());
6512 if (coherent == 1)
6513 return true;
6514 } else if (auto *arg = dyn_cast<Argument>(v)) {
6515 // If this is a function argument, trace through its callers.
alan-bakere98f3f92019-04-08 15:06:36 -04006516 for (auto U : arg->getParent()->users()) {
alan-bakere9308012019-03-15 10:25:13 -04006517 if (auto *call = dyn_cast<CallInst>(U)) {
6518 stack.push_back(call->getOperand(arg->getArgNo()));
6519 }
6520 }
6521 } else if (auto *user = dyn_cast<User>(v)) {
6522 // If this is a user, traverse all operands that could lead to resource
6523 // variables.
6524 for (unsigned i = 0; i != user->getNumOperands(); ++i) {
6525 Value *operand = user->getOperand(i);
6526 if (operand->getType()->isPointerTy() &&
6527 operand->getType()->getPointerAddressSpace() ==
6528 clspv::AddressSpace::Global) {
6529 stack.push_back(operand);
6530 }
6531 }
6532 }
6533 }
6534
6535 // No coherent resource variables encountered.
6536 return false;
6537}