blob: 7157019d1cf1c4bd2289cbd982db5659b582468d [file] [log] [blame]
David Neto22f144c2017-06-12 14:26:21 -04001// Copyright 2017 The Clspv Authors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#ifdef _MSC_VER
16#pragma warning(push, 0)
17#endif
18
David Neto156783e2017-07-05 15:39:41 -040019#include <cassert>
David Neto257c3892018-04-11 13:19:45 -040020#include <cstring>
David Neto118188e2018-08-24 11:27:54 -040021#include <iomanip>
22#include <list>
David Neto862b7d82018-06-14 18:48:37 -040023#include <memory>
David Neto118188e2018-08-24 11:27:54 -040024#include <set>
25#include <sstream>
26#include <string>
27#include <tuple>
28#include <unordered_set>
29#include <utility>
David Neto862b7d82018-06-14 18:48:37 -040030
David Neto118188e2018-08-24 11:27:54 -040031#include "llvm/ADT/StringSwitch.h"
32#include "llvm/ADT/UniqueVector.h"
33#include "llvm/Analysis/LoopInfo.h"
34#include "llvm/IR/Constants.h"
35#include "llvm/IR/Dominators.h"
36#include "llvm/IR/Instructions.h"
37#include "llvm/IR/Metadata.h"
38#include "llvm/IR/Module.h"
39#include "llvm/Pass.h"
40#include "llvm/Support/CommandLine.h"
41#include "llvm/Support/raw_ostream.h"
42#include "llvm/Transforms/Utils/Cloning.h"
David Neto22f144c2017-06-12 14:26:21 -040043
David Neto85082642018-03-24 06:55:20 -070044#include "spirv/1.0/spirv.hpp"
David Neto118188e2018-08-24 11:27:54 -040045
David Neto85082642018-03-24 06:55:20 -070046#include "clspv/AddressSpace.h"
alan-bakerf5e5f692018-11-27 08:33:24 -050047#include "clspv/DescriptorMap.h"
David Neto118188e2018-08-24 11:27:54 -040048#include "clspv/Option.h"
49#include "clspv/Passes.h"
David Neto85082642018-03-24 06:55:20 -070050#include "clspv/spirv_c_strings.hpp"
51#include "clspv/spirv_glsl.hpp"
David Neto22f144c2017-06-12 14:26:21 -040052
David Neto4feb7a42017-10-06 17:29:42 -040053#include "ArgKind.h"
David Neto85082642018-03-24 06:55:20 -070054#include "ConstantEmitter.h"
Alan Baker202c8c72018-08-13 13:47:44 -040055#include "Constants.h"
David Neto78383442018-06-15 20:31:56 -040056#include "DescriptorCounter.h"
David Neto48f56a42017-10-06 16:44:25 -040057
David Neto22f144c2017-06-12 14:26:21 -040058#if defined(_MSC_VER)
59#pragma warning(pop)
60#endif
61
62using namespace llvm;
63using namespace clspv;
David Neto156783e2017-07-05 15:39:41 -040064using namespace mdconst;
David Neto22f144c2017-06-12 14:26:21 -040065
66namespace {
David Netocd8ca5f2017-10-02 23:34:11 -040067
David Neto862b7d82018-06-14 18:48:37 -040068cl::opt<bool> ShowResourceVars("show-rv", cl::init(false), cl::Hidden,
69 cl::desc("Show resource variable creation"));
70
71// These hacks exist to help transition code generation algorithms
72// without making huge noise in detailed test output.
73const bool Hack_generate_runtime_array_stride_early = true;
74
David Neto3fbb4072017-10-16 11:28:14 -040075// The value of 1/pi. This value is from MSDN
76// https://msdn.microsoft.com/en-us/library/4hwaceh6.aspx
77const double kOneOverPi = 0.318309886183790671538;
78const glsl::ExtInst kGlslExtInstBad = static_cast<glsl::ExtInst>(0);
79
alan-bakerb6b09dc2018-11-08 16:59:28 -050080const char *kCompositeConstructFunctionPrefix = "clspv.composite_construct.";
David Netoab03f432017-11-03 17:00:44 -040081
David Neto22f144c2017-06-12 14:26:21 -040082enum SPIRVOperandType {
83 NUMBERID,
84 LITERAL_INTEGER,
85 LITERAL_STRING,
86 LITERAL_FLOAT
87};
88
89struct SPIRVOperand {
90 explicit SPIRVOperand(SPIRVOperandType Ty, uint32_t Num)
91 : Type(Ty), LiteralNum(1, Num) {}
92 explicit SPIRVOperand(SPIRVOperandType Ty, const char *Str)
93 : Type(Ty), LiteralStr(Str) {}
94 explicit SPIRVOperand(SPIRVOperandType Ty, StringRef Str)
95 : Type(Ty), LiteralStr(Str) {}
96 explicit SPIRVOperand(SPIRVOperandType Ty, ArrayRef<uint32_t> NumVec)
97 : Type(Ty), LiteralNum(NumVec.begin(), NumVec.end()) {}
98
99 SPIRVOperandType getType() { return Type; };
100 uint32_t getNumID() { return LiteralNum[0]; };
101 std::string getLiteralStr() { return LiteralStr; };
102 ArrayRef<uint32_t> getLiteralNum() { return LiteralNum; };
103
David Neto87846742018-04-11 17:36:22 -0400104 uint32_t GetNumWords() const {
105 switch (Type) {
106 case NUMBERID:
107 return 1;
108 case LITERAL_INTEGER:
109 case LITERAL_FLOAT:
David Netoee2660d2018-06-28 16:31:29 -0400110 return uint32_t(LiteralNum.size());
David Neto87846742018-04-11 17:36:22 -0400111 case LITERAL_STRING:
112 // Account for the terminating null character.
David Netoee2660d2018-06-28 16:31:29 -0400113 return uint32_t((LiteralStr.size() + 4) / 4);
David Neto87846742018-04-11 17:36:22 -0400114 }
115 llvm_unreachable("Unhandled case in SPIRVOperand::GetNumWords()");
116 }
117
David Neto22f144c2017-06-12 14:26:21 -0400118private:
119 SPIRVOperandType Type;
120 std::string LiteralStr;
121 SmallVector<uint32_t, 4> LiteralNum;
122};
123
David Netoc6f3ab22018-04-06 18:02:31 -0400124class SPIRVOperandList {
125public:
126 SPIRVOperandList() {}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500127 SPIRVOperandList(const SPIRVOperandList &other) = delete;
128 SPIRVOperandList(SPIRVOperandList &&other) {
David Netoc6f3ab22018-04-06 18:02:31 -0400129 contents_ = std::move(other.contents_);
130 other.contents_.clear();
131 }
132 SPIRVOperandList(ArrayRef<SPIRVOperand *> init)
133 : contents_(init.begin(), init.end()) {}
134 operator ArrayRef<SPIRVOperand *>() { return contents_; }
135 void push_back(SPIRVOperand *op) { contents_.push_back(op); }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500136 void clear() { contents_.clear(); }
David Netoc6f3ab22018-04-06 18:02:31 -0400137 size_t size() const { return contents_.size(); }
138 SPIRVOperand *&operator[](size_t i) { return contents_[i]; }
139
David Neto87846742018-04-11 17:36:22 -0400140 const SmallVector<SPIRVOperand *, 8> &getOperands() const {
141 return contents_;
142 }
143
David Netoc6f3ab22018-04-06 18:02:31 -0400144private:
alan-bakerb6b09dc2018-11-08 16:59:28 -0500145 SmallVector<SPIRVOperand *, 8> contents_;
David Netoc6f3ab22018-04-06 18:02:31 -0400146};
147
148SPIRVOperandList &operator<<(SPIRVOperandList &list, SPIRVOperand *elem) {
149 list.push_back(elem);
150 return list;
151}
152
alan-bakerb6b09dc2018-11-08 16:59:28 -0500153SPIRVOperand *MkNum(uint32_t num) {
David Netoc6f3ab22018-04-06 18:02:31 -0400154 return new SPIRVOperand(LITERAL_INTEGER, num);
155}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500156SPIRVOperand *MkInteger(ArrayRef<uint32_t> num_vec) {
David Neto257c3892018-04-11 13:19:45 -0400157 return new SPIRVOperand(LITERAL_INTEGER, num_vec);
158}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500159SPIRVOperand *MkFloat(ArrayRef<uint32_t> num_vec) {
David Neto257c3892018-04-11 13:19:45 -0400160 return new SPIRVOperand(LITERAL_FLOAT, num_vec);
161}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500162SPIRVOperand *MkId(uint32_t id) { return new SPIRVOperand(NUMBERID, id); }
163SPIRVOperand *MkString(StringRef str) {
David Neto257c3892018-04-11 13:19:45 -0400164 return new SPIRVOperand(LITERAL_STRING, str);
165}
David Netoc6f3ab22018-04-06 18:02:31 -0400166
David Neto22f144c2017-06-12 14:26:21 -0400167struct SPIRVInstruction {
David Neto87846742018-04-11 17:36:22 -0400168 // Create an instruction with an opcode and no result ID, and with the given
169 // operands. This computes its own word count.
170 explicit SPIRVInstruction(spv::Op Opc, ArrayRef<SPIRVOperand *> Ops)
171 : WordCount(1), Opcode(static_cast<uint16_t>(Opc)), ResultID(0),
172 Operands(Ops.begin(), Ops.end()) {
173 for (auto *operand : Ops) {
David Netoee2660d2018-06-28 16:31:29 -0400174 WordCount += uint16_t(operand->GetNumWords());
David Neto87846742018-04-11 17:36:22 -0400175 }
176 }
177 // Create an instruction with an opcode and a no-zero result ID, and
178 // with the given operands. This computes its own word count.
179 explicit SPIRVInstruction(spv::Op Opc, uint32_t ResID,
David Neto22f144c2017-06-12 14:26:21 -0400180 ArrayRef<SPIRVOperand *> Ops)
David Neto87846742018-04-11 17:36:22 -0400181 : WordCount(2), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID),
182 Operands(Ops.begin(), Ops.end()) {
183 if (ResID == 0) {
184 llvm_unreachable("Result ID of 0 was provided");
185 }
186 for (auto *operand : Ops) {
187 WordCount += operand->GetNumWords();
188 }
189 }
David Neto22f144c2017-06-12 14:26:21 -0400190
David Netoee2660d2018-06-28 16:31:29 -0400191 uint32_t getWordCount() const { return WordCount; }
David Neto22f144c2017-06-12 14:26:21 -0400192 uint16_t getOpcode() const { return Opcode; }
193 uint32_t getResultID() const { return ResultID; }
194 ArrayRef<SPIRVOperand *> getOperands() const { return Operands; }
195
196private:
David Netoee2660d2018-06-28 16:31:29 -0400197 uint32_t WordCount; // Check the 16-bit bound at code generation time.
David Neto22f144c2017-06-12 14:26:21 -0400198 uint16_t Opcode;
199 uint32_t ResultID;
200 SmallVector<SPIRVOperand *, 4> Operands;
201};
202
203struct SPIRVProducerPass final : public ModulePass {
David Neto22f144c2017-06-12 14:26:21 -0400204 typedef DenseMap<Type *, uint32_t> TypeMapType;
205 typedef UniqueVector<Type *> TypeList;
206 typedef DenseMap<Value *, uint32_t> ValueMapType;
David Netofb9a7972017-08-25 17:08:24 -0400207 typedef UniqueVector<Value *> ValueList;
David Neto22f144c2017-06-12 14:26:21 -0400208 typedef std::vector<std::pair<Value *, uint32_t>> EntryPointVecType;
209 typedef std::list<SPIRVInstruction *> SPIRVInstructionList;
David Neto87846742018-04-11 17:36:22 -0400210 // A vector of tuples, each of which is:
211 // - the LLVM instruction that we will later generate SPIR-V code for
212 // - where the SPIR-V instruction should be inserted
213 // - the result ID of the SPIR-V instruction
David Neto22f144c2017-06-12 14:26:21 -0400214 typedef std::vector<
215 std::tuple<Value *, SPIRVInstructionList::iterator, uint32_t>>
216 DeferredInstVecType;
217 typedef DenseMap<FunctionType *, std::pair<FunctionType *, uint32_t>>
218 GlobalConstFuncMapType;
219
David Neto44795152017-07-13 15:45:28 -0400220 explicit SPIRVProducerPass(
alan-bakerf5e5f692018-11-27 08:33:24 -0500221 raw_pwrite_stream &out,
222 std::vector<clspv::version0::DescriptorMapEntry> *descriptor_map_entries,
David Neto44795152017-07-13 15:45:28 -0400223 ArrayRef<std::pair<unsigned, std::string>> samplerMap, bool outputAsm,
224 bool outputCInitList)
David Netoc2c368d2017-06-30 16:50:17 -0400225 : ModulePass(ID), samplerMap(samplerMap), out(out),
David Neto0676e6f2017-07-11 18:47:44 -0400226 binaryTempOut(binaryTempUnderlyingVector), binaryOut(&out),
alan-bakerf5e5f692018-11-27 08:33:24 -0500227 descriptorMapEntries(descriptor_map_entries), outputAsm(outputAsm),
David Neto0676e6f2017-07-11 18:47:44 -0400228 outputCInitList(outputCInitList), patchBoundOffset(0), nextID(1),
alan-baker5b86ed72019-02-15 08:26:50 -0500229 OpExtInstImportID(0), HasVariablePointersStorageBuffer(false),
230 HasVariablePointers(false), SamplerTy(nullptr), WorkgroupSizeValueID(0),
231 WorkgroupSizeVarID(0), max_local_spec_id_(0), constant_i32_zero_id_(0) {
232 }
David Neto22f144c2017-06-12 14:26:21 -0400233
234 void getAnalysisUsage(AnalysisUsage &AU) const override {
235 AU.addRequired<DominatorTreeWrapperPass>();
236 AU.addRequired<LoopInfoWrapperPass>();
237 }
238
239 virtual bool runOnModule(Module &module) override;
240
241 // output the SPIR-V header block
242 void outputHeader();
243
244 // patch the SPIR-V header block
245 void patchHeader();
246
247 uint32_t lookupType(Type *Ty) {
248 if (Ty->isPointerTy() &&
249 (Ty->getPointerAddressSpace() != AddressSpace::UniformConstant)) {
250 auto PointeeTy = Ty->getPointerElementType();
251 if (PointeeTy->isStructTy() &&
252 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
253 Ty = PointeeTy;
254 }
255 }
256
David Neto862b7d82018-06-14 18:48:37 -0400257 auto where = TypeMap.find(Ty);
258 if (where == TypeMap.end()) {
259 if (Ty) {
260 errs() << "Unhandled type " << *Ty << "\n";
261 } else {
262 errs() << "Unhandled type (null)\n";
263 }
David Netoe439d702018-03-23 13:14:08 -0700264 llvm_unreachable("\nUnhandled type!");
David Neto22f144c2017-06-12 14:26:21 -0400265 }
266
David Neto862b7d82018-06-14 18:48:37 -0400267 return where->second;
David Neto22f144c2017-06-12 14:26:21 -0400268 }
269 TypeMapType &getImageTypeMap() { return ImageTypeMap; }
270 TypeList &getTypeList() { return Types; };
271 ValueList &getConstantList() { return Constants; };
272 ValueMapType &getValueMap() { return ValueMap; }
273 ValueMapType &getAllocatedValueMap() { return AllocatedValueMap; }
274 SPIRVInstructionList &getSPIRVInstList() { return SPIRVInsts; };
David Neto22f144c2017-06-12 14:26:21 -0400275 EntryPointVecType &getEntryPointVec() { return EntryPointVec; };
276 DeferredInstVecType &getDeferredInstVec() { return DeferredInstVec; };
277 ValueList &getEntryPointInterfacesVec() { return EntryPointInterfacesVec; };
278 uint32_t &getOpExtInstImportID() { return OpExtInstImportID; };
279 std::vector<uint32_t> &getBuiltinDimVec() { return BuiltinDimensionVec; };
alan-baker5b86ed72019-02-15 08:26:50 -0500280 bool hasVariablePointersStorageBuffer() {
281 return HasVariablePointersStorageBuffer;
282 }
283 void setVariablePointersStorageBuffer(bool Val) {
284 HasVariablePointersStorageBuffer = Val;
285 }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500286 bool hasVariablePointers() {
alan-baker5b86ed72019-02-15 08:26:50 -0500287 return HasVariablePointers;
alan-bakerb6b09dc2018-11-08 16:59:28 -0500288 };
David Neto22f144c2017-06-12 14:26:21 -0400289 void setVariablePointers(bool Val) { HasVariablePointers = Val; };
alan-bakerb6b09dc2018-11-08 16:59:28 -0500290 ArrayRef<std::pair<unsigned, std::string>> &getSamplerMap() {
291 return samplerMap;
292 }
David Neto22f144c2017-06-12 14:26:21 -0400293 GlobalConstFuncMapType &getGlobalConstFuncTypeMap() {
294 return GlobalConstFuncTypeMap;
295 }
296 SmallPtrSet<Value *, 16> &getGlobalConstArgSet() {
297 return GlobalConstArgumentSet;
298 }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500299 TypeList &getTypesNeedingArrayStride() { return TypesNeedingArrayStride; }
David Neto22f144c2017-06-12 14:26:21 -0400300
David Netoc6f3ab22018-04-06 18:02:31 -0400301 void GenerateLLVMIRInfo(Module &M, const DataLayout &DL);
alan-bakerb6b09dc2018-11-08 16:59:28 -0500302 // Populate GlobalConstFuncTypeMap. Also, if module-scope __constant will
303 // *not* be converted to a storage buffer, replace each such global variable
304 // with one in the storage class expecgted by SPIR-V.
David Neto862b7d82018-06-14 18:48:37 -0400305 void FindGlobalConstVars(Module &M, const DataLayout &DL);
306 // Populate ResourceVarInfoList, FunctionToResourceVarsMap, and
307 // ModuleOrderedResourceVars.
308 void FindResourceVars(Module &M, const DataLayout &DL);
Alan Baker202c8c72018-08-13 13:47:44 -0400309 void FindWorkgroupVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400310 bool FindExtInst(Module &M);
311 void FindTypePerGlobalVar(GlobalVariable &GV);
312 void FindTypePerFunc(Function &F);
David Neto862b7d82018-06-14 18:48:37 -0400313 void FindTypesForSamplerMap(Module &M);
314 void FindTypesForResourceVars(Module &M);
alan-bakerb6b09dc2018-11-08 16:59:28 -0500315 // Inserts |Ty| and relevant sub-types into the |Types| member, indicating
316 // that |Ty| and its subtypes will need a corresponding SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400317 void FindType(Type *Ty);
318 void FindConstantPerGlobalVar(GlobalVariable &GV);
319 void FindConstantPerFunc(Function &F);
320 void FindConstant(Value *V);
321 void GenerateExtInstImport();
David Neto19a1bad2017-08-25 15:01:41 -0400322 // Generates instructions for SPIR-V types corresponding to the LLVM types
323 // saved in the |Types| member. A type follows its subtypes. IDs are
324 // allocated sequentially starting with the current value of nextID, and
325 // with a type following its subtypes. Also updates nextID to just beyond
326 // the last generated ID.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500327 void GenerateSPIRVTypes(LLVMContext &context, Module &module);
David Neto22f144c2017-06-12 14:26:21 -0400328 void GenerateSPIRVConstants();
David Neto5c22a252018-03-15 16:07:41 -0400329 void GenerateModuleInfo(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400330 void GenerateGlobalVar(GlobalVariable &GV);
David Netoc6f3ab22018-04-06 18:02:31 -0400331 void GenerateWorkgroupVars();
David Neto862b7d82018-06-14 18:48:37 -0400332 // Generate descriptor map entries for resource variables associated with
333 // arguments to F.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500334 void GenerateDescriptorMapInfo(const DataLayout &DL, Function &F);
David Neto22f144c2017-06-12 14:26:21 -0400335 void GenerateSamplers(Module &M);
David Neto862b7d82018-06-14 18:48:37 -0400336 // Generate OpVariables for %clspv.resource.var.* calls.
337 void GenerateResourceVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400338 void GenerateFuncPrologue(Function &F);
339 void GenerateFuncBody(Function &F);
David Netob6e2e062018-04-25 10:32:06 -0400340 void GenerateEntryPointInitialStores();
David Neto22f144c2017-06-12 14:26:21 -0400341 spv::Op GetSPIRVCmpOpcode(CmpInst *CmpI);
342 spv::Op GetSPIRVCastOpcode(Instruction &I);
343 spv::Op GetSPIRVBinaryOpcode(Instruction &I);
344 void GenerateInstruction(Instruction &I);
345 void GenerateFuncEpilogue();
346 void HandleDeferredInstruction();
alan-bakerb6b09dc2018-11-08 16:59:28 -0500347 void HandleDeferredDecorations(const DataLayout &DL);
David Neto22f144c2017-06-12 14:26:21 -0400348 bool is4xi8vec(Type *Ty) const;
David Neto257c3892018-04-11 13:19:45 -0400349 // Return the SPIR-V Id for 32-bit constant zero. The constant must already
350 // have been created.
351 uint32_t GetI32Zero();
David Neto22f144c2017-06-12 14:26:21 -0400352 spv::StorageClass GetStorageClass(unsigned AddrSpace) const;
David Neto862b7d82018-06-14 18:48:37 -0400353 spv::StorageClass GetStorageClassForArgKind(clspv::ArgKind arg_kind) const;
David Neto22f144c2017-06-12 14:26:21 -0400354 spv::BuiltIn GetBuiltin(StringRef globalVarName) const;
David Neto3fbb4072017-10-16 11:28:14 -0400355 // Returns the GLSL extended instruction enum that the given function
356 // call maps to. If none, then returns the 0 value, i.e. GLSLstd4580Bad.
David Neto22f144c2017-06-12 14:26:21 -0400357 glsl::ExtInst getExtInstEnum(StringRef Name);
David Neto3fbb4072017-10-16 11:28:14 -0400358 // Returns the GLSL extended instruction enum indirectly used by the given
359 // function. That is, to implement the given function, we use an extended
360 // instruction plus one more instruction. If none, then returns the 0 value,
361 // i.e. GLSLstd4580Bad.
362 glsl::ExtInst getIndirectExtInstEnum(StringRef Name);
363 // Returns the single GLSL extended instruction used directly or
364 // indirectly by the given function call.
365 glsl::ExtInst getDirectOrIndirectExtInstEnum(StringRef Name);
David Neto22f144c2017-06-12 14:26:21 -0400366 void PrintResID(SPIRVInstruction *Inst);
367 void PrintOpcode(SPIRVInstruction *Inst);
368 void PrintOperand(SPIRVOperand *Op);
369 void PrintCapability(SPIRVOperand *Op);
370 void PrintExtInst(SPIRVOperand *Op);
371 void PrintAddrModel(SPIRVOperand *Op);
372 void PrintMemModel(SPIRVOperand *Op);
373 void PrintExecModel(SPIRVOperand *Op);
374 void PrintExecMode(SPIRVOperand *Op);
375 void PrintSourceLanguage(SPIRVOperand *Op);
376 void PrintFuncCtrl(SPIRVOperand *Op);
377 void PrintStorageClass(SPIRVOperand *Op);
378 void PrintDecoration(SPIRVOperand *Op);
379 void PrintBuiltIn(SPIRVOperand *Op);
380 void PrintSelectionControl(SPIRVOperand *Op);
381 void PrintLoopControl(SPIRVOperand *Op);
382 void PrintDimensionality(SPIRVOperand *Op);
383 void PrintImageFormat(SPIRVOperand *Op);
384 void PrintMemoryAccess(SPIRVOperand *Op);
385 void PrintImageOperandsType(SPIRVOperand *Op);
386 void WriteSPIRVAssembly();
387 void WriteOneWord(uint32_t Word);
388 void WriteResultID(SPIRVInstruction *Inst);
389 void WriteWordCountAndOpcode(SPIRVInstruction *Inst);
390 void WriteOperand(SPIRVOperand *Op);
391 void WriteSPIRVBinary();
392
Alan Baker9bf93fb2018-08-28 16:59:26 -0400393 // Returns true if |type| is compatible with OpConstantNull.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500394 bool IsTypeNullable(const Type *type) const;
Alan Baker9bf93fb2018-08-28 16:59:26 -0400395
Alan Bakerfcda9482018-10-02 17:09:59 -0400396 // Populate UBO remapped type maps.
397 void PopulateUBOTypeMaps(Module &module);
398
399 // Wrapped methods of DataLayout accessors. If |type| was remapped for UBOs,
400 // uses the internal map, otherwise it falls back on the data layout.
401 uint64_t GetTypeSizeInBits(Type *type, const DataLayout &DL);
402 uint64_t GetTypeStoreSize(Type *type, const DataLayout &DL);
403 uint64_t GetTypeAllocSize(Type *type, const DataLayout &DL);
404
alan-baker5b86ed72019-02-15 08:26:50 -0500405 // Returns the base pointer of |v|.
406 Value *GetBasePointer(Value *v);
407
408 // Sets |HasVariablePointersStorageBuffer| or |HasVariablePointers| base on
409 // |address_space|.
410 void setVariablePointersCapabilities(unsigned address_space);
411
412 // Returns true if |lhs| and |rhs| represent the same resource or workgroup
413 // variable.
414 bool sameResource(Value *lhs, Value *rhs) const;
415
416 // Returns true if |inst| is phi or select that selects from the same
417 // structure (or null).
418 bool selectFromSameObject(Instruction *inst);
419
David Neto22f144c2017-06-12 14:26:21 -0400420private:
421 static char ID;
David Neto44795152017-07-13 15:45:28 -0400422 ArrayRef<std::pair<unsigned, std::string>> samplerMap;
David Neto22f144c2017-06-12 14:26:21 -0400423 raw_pwrite_stream &out;
David Neto0676e6f2017-07-11 18:47:44 -0400424
425 // TODO(dneto): Wouldn't it be better to always just emit a binary, and then
426 // convert to other formats on demand?
427
428 // When emitting a C initialization list, the WriteSPIRVBinary method
429 // will actually write its words to this vector via binaryTempOut.
430 SmallVector<char, 100> binaryTempUnderlyingVector;
431 raw_svector_ostream binaryTempOut;
432
433 // Binary output writes to this stream, which might be |out| or
434 // |binaryTempOut|. It's the latter when we really want to write a C
435 // initializer list.
alan-bakerf5e5f692018-11-27 08:33:24 -0500436 raw_pwrite_stream* binaryOut;
437 std::vector<version0::DescriptorMapEntry> *descriptorMapEntries;
David Neto22f144c2017-06-12 14:26:21 -0400438 const bool outputAsm;
David Neto0676e6f2017-07-11 18:47:44 -0400439 const bool outputCInitList; // If true, output look like {0x7023, ... , 5}
David Neto22f144c2017-06-12 14:26:21 -0400440 uint64_t patchBoundOffset;
441 uint32_t nextID;
442
David Neto19a1bad2017-08-25 15:01:41 -0400443 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400444 TypeMapType TypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400445 // Maps an LLVM image type to its SPIR-V ID.
David Neto22f144c2017-06-12 14:26:21 -0400446 TypeMapType ImageTypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400447 // A unique-vector of LLVM types that map to a SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400448 TypeList Types;
449 ValueList Constants;
David Neto19a1bad2017-08-25 15:01:41 -0400450 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400451 ValueMapType ValueMap;
452 ValueMapType AllocatedValueMap;
453 SPIRVInstructionList SPIRVInsts;
David Neto862b7d82018-06-14 18:48:37 -0400454
David Neto22f144c2017-06-12 14:26:21 -0400455 EntryPointVecType EntryPointVec;
456 DeferredInstVecType DeferredInstVec;
457 ValueList EntryPointInterfacesVec;
458 uint32_t OpExtInstImportID;
459 std::vector<uint32_t> BuiltinDimensionVec;
alan-baker5b86ed72019-02-15 08:26:50 -0500460 bool HasVariablePointersStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -0400461 bool HasVariablePointers;
462 Type *SamplerTy;
alan-bakerb6b09dc2018-11-08 16:59:28 -0500463 DenseMap<unsigned, uint32_t> SamplerMapIndexToIDMap;
David Netoc77d9e22018-03-24 06:30:28 -0700464
465 // If a function F has a pointer-to-__constant parameter, then this variable
David Neto9ed8e2f2018-03-24 06:47:24 -0700466 // will map F's type to (G, index of the parameter), where in a first phase
467 // G is F's type. During FindTypePerFunc, G will be changed to F's type
468 // but replacing the pointer-to-constant parameter with
469 // pointer-to-ModuleScopePrivate.
David Netoc77d9e22018-03-24 06:30:28 -0700470 // TODO(dneto): This doesn't seem general enough? A function might have
471 // more than one such parameter.
David Neto22f144c2017-06-12 14:26:21 -0400472 GlobalConstFuncMapType GlobalConstFuncTypeMap;
473 SmallPtrSet<Value *, 16> GlobalConstArgumentSet;
David Neto1a1a0582017-07-07 12:01:44 -0400474 // An ordered set of pointer types of Base arguments to OpPtrAccessChain,
David Neto85082642018-03-24 06:55:20 -0700475 // or array types, and which point into transparent memory (StorageBuffer
476 // storage class). These will require an ArrayStride decoration.
David Neto1a1a0582017-07-07 12:01:44 -0400477 // See SPV_KHR_variable_pointers rev 13.
David Neto85082642018-03-24 06:55:20 -0700478 TypeList TypesNeedingArrayStride;
David Netoa60b00b2017-09-15 16:34:09 -0400479
480 // This is truly ugly, but works around what look like driver bugs.
481 // For get_local_size, an earlier part of the flow has created a module-scope
482 // variable in Private address space to hold the value for the workgroup
483 // size. Its intializer is a uint3 value marked as builtin WorkgroupSize.
484 // When this is present, save the IDs of the initializer value and variable
485 // in these two variables. We only ever do a vector load from it, and
486 // when we see one of those, substitute just the value of the intializer.
487 // This mimics what Glslang does, and that's what drivers are used to.
David Neto66cfe642018-03-24 06:13:56 -0700488 // TODO(dneto): Remove this once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -0400489 uint32_t WorkgroupSizeValueID;
490 uint32_t WorkgroupSizeVarID;
David Neto26aaf622017-10-23 18:11:53 -0400491
David Neto862b7d82018-06-14 18:48:37 -0400492 // Bookkeeping for mapping kernel arguments to resource variables.
493 struct ResourceVarInfo {
494 ResourceVarInfo(int index_arg, unsigned set_arg, unsigned binding_arg,
495 Function *fn, clspv::ArgKind arg_kind_arg)
496 : index(index_arg), descriptor_set(set_arg), binding(binding_arg),
497 var_fn(fn), arg_kind(arg_kind_arg),
498 addr_space(fn->getReturnType()->getPointerAddressSpace()) {}
499 const int index; // Index into ResourceVarInfoList
500 const unsigned descriptor_set;
501 const unsigned binding;
502 Function *const var_fn; // The @clspv.resource.var.* function.
503 const clspv::ArgKind arg_kind;
504 const unsigned addr_space; // The LLVM address space
505 // The SPIR-V ID of the OpVariable. Not populated at construction time.
506 uint32_t var_id = 0;
507 };
508 // A list of resource var info. Each one correponds to a module-scope
509 // resource variable we will have to create. Resource var indices are
510 // indices into this vector.
511 SmallVector<std::unique_ptr<ResourceVarInfo>, 8> ResourceVarInfoList;
512 // This is a vector of pointers of all the resource vars, but ordered by
513 // kernel function, and then by argument.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500514 UniqueVector<ResourceVarInfo *> ModuleOrderedResourceVars;
David Neto862b7d82018-06-14 18:48:37 -0400515 // Map a function to the ordered list of resource variables it uses, one for
516 // each argument. If an argument does not use a resource variable, it
517 // will have a null pointer entry.
518 using FunctionToResourceVarsMapType =
519 DenseMap<Function *, SmallVector<ResourceVarInfo *, 8>>;
520 FunctionToResourceVarsMapType FunctionToResourceVarsMap;
521
522 // What LLVM types map to SPIR-V types needing layout? These are the
523 // arrays and structures supporting storage buffers and uniform buffers.
524 TypeList TypesNeedingLayout;
525 // What LLVM struct types map to a SPIR-V struct type with Block decoration?
526 UniqueVector<StructType *> StructTypesNeedingBlock;
527 // For a call that represents a load from an opaque type (samplers, images),
528 // map it to the variable id it should load from.
529 DenseMap<CallInst *, uint32_t> ResourceVarDeferredLoadCalls;
David Neto85082642018-03-24 06:55:20 -0700530
Alan Baker202c8c72018-08-13 13:47:44 -0400531 // One larger than the maximum used SpecId for pointer-to-local arguments.
532 int max_local_spec_id_;
David Netoc6f3ab22018-04-06 18:02:31 -0400533 // An ordered list of the kernel arguments of type pointer-to-local.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500534 using LocalArgList = SmallVector<Argument *, 8>;
David Netoc6f3ab22018-04-06 18:02:31 -0400535 LocalArgList LocalArgs;
536 // Information about a pointer-to-local argument.
537 struct LocalArgInfo {
538 // The SPIR-V ID of the array variable.
539 uint32_t variable_id;
540 // The element type of the
alan-bakerb6b09dc2018-11-08 16:59:28 -0500541 Type *elem_type;
David Netoc6f3ab22018-04-06 18:02:31 -0400542 // The ID of the array type.
543 uint32_t array_size_id;
544 // The ID of the array type.
545 uint32_t array_type_id;
546 // The ID of the pointer to the array type.
547 uint32_t ptr_array_type_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400548 // The specialization constant ID of the array size.
549 int spec_id;
550 };
Alan Baker202c8c72018-08-13 13:47:44 -0400551 // A mapping from Argument to its assigned SpecId.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500552 DenseMap<const Argument *, int> LocalArgSpecIds;
Alan Baker202c8c72018-08-13 13:47:44 -0400553 // A mapping from SpecId to its LocalArgInfo.
554 DenseMap<int, LocalArgInfo> LocalSpecIdInfoMap;
Alan Bakerfcda9482018-10-02 17:09:59 -0400555 // A mapping from a remapped type to its real offsets.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500556 DenseMap<Type *, std::vector<uint32_t>> RemappedUBOTypeOffsets;
Alan Bakerfcda9482018-10-02 17:09:59 -0400557 // A mapping from a remapped type to its real sizes.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500558 DenseMap<Type *, std::tuple<uint64_t, uint64_t, uint64_t>>
559 RemappedUBOTypeSizes;
David Neto257c3892018-04-11 13:19:45 -0400560
561 // The ID of 32-bit integer zero constant. This is only valid after
562 // GenerateSPIRVConstants has run.
563 uint32_t constant_i32_zero_id_;
David Neto22f144c2017-06-12 14:26:21 -0400564};
565
566char SPIRVProducerPass::ID;
David Netoc6f3ab22018-04-06 18:02:31 -0400567
alan-bakerb6b09dc2018-11-08 16:59:28 -0500568} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400569
570namespace clspv {
alan-bakerf5e5f692018-11-27 08:33:24 -0500571ModulePass *createSPIRVProducerPass(
572 raw_pwrite_stream &out,
573 std::vector<version0::DescriptorMapEntry> *descriptor_map_entries,
574 ArrayRef<std::pair<unsigned, std::string>> samplerMap, bool outputAsm,
575 bool outputCInitList) {
576 return new SPIRVProducerPass(out, descriptor_map_entries, samplerMap,
577 outputAsm, outputCInitList);
David Neto22f144c2017-06-12 14:26:21 -0400578}
David Netoc2c368d2017-06-30 16:50:17 -0400579} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400580
581bool SPIRVProducerPass::runOnModule(Module &module) {
David Neto0676e6f2017-07-11 18:47:44 -0400582 binaryOut = outputCInitList ? &binaryTempOut : &out;
583
David Neto257c3892018-04-11 13:19:45 -0400584 constant_i32_zero_id_ = 0; // Reset, for the benefit of validity checks.
585
Alan Bakerfcda9482018-10-02 17:09:59 -0400586 PopulateUBOTypeMaps(module);
587
David Neto22f144c2017-06-12 14:26:21 -0400588 // SPIR-V always begins with its header information
589 outputHeader();
590
David Netoc6f3ab22018-04-06 18:02:31 -0400591 const DataLayout &DL = module.getDataLayout();
592
David Neto22f144c2017-06-12 14:26:21 -0400593 // Gather information from the LLVM IR that we require.
David Netoc6f3ab22018-04-06 18:02:31 -0400594 GenerateLLVMIRInfo(module, DL);
David Neto22f144c2017-06-12 14:26:21 -0400595
David Neto22f144c2017-06-12 14:26:21 -0400596 // Collect information on global variables too.
597 for (GlobalVariable &GV : module.globals()) {
598 // If the GV is one of our special __spirv_* variables, remove the
599 // initializer as it was only placed there to force LLVM to not throw the
600 // value away.
601 if (GV.getName().startswith("__spirv_")) {
602 GV.setInitializer(nullptr);
603 }
604
605 // Collect types' information from global variable.
606 FindTypePerGlobalVar(GV);
607
608 // Collect constant information from global variable.
609 FindConstantPerGlobalVar(GV);
610
611 // If the variable is an input, entry points need to know about it.
612 if (AddressSpace::Input == GV.getType()->getPointerAddressSpace()) {
David Netofb9a7972017-08-25 17:08:24 -0400613 getEntryPointInterfacesVec().insert(&GV);
David Neto22f144c2017-06-12 14:26:21 -0400614 }
615 }
616
617 // If there are extended instructions, generate OpExtInstImport.
618 if (FindExtInst(module)) {
619 GenerateExtInstImport();
620 }
621
622 // Generate SPIRV instructions for types.
Alan Bakerfcda9482018-10-02 17:09:59 -0400623 GenerateSPIRVTypes(module.getContext(), module);
David Neto22f144c2017-06-12 14:26:21 -0400624
625 // Generate SPIRV constants.
626 GenerateSPIRVConstants();
627
628 // If we have a sampler map, we might have literal samplers to generate.
629 if (0 < getSamplerMap().size()) {
630 GenerateSamplers(module);
631 }
632
633 // Generate SPIRV variables.
634 for (GlobalVariable &GV : module.globals()) {
635 GenerateGlobalVar(GV);
636 }
David Neto862b7d82018-06-14 18:48:37 -0400637 GenerateResourceVars(module);
David Netoc6f3ab22018-04-06 18:02:31 -0400638 GenerateWorkgroupVars();
David Neto22f144c2017-06-12 14:26:21 -0400639
640 // Generate SPIRV instructions for each function.
641 for (Function &F : module) {
642 if (F.isDeclaration()) {
643 continue;
644 }
645
David Neto862b7d82018-06-14 18:48:37 -0400646 GenerateDescriptorMapInfo(DL, F);
647
David Neto22f144c2017-06-12 14:26:21 -0400648 // Generate Function Prologue.
649 GenerateFuncPrologue(F);
650
651 // Generate SPIRV instructions for function body.
652 GenerateFuncBody(F);
653
654 // Generate Function Epilogue.
655 GenerateFuncEpilogue();
656 }
657
658 HandleDeferredInstruction();
David Neto1a1a0582017-07-07 12:01:44 -0400659 HandleDeferredDecorations(DL);
David Neto22f144c2017-06-12 14:26:21 -0400660
661 // Generate SPIRV module information.
David Neto5c22a252018-03-15 16:07:41 -0400662 GenerateModuleInfo(module);
David Neto22f144c2017-06-12 14:26:21 -0400663
664 if (outputAsm) {
665 WriteSPIRVAssembly();
666 } else {
667 WriteSPIRVBinary();
668 }
669
670 // We need to patch the SPIR-V header to set bound correctly.
671 patchHeader();
David Neto0676e6f2017-07-11 18:47:44 -0400672
673 if (outputCInitList) {
674 bool first = true;
David Neto0676e6f2017-07-11 18:47:44 -0400675 std::ostringstream os;
676
David Neto57fb0b92017-08-04 15:35:09 -0400677 auto emit_word = [&os, &first](uint32_t word) {
David Neto0676e6f2017-07-11 18:47:44 -0400678 if (!first)
David Neto57fb0b92017-08-04 15:35:09 -0400679 os << ",\n";
680 os << word;
David Neto0676e6f2017-07-11 18:47:44 -0400681 first = false;
682 };
683
684 os << "{";
David Neto57fb0b92017-08-04 15:35:09 -0400685 const std::string str(binaryTempOut.str());
686 for (unsigned i = 0; i < str.size(); i += 4) {
687 const uint32_t a = static_cast<unsigned char>(str[i]);
688 const uint32_t b = static_cast<unsigned char>(str[i + 1]);
689 const uint32_t c = static_cast<unsigned char>(str[i + 2]);
690 const uint32_t d = static_cast<unsigned char>(str[i + 3]);
691 emit_word(a | (b << 8) | (c << 16) | (d << 24));
David Neto0676e6f2017-07-11 18:47:44 -0400692 }
693 os << "}\n";
694 out << os.str();
695 }
696
David Neto22f144c2017-06-12 14:26:21 -0400697 return false;
698}
699
700void SPIRVProducerPass::outputHeader() {
701 if (outputAsm) {
702 // for ASM output the header goes into 5 comments at the beginning of the
703 // file
704 out << "; SPIR-V\n";
705
706 // the major version number is in the 2nd highest byte
707 const uint32_t major = (spv::Version >> 16) & 0xFF;
708
709 // the minor version number is in the 2nd lowest byte
710 const uint32_t minor = (spv::Version >> 8) & 0xFF;
711 out << "; Version: " << major << "." << minor << "\n";
712
713 // use Codeplay's vendor ID
714 out << "; Generator: Codeplay; 0\n";
715
716 out << "; Bound: ";
717
718 // we record where we need to come back to and patch in the bound value
719 patchBoundOffset = out.tell();
720
721 // output one space per digit for the max size of a 32 bit unsigned integer
722 // (which is the maximum ID we could possibly be using)
723 for (uint32_t i = std::numeric_limits<uint32_t>::max(); 0 != i; i /= 10) {
724 out << " ";
725 }
726
727 out << "\n";
728
729 out << "; Schema: 0\n";
730 } else {
David Neto0676e6f2017-07-11 18:47:44 -0400731 binaryOut->write(reinterpret_cast<const char *>(&spv::MagicNumber),
alan-bakerb6b09dc2018-11-08 16:59:28 -0500732 sizeof(spv::MagicNumber));
David Neto0676e6f2017-07-11 18:47:44 -0400733 binaryOut->write(reinterpret_cast<const char *>(&spv::Version),
alan-bakerb6b09dc2018-11-08 16:59:28 -0500734 sizeof(spv::Version));
David Neto22f144c2017-06-12 14:26:21 -0400735
736 // use Codeplay's vendor ID
737 const uint32_t vendor = 3 << 16;
David Neto0676e6f2017-07-11 18:47:44 -0400738 binaryOut->write(reinterpret_cast<const char *>(&vendor), sizeof(vendor));
David Neto22f144c2017-06-12 14:26:21 -0400739
740 // we record where we need to come back to and patch in the bound value
David Neto0676e6f2017-07-11 18:47:44 -0400741 patchBoundOffset = binaryOut->tell();
David Neto22f144c2017-06-12 14:26:21 -0400742
743 // output a bad bound for now
David Neto0676e6f2017-07-11 18:47:44 -0400744 binaryOut->write(reinterpret_cast<const char *>(&nextID), sizeof(nextID));
David Neto22f144c2017-06-12 14:26:21 -0400745
746 // output the schema (reserved for use and must be 0)
747 const uint32_t schema = 0;
David Neto0676e6f2017-07-11 18:47:44 -0400748 binaryOut->write(reinterpret_cast<const char *>(&schema), sizeof(schema));
David Neto22f144c2017-06-12 14:26:21 -0400749 }
750}
751
752void SPIRVProducerPass::patchHeader() {
753 if (outputAsm) {
754 // get the string representation of the max bound used (nextID will be the
755 // max ID used)
756 auto asString = std::to_string(nextID);
757 out.pwrite(asString.c_str(), asString.size(), patchBoundOffset);
758 } else {
759 // for a binary we just write the value of nextID over bound
David Neto0676e6f2017-07-11 18:47:44 -0400760 binaryOut->pwrite(reinterpret_cast<char *>(&nextID), sizeof(nextID),
761 patchBoundOffset);
David Neto22f144c2017-06-12 14:26:21 -0400762 }
763}
764
David Netoc6f3ab22018-04-06 18:02:31 -0400765void SPIRVProducerPass::GenerateLLVMIRInfo(Module &M, const DataLayout &DL) {
David Neto22f144c2017-06-12 14:26:21 -0400766 // This function generates LLVM IR for function such as global variable for
767 // argument, constant and pointer type for argument access. These information
768 // is artificial one because we need Vulkan SPIR-V output. This function is
769 // executed ahead of FindType and FindConstant.
David Neto22f144c2017-06-12 14:26:21 -0400770 LLVMContext &Context = M.getContext();
771
David Neto862b7d82018-06-14 18:48:37 -0400772 FindGlobalConstVars(M, DL);
David Neto5c22a252018-03-15 16:07:41 -0400773
David Neto862b7d82018-06-14 18:48:37 -0400774 FindResourceVars(M, DL);
David Neto22f144c2017-06-12 14:26:21 -0400775
776 bool HasWorkGroupBuiltin = false;
777 for (GlobalVariable &GV : M.globals()) {
778 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
779 if (spv::BuiltInWorkgroupSize == BuiltinType) {
780 HasWorkGroupBuiltin = true;
781 }
782 }
783
David Neto862b7d82018-06-14 18:48:37 -0400784 FindTypesForSamplerMap(M);
785 FindTypesForResourceVars(M);
Alan Baker202c8c72018-08-13 13:47:44 -0400786 FindWorkgroupVars(M);
David Neto22f144c2017-06-12 14:26:21 -0400787
David Neto862b7d82018-06-14 18:48:37 -0400788 // These function calls need a <2 x i32> as an intermediate result but not
789 // the final result.
790 std::unordered_set<std::string> NeedsIVec2{
791 "_Z15get_image_width14ocl_image2d_ro",
792 "_Z15get_image_width14ocl_image2d_wo",
793 "_Z16get_image_height14ocl_image2d_ro",
794 "_Z16get_image_height14ocl_image2d_wo",
795 };
796
David Neto22f144c2017-06-12 14:26:21 -0400797 for (Function &F : M) {
798 // Handle kernel function first.
799 if (F.isDeclaration() || F.getCallingConv() != CallingConv::SPIR_KERNEL) {
800 continue;
801 }
802
803 for (BasicBlock &BB : F) {
804 for (Instruction &I : BB) {
805 if (I.getOpcode() == Instruction::ZExt ||
806 I.getOpcode() == Instruction::SExt ||
807 I.getOpcode() == Instruction::UIToFP) {
808 // If there is zext with i1 type, it will be changed to OpSelect. The
809 // OpSelect needs constant 0 and 1 so the constants are added here.
810
811 auto OpTy = I.getOperand(0)->getType();
812
Kévin Petit24272b62018-10-18 19:16:12 +0000813 if (OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -0400814 if (I.getOpcode() == Instruction::ZExt) {
David Neto22f144c2017-06-12 14:26:21 -0400815 FindConstant(Constant::getNullValue(I.getType()));
Kévin Petit7bfb8992019-02-26 13:45:08 +0000816 FindConstant(ConstantInt::get(I.getType(), 1));
David Neto22f144c2017-06-12 14:26:21 -0400817 } else if (I.getOpcode() == Instruction::SExt) {
David Neto22f144c2017-06-12 14:26:21 -0400818 FindConstant(Constant::getNullValue(I.getType()));
Kévin Petit7bfb8992019-02-26 13:45:08 +0000819 FindConstant(ConstantInt::getSigned(I.getType(), -1));
David Neto22f144c2017-06-12 14:26:21 -0400820 } else {
821 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
822 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
823 }
824 }
825 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
David Neto862b7d82018-06-14 18:48:37 -0400826 StringRef callee_name = Call->getCalledFunction()->getName();
David Neto22f144c2017-06-12 14:26:21 -0400827
828 // Handle image type specially.
David Neto862b7d82018-06-14 18:48:37 -0400829 if (callee_name.equals(
David Neto22f144c2017-06-12 14:26:21 -0400830 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
David Neto862b7d82018-06-14 18:48:37 -0400831 callee_name.equals(
David Neto22f144c2017-06-12 14:26:21 -0400832 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
833 TypeMapType &OpImageTypeMap = getImageTypeMap();
834 Type *ImageTy =
835 Call->getArgOperand(0)->getType()->getPointerElementType();
836 OpImageTypeMap[ImageTy] = 0;
837
838 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
839 }
David Neto5c22a252018-03-15 16:07:41 -0400840
David Neto862b7d82018-06-14 18:48:37 -0400841 if (NeedsIVec2.find(callee_name) != NeedsIVec2.end()) {
David Neto5c22a252018-03-15 16:07:41 -0400842 FindType(VectorType::get(Type::getInt32Ty(Context), 2));
843 }
David Neto22f144c2017-06-12 14:26:21 -0400844 }
845 }
846 }
847
David Neto22f144c2017-06-12 14:26:21 -0400848 if (const MDNode *MD =
849 dyn_cast<Function>(&F)->getMetadata("reqd_work_group_size")) {
850 // We generate constants if the WorkgroupSize builtin is being used.
851 if (HasWorkGroupBuiltin) {
852 // Collect constant information for work group size.
853 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(0)));
854 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(1)));
855 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(2)));
856 }
857 }
858
David Neto22f144c2017-06-12 14:26:21 -0400859 // Collect types' information from function.
860 FindTypePerFunc(F);
861
862 // Collect constant information from function.
863 FindConstantPerFunc(F);
864 }
865
866 for (Function &F : M) {
867 // Handle non-kernel functions.
868 if (F.isDeclaration() || F.getCallingConv() == CallingConv::SPIR_KERNEL) {
869 continue;
870 }
871
872 for (BasicBlock &BB : F) {
873 for (Instruction &I : BB) {
874 if (I.getOpcode() == Instruction::ZExt ||
875 I.getOpcode() == Instruction::SExt ||
876 I.getOpcode() == Instruction::UIToFP) {
877 // If there is zext with i1 type, it will be changed to OpSelect. The
878 // OpSelect needs constant 0 and 1 so the constants are added here.
879
880 auto OpTy = I.getOperand(0)->getType();
881
Kévin Petit24272b62018-10-18 19:16:12 +0000882 if (OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -0400883 if (I.getOpcode() == Instruction::ZExt) {
David Neto22f144c2017-06-12 14:26:21 -0400884 FindConstant(Constant::getNullValue(I.getType()));
Kévin Petit7bfb8992019-02-26 13:45:08 +0000885 FindConstant(ConstantInt::get(I.getType(), 1));
David Neto22f144c2017-06-12 14:26:21 -0400886 } else if (I.getOpcode() == Instruction::SExt) {
David Neto22f144c2017-06-12 14:26:21 -0400887 FindConstant(Constant::getNullValue(I.getType()));
Kévin Petit7bfb8992019-02-26 13:45:08 +0000888 FindConstant(ConstantInt::getSigned(I.getType(), -1));
David Neto22f144c2017-06-12 14:26:21 -0400889 } else {
890 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
891 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
892 }
893 }
894 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
895 Function *Callee = Call->getCalledFunction();
896
897 // Handle image type specially.
898 if (Callee->getName().equals(
899 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
900 Callee->getName().equals(
901 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
902 TypeMapType &OpImageTypeMap = getImageTypeMap();
903 Type *ImageTy =
904 Call->getArgOperand(0)->getType()->getPointerElementType();
905 OpImageTypeMap[ImageTy] = 0;
906
907 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
908 }
909 }
910 }
911 }
912
913 if (M.getTypeByName("opencl.image2d_ro_t") ||
914 M.getTypeByName("opencl.image2d_wo_t") ||
915 M.getTypeByName("opencl.image3d_ro_t") ||
916 M.getTypeByName("opencl.image3d_wo_t")) {
917 // Assume Image type's sampled type is float type.
918 FindType(Type::getFloatTy(Context));
919 }
920
921 // Collect types' information from function.
922 FindTypePerFunc(F);
923
924 // Collect constant information from function.
925 FindConstantPerFunc(F);
926 }
927}
928
David Neto862b7d82018-06-14 18:48:37 -0400929void SPIRVProducerPass::FindGlobalConstVars(Module &M, const DataLayout &DL) {
930 SmallVector<GlobalVariable *, 8> GVList;
931 SmallVector<GlobalVariable *, 8> DeadGVList;
932 for (GlobalVariable &GV : M.globals()) {
933 if (GV.getType()->getAddressSpace() == AddressSpace::Constant) {
934 if (GV.use_empty()) {
935 DeadGVList.push_back(&GV);
936 } else {
937 GVList.push_back(&GV);
938 }
939 }
940 }
941
942 // Remove dead global __constant variables.
943 for (auto GV : DeadGVList) {
944 GV->eraseFromParent();
945 }
946 DeadGVList.clear();
947
948 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
949 // For now, we only support a single storage buffer.
950 if (GVList.size() > 0) {
951 assert(GVList.size() == 1);
952 const auto *GV = GVList[0];
953 const auto constants_byte_size =
Alan Bakerfcda9482018-10-02 17:09:59 -0400954 (GetTypeSizeInBits(GV->getInitializer()->getType(), DL)) / 8;
David Neto862b7d82018-06-14 18:48:37 -0400955 const size_t kConstantMaxSize = 65536;
956 if (constants_byte_size > kConstantMaxSize) {
957 outs() << "Max __constant capacity of " << kConstantMaxSize
958 << " bytes exceeded: " << constants_byte_size << " bytes used\n";
959 llvm_unreachable("Max __constant capacity exceeded");
960 }
961 }
962 } else {
963 // Change global constant variable's address space to ModuleScopePrivate.
964 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
965 for (auto GV : GVList) {
966 // Create new gv with ModuleScopePrivate address space.
967 Type *NewGVTy = GV->getType()->getPointerElementType();
968 GlobalVariable *NewGV = new GlobalVariable(
969 M, NewGVTy, false, GV->getLinkage(), GV->getInitializer(), "",
970 nullptr, GV->getThreadLocalMode(), AddressSpace::ModuleScopePrivate);
971 NewGV->takeName(GV);
972
973 const SmallVector<User *, 8> GVUsers(GV->user_begin(), GV->user_end());
974 SmallVector<User *, 8> CandidateUsers;
975
976 auto record_called_function_type_as_user =
977 [&GlobalConstFuncTyMap](Value *gv, CallInst *call) {
978 // Find argument index.
979 unsigned index = 0;
980 for (unsigned i = 0; i < call->getNumArgOperands(); i++) {
981 if (gv == call->getOperand(i)) {
982 // TODO(dneto): Should we break here?
983 index = i;
984 }
985 }
986
987 // Record function type with global constant.
988 GlobalConstFuncTyMap[call->getFunctionType()] =
989 std::make_pair(call->getFunctionType(), index);
990 };
991
992 for (User *GVU : GVUsers) {
993 if (CallInst *Call = dyn_cast<CallInst>(GVU)) {
994 record_called_function_type_as_user(GV, Call);
995 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(GVU)) {
996 // Check GEP users.
997 for (User *GEPU : GEP->users()) {
998 if (CallInst *GEPCall = dyn_cast<CallInst>(GEPU)) {
999 record_called_function_type_as_user(GEP, GEPCall);
1000 }
1001 }
1002 }
1003
1004 CandidateUsers.push_back(GVU);
1005 }
1006
1007 for (User *U : CandidateUsers) {
1008 // Update users of gv with new gv.
alan-bakered80f572019-02-11 17:28:26 -05001009 if (!isa<Constant>(U)) {
1010 // #254: Can't change operands of a constant, but this shouldn't be
1011 // something that sticks around in the module.
1012 U->replaceUsesOfWith(GV, NewGV);
1013 }
David Neto862b7d82018-06-14 18:48:37 -04001014 }
1015
1016 // Delete original gv.
1017 GV->eraseFromParent();
1018 }
1019 }
1020}
1021
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001022void SPIRVProducerPass::FindResourceVars(Module &M, const DataLayout &) {
David Neto862b7d82018-06-14 18:48:37 -04001023 ResourceVarInfoList.clear();
1024 FunctionToResourceVarsMap.clear();
1025 ModuleOrderedResourceVars.reset();
1026 // Normally, there is one resource variable per clspv.resource.var.*
1027 // function, since that is unique'd by arg type and index. By design,
1028 // we can share these resource variables across kernels because all
1029 // kernels use the same descriptor set.
1030 //
1031 // But if the user requested distinct descriptor sets per kernel, then
1032 // the descriptor allocator has made different (set,binding) pairs for
1033 // the same (type,arg_index) pair. Since we can decorate a resource
1034 // variable with only exactly one DescriptorSet and Binding, we are
1035 // forced in this case to make distinct resource variables whenever
1036 // the same clspv.reource.var.X function is seen with disintct
1037 // (set,binding) values.
1038 const bool always_distinct_sets =
1039 clspv::Option::DistinctKernelDescriptorSets();
1040 for (Function &F : M) {
1041 // Rely on the fact the resource var functions have a stable ordering
1042 // in the module.
Alan Baker202c8c72018-08-13 13:47:44 -04001043 if (F.getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001044 // Find all calls to this function with distinct set and binding pairs.
1045 // Save them in ResourceVarInfoList.
1046
1047 // Determine uniqueness of the (set,binding) pairs only withing this
1048 // one resource-var builtin function.
1049 using SetAndBinding = std::pair<unsigned, unsigned>;
1050 // Maps set and binding to the resource var info.
1051 DenseMap<SetAndBinding, ResourceVarInfo *> set_and_binding_map;
1052 bool first_use = true;
1053 for (auto &U : F.uses()) {
1054 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
1055 const auto set = unsigned(
1056 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
1057 const auto binding = unsigned(
1058 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
1059 const auto arg_kind = clspv::ArgKind(
1060 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
1061 const auto arg_index = unsigned(
1062 dyn_cast<ConstantInt>(call->getArgOperand(3))->getZExtValue());
1063
1064 // Find or make the resource var info for this combination.
1065 ResourceVarInfo *rv = nullptr;
1066 if (always_distinct_sets) {
1067 // Make a new resource var any time we see a different
1068 // (set,binding) pair.
1069 SetAndBinding key{set, binding};
1070 auto where = set_and_binding_map.find(key);
1071 if (where == set_and_binding_map.end()) {
1072 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
1073 binding, &F, arg_kind);
1074 ResourceVarInfoList.emplace_back(rv);
1075 set_and_binding_map[key] = rv;
1076 } else {
1077 rv = where->second;
1078 }
1079 } else {
1080 // The default is to make exactly one resource for each
1081 // clspv.resource.var.* function.
1082 if (first_use) {
1083 first_use = false;
1084 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
1085 binding, &F, arg_kind);
1086 ResourceVarInfoList.emplace_back(rv);
1087 } else {
1088 rv = ResourceVarInfoList.back().get();
1089 }
1090 }
1091
1092 // Now populate FunctionToResourceVarsMap.
1093 auto &mapping =
1094 FunctionToResourceVarsMap[call->getParent()->getParent()];
1095 while (mapping.size() <= arg_index) {
1096 mapping.push_back(nullptr);
1097 }
1098 mapping[arg_index] = rv;
1099 }
1100 }
1101 }
1102 }
1103
1104 // Populate ModuleOrderedResourceVars.
1105 for (Function &F : M) {
1106 auto where = FunctionToResourceVarsMap.find(&F);
1107 if (where != FunctionToResourceVarsMap.end()) {
1108 for (auto &rv : where->second) {
1109 if (rv != nullptr) {
1110 ModuleOrderedResourceVars.insert(rv);
1111 }
1112 }
1113 }
1114 }
1115 if (ShowResourceVars) {
1116 for (auto *info : ModuleOrderedResourceVars) {
1117 outs() << "MORV index " << info->index << " (" << info->descriptor_set
1118 << "," << info->binding << ") " << *(info->var_fn->getReturnType())
1119 << "\n";
1120 }
1121 }
1122}
1123
David Neto22f144c2017-06-12 14:26:21 -04001124bool SPIRVProducerPass::FindExtInst(Module &M) {
1125 LLVMContext &Context = M.getContext();
1126 bool HasExtInst = false;
1127
1128 for (Function &F : M) {
1129 for (BasicBlock &BB : F) {
1130 for (Instruction &I : BB) {
1131 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1132 Function *Callee = Call->getCalledFunction();
1133 // Check whether this call is for extend instructions.
David Neto3fbb4072017-10-16 11:28:14 -04001134 auto callee_name = Callee->getName();
1135 const glsl::ExtInst EInst = getExtInstEnum(callee_name);
1136 const glsl::ExtInst IndirectEInst =
1137 getIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04001138
David Neto3fbb4072017-10-16 11:28:14 -04001139 HasExtInst |=
1140 (EInst != kGlslExtInstBad) || (IndirectEInst != kGlslExtInstBad);
1141
1142 if (IndirectEInst) {
1143 // Register extra constants if needed.
1144
1145 // Registers a type and constant for computing the result of the
1146 // given instruction. If the result of the instruction is a vector,
1147 // then make a splat vector constant with the same number of
1148 // elements.
1149 auto register_constant = [this, &I](Constant *constant) {
1150 FindType(constant->getType());
1151 FindConstant(constant);
1152 if (auto *vectorTy = dyn_cast<VectorType>(I.getType())) {
1153 // Register the splat vector of the value with the same
1154 // width as the result of the instruction.
1155 auto *vec_constant = ConstantVector::getSplat(
1156 static_cast<unsigned>(vectorTy->getNumElements()),
1157 constant);
1158 FindConstant(vec_constant);
1159 FindType(vec_constant->getType());
1160 }
1161 };
1162 switch (IndirectEInst) {
1163 case glsl::ExtInstFindUMsb:
1164 // clz needs OpExtInst and OpISub with constant 31, or splat
1165 // vector of 31. Add it to the constant list here.
1166 register_constant(
1167 ConstantInt::get(Type::getInt32Ty(Context), 31));
1168 break;
1169 case glsl::ExtInstAcos:
1170 case glsl::ExtInstAsin:
Kévin Petiteb9f90a2018-09-29 12:29:34 +01001171 case glsl::ExtInstAtan:
David Neto3fbb4072017-10-16 11:28:14 -04001172 case glsl::ExtInstAtan2:
1173 // We need 1/pi for acospi, asinpi, atan2pi.
1174 register_constant(
1175 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
1176 break;
1177 default:
1178 assert(false && "internally inconsistent");
1179 }
David Neto22f144c2017-06-12 14:26:21 -04001180 }
1181 }
1182 }
1183 }
1184 }
1185
1186 return HasExtInst;
1187}
1188
1189void SPIRVProducerPass::FindTypePerGlobalVar(GlobalVariable &GV) {
1190 // Investigate global variable's type.
1191 FindType(GV.getType());
1192}
1193
1194void SPIRVProducerPass::FindTypePerFunc(Function &F) {
1195 // Investigate function's type.
1196 FunctionType *FTy = F.getFunctionType();
1197
1198 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
1199 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
David Neto9ed8e2f2018-03-24 06:47:24 -07001200 // Handle a regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04001201 if (GlobalConstFuncTyMap.count(FTy)) {
1202 uint32_t GVCstArgIdx = GlobalConstFuncTypeMap[FTy].second;
1203 SmallVector<Type *, 4> NewFuncParamTys;
1204 for (unsigned i = 0; i < FTy->getNumParams(); i++) {
1205 Type *ParamTy = FTy->getParamType(i);
1206 if (i == GVCstArgIdx) {
1207 Type *EleTy = ParamTy->getPointerElementType();
1208 ParamTy = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1209 }
1210
1211 NewFuncParamTys.push_back(ParamTy);
1212 }
1213
1214 FunctionType *NewFTy =
1215 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1216 GlobalConstFuncTyMap[FTy] = std::make_pair(NewFTy, GVCstArgIdx);
1217 FTy = NewFTy;
1218 }
1219
1220 FindType(FTy);
1221 } else {
1222 // As kernel functions do not have parameters, create new function type and
1223 // add it to type map.
1224 SmallVector<Type *, 4> NewFuncParamTys;
1225 FunctionType *NewFTy =
1226 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1227 FindType(NewFTy);
1228 }
1229
1230 // Investigate instructions' type in function body.
1231 for (BasicBlock &BB : F) {
1232 for (Instruction &I : BB) {
1233 if (isa<ShuffleVectorInst>(I)) {
1234 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1235 // Ignore type for mask of shuffle vector instruction.
1236 if (i == 2) {
1237 continue;
1238 }
1239
1240 Value *Op = I.getOperand(i);
1241 if (!isa<MetadataAsValue>(Op)) {
1242 FindType(Op->getType());
1243 }
1244 }
1245
1246 FindType(I.getType());
1247 continue;
1248 }
1249
David Neto862b7d82018-06-14 18:48:37 -04001250 CallInst *Call = dyn_cast<CallInst>(&I);
1251
1252 if (Call && Call->getCalledFunction()->getName().startswith(
Alan Baker202c8c72018-08-13 13:47:44 -04001253 clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001254 // This is a fake call representing access to a resource variable.
1255 // We handle that elsewhere.
1256 continue;
1257 }
1258
Alan Baker202c8c72018-08-13 13:47:44 -04001259 if (Call && Call->getCalledFunction()->getName().startswith(
1260 clspv::WorkgroupAccessorFunction())) {
1261 // This is a fake call representing access to a workgroup variable.
1262 // We handle that elsewhere.
1263 continue;
1264 }
1265
David Neto22f144c2017-06-12 14:26:21 -04001266 // Work through the operands of the instruction.
1267 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1268 Value *const Op = I.getOperand(i);
1269 // If any of the operands is a constant, find the type!
1270 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1271 FindType(Op->getType());
1272 }
1273 }
1274
1275 for (Use &Op : I.operands()) {
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001276 if (isa<CallInst>(&I)) {
David Neto22f144c2017-06-12 14:26:21 -04001277 // Avoid to check call instruction's type.
1278 break;
1279 }
Alan Baker202c8c72018-08-13 13:47:44 -04001280 if (CallInst *OpCall = dyn_cast<CallInst>(Op)) {
1281 if (OpCall && OpCall->getCalledFunction()->getName().startswith(
1282 clspv::WorkgroupAccessorFunction())) {
1283 // This is a fake call representing access to a workgroup variable.
1284 // We handle that elsewhere.
1285 continue;
1286 }
1287 }
David Neto22f144c2017-06-12 14:26:21 -04001288 if (!isa<MetadataAsValue>(&Op)) {
1289 FindType(Op->getType());
1290 continue;
1291 }
1292 }
1293
David Neto22f144c2017-06-12 14:26:21 -04001294 // We don't want to track the type of this call as we are going to replace
1295 // it.
David Neto862b7d82018-06-14 18:48:37 -04001296 if (Call && ("clspv.sampler.var.literal" ==
David Neto22f144c2017-06-12 14:26:21 -04001297 Call->getCalledFunction()->getName())) {
1298 continue;
1299 }
1300
1301 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1302 // If gep's base operand has ModuleScopePrivate address space, make gep
1303 // return ModuleScopePrivate address space.
1304 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate) {
1305 // Add pointer type with private address space for global constant to
1306 // type list.
1307 Type *EleTy = I.getType()->getPointerElementType();
1308 Type *NewPTy =
1309 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1310
1311 FindType(NewPTy);
1312 continue;
1313 }
1314 }
1315
1316 FindType(I.getType());
1317 }
1318 }
1319}
1320
David Neto862b7d82018-06-14 18:48:37 -04001321void SPIRVProducerPass::FindTypesForSamplerMap(Module &M) {
1322 // If we are using a sampler map, find the type of the sampler.
1323 if (M.getFunction("clspv.sampler.var.literal") ||
1324 0 < getSamplerMap().size()) {
1325 auto SamplerStructTy = M.getTypeByName("opencl.sampler_t");
1326 if (!SamplerStructTy) {
1327 SamplerStructTy = StructType::create(M.getContext(), "opencl.sampler_t");
1328 }
1329
1330 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
1331
1332 FindType(SamplerTy);
1333 }
1334}
1335
1336void SPIRVProducerPass::FindTypesForResourceVars(Module &M) {
1337 // Record types so they are generated.
1338 TypesNeedingLayout.reset();
1339 StructTypesNeedingBlock.reset();
1340
1341 // To match older clspv codegen, generate the float type first if required
1342 // for images.
1343 for (const auto *info : ModuleOrderedResourceVars) {
1344 if (info->arg_kind == clspv::ArgKind::ReadOnlyImage ||
1345 info->arg_kind == clspv::ArgKind::WriteOnlyImage) {
1346 // We need "float" for the sampled component type.
1347 FindType(Type::getFloatTy(M.getContext()));
1348 // We only need to find it once.
1349 break;
1350 }
1351 }
1352
1353 for (const auto *info : ModuleOrderedResourceVars) {
1354 Type *type = info->var_fn->getReturnType();
1355
1356 switch (info->arg_kind) {
1357 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04001358 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04001359 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1360 StructTypesNeedingBlock.insert(sty);
1361 } else {
1362 errs() << *type << "\n";
1363 llvm_unreachable("Buffer arguments must map to structures!");
1364 }
1365 break;
1366 case clspv::ArgKind::Pod:
1367 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1368 StructTypesNeedingBlock.insert(sty);
1369 } else {
1370 errs() << *type << "\n";
1371 llvm_unreachable("POD arguments must map to structures!");
1372 }
1373 break;
1374 case clspv::ArgKind::ReadOnlyImage:
1375 case clspv::ArgKind::WriteOnlyImage:
1376 case clspv::ArgKind::Sampler:
1377 // Sampler and image types map to the pointee type but
1378 // in the uniform constant address space.
1379 type = PointerType::get(type->getPointerElementType(),
1380 clspv::AddressSpace::UniformConstant);
1381 break;
1382 default:
1383 break;
1384 }
1385
1386 // The converted type is the type of the OpVariable we will generate.
1387 // If the pointee type is an array of size zero, FindType will convert it
1388 // to a runtime array.
1389 FindType(type);
1390 }
1391
1392 // Traverse the arrays and structures underneath each Block, and
1393 // mark them as needing layout.
1394 std::vector<Type *> work_list(StructTypesNeedingBlock.begin(),
1395 StructTypesNeedingBlock.end());
1396 while (!work_list.empty()) {
1397 Type *type = work_list.back();
1398 work_list.pop_back();
1399 TypesNeedingLayout.insert(type);
1400 switch (type->getTypeID()) {
1401 case Type::ArrayTyID:
1402 work_list.push_back(type->getArrayElementType());
1403 if (!Hack_generate_runtime_array_stride_early) {
1404 // Remember this array type for deferred decoration.
1405 TypesNeedingArrayStride.insert(type);
1406 }
1407 break;
1408 case Type::StructTyID:
1409 for (auto *elem_ty : cast<StructType>(type)->elements()) {
1410 work_list.push_back(elem_ty);
1411 }
1412 default:
1413 // This type and its contained types don't get layout.
1414 break;
1415 }
1416 }
1417}
1418
Alan Baker202c8c72018-08-13 13:47:44 -04001419void SPIRVProducerPass::FindWorkgroupVars(Module &M) {
1420 // The SpecId assignment for pointer-to-local arguments is recorded in
1421 // module-level metadata. Translate that information into local argument
1422 // information.
1423 NamedMDNode *nmd = M.getNamedMetadata(clspv::LocalSpecIdMetadataName());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001424 if (!nmd)
1425 return;
Alan Baker202c8c72018-08-13 13:47:44 -04001426 for (auto operand : nmd->operands()) {
1427 MDTuple *tuple = cast<MDTuple>(operand);
1428 ValueAsMetadata *fn_md = cast<ValueAsMetadata>(tuple->getOperand(0));
1429 Function *func = cast<Function>(fn_md->getValue());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001430 ConstantAsMetadata *arg_index_md =
1431 cast<ConstantAsMetadata>(tuple->getOperand(1));
1432 int arg_index = static_cast<int>(
1433 cast<ConstantInt>(arg_index_md->getValue())->getSExtValue());
1434 Argument *arg = &*(func->arg_begin() + arg_index);
Alan Baker202c8c72018-08-13 13:47:44 -04001435
1436 ConstantAsMetadata *spec_id_md =
1437 cast<ConstantAsMetadata>(tuple->getOperand(2));
alan-bakerb6b09dc2018-11-08 16:59:28 -05001438 int spec_id = static_cast<int>(
1439 cast<ConstantInt>(spec_id_md->getValue())->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04001440
1441 max_local_spec_id_ = std::max(max_local_spec_id_, spec_id + 1);
1442 LocalArgSpecIds[arg] = spec_id;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001443 if (LocalSpecIdInfoMap.count(spec_id))
1444 continue;
Alan Baker202c8c72018-08-13 13:47:44 -04001445
1446 // We haven't seen this SpecId yet, so generate the LocalArgInfo for it.
1447 LocalArgInfo info{nextID, arg->getType()->getPointerElementType(),
1448 nextID + 1, nextID + 2,
1449 nextID + 3, spec_id};
1450 LocalSpecIdInfoMap[spec_id] = info;
1451 nextID += 4;
1452
1453 // Ensure the types necessary for this argument get generated.
1454 Type *IdxTy = Type::getInt32Ty(M.getContext());
1455 FindConstant(ConstantInt::get(IdxTy, 0));
1456 FindType(IdxTy);
1457 FindType(arg->getType());
1458 }
1459}
1460
David Neto22f144c2017-06-12 14:26:21 -04001461void SPIRVProducerPass::FindType(Type *Ty) {
1462 TypeList &TyList = getTypeList();
1463
1464 if (0 != TyList.idFor(Ty)) {
1465 return;
1466 }
1467
1468 if (Ty->isPointerTy()) {
1469 auto AddrSpace = Ty->getPointerAddressSpace();
1470 if ((AddressSpace::Constant == AddrSpace) ||
1471 (AddressSpace::Global == AddrSpace)) {
1472 auto PointeeTy = Ty->getPointerElementType();
1473
1474 if (PointeeTy->isStructTy() &&
1475 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1476 FindType(PointeeTy);
1477 auto ActualPointerTy =
1478 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1479 FindType(ActualPointerTy);
1480 return;
1481 }
1482 }
1483 }
1484
David Neto862b7d82018-06-14 18:48:37 -04001485 // By convention, LLVM array type with 0 elements will map to
1486 // OpTypeRuntimeArray. Otherwise, it will map to OpTypeArray, which
1487 // has a constant number of elements. We need to support type of the
1488 // constant.
1489 if (auto *arrayTy = dyn_cast<ArrayType>(Ty)) {
1490 if (arrayTy->getNumElements() > 0) {
1491 LLVMContext &Context = Ty->getContext();
1492 FindType(Type::getInt32Ty(Context));
1493 }
David Neto22f144c2017-06-12 14:26:21 -04001494 }
1495
1496 for (Type *SubTy : Ty->subtypes()) {
1497 FindType(SubTy);
1498 }
1499
1500 TyList.insert(Ty);
1501}
1502
1503void SPIRVProducerPass::FindConstantPerGlobalVar(GlobalVariable &GV) {
1504 // If the global variable has a (non undef) initializer.
1505 if (GV.hasInitializer() && !isa<UndefValue>(GV.getInitializer())) {
David Neto862b7d82018-06-14 18:48:37 -04001506 // Generate the constant if it's not the initializer to a module scope
1507 // constant that we will expect in a storage buffer.
1508 const bool module_scope_constant_external_init =
1509 (GV.getType()->getPointerAddressSpace() == AddressSpace::Constant) &&
1510 clspv::Option::ModuleConstantsInStorageBuffer();
1511 if (!module_scope_constant_external_init) {
1512 FindConstant(GV.getInitializer());
1513 }
David Neto22f144c2017-06-12 14:26:21 -04001514 }
1515}
1516
1517void SPIRVProducerPass::FindConstantPerFunc(Function &F) {
1518 // Investigate constants in function body.
1519 for (BasicBlock &BB : F) {
1520 for (Instruction &I : BB) {
David Neto862b7d82018-06-14 18:48:37 -04001521 if (auto *call = dyn_cast<CallInst>(&I)) {
1522 auto name = call->getCalledFunction()->getName();
1523 if (name == "clspv.sampler.var.literal") {
1524 // We've handled these constants elsewhere, so skip it.
1525 continue;
1526 }
Alan Baker202c8c72018-08-13 13:47:44 -04001527 if (name.startswith(clspv::ResourceAccessorFunction())) {
1528 continue;
1529 }
1530 if (name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001531 continue;
1532 }
David Neto22f144c2017-06-12 14:26:21 -04001533 }
1534
1535 if (isa<AllocaInst>(I)) {
1536 // Alloca instruction has constant for the number of element. Ignore it.
1537 continue;
1538 } else if (isa<ShuffleVectorInst>(I)) {
1539 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1540 // Ignore constant for mask of shuffle vector instruction.
1541 if (i == 2) {
1542 continue;
1543 }
1544
1545 if (isa<Constant>(I.getOperand(i)) &&
1546 !isa<GlobalValue>(I.getOperand(i))) {
1547 FindConstant(I.getOperand(i));
1548 }
1549 }
1550
1551 continue;
1552 } else if (isa<InsertElementInst>(I)) {
1553 // Handle InsertElement with <4 x i8> specially.
1554 Type *CompositeTy = I.getOperand(0)->getType();
1555 if (is4xi8vec(CompositeTy)) {
1556 LLVMContext &Context = CompositeTy->getContext();
1557 if (isa<Constant>(I.getOperand(0))) {
1558 FindConstant(I.getOperand(0));
1559 }
1560
1561 if (isa<Constant>(I.getOperand(1))) {
1562 FindConstant(I.getOperand(1));
1563 }
1564
1565 // Add mask constant 0xFF.
1566 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1567 FindConstant(CstFF);
1568
1569 // Add shift amount constant.
1570 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
1571 uint64_t Idx = CI->getZExtValue();
1572 Constant *CstShiftAmount =
1573 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1574 FindConstant(CstShiftAmount);
1575 }
1576
1577 continue;
1578 }
1579
1580 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1581 // Ignore constant for index of InsertElement instruction.
1582 if (i == 2) {
1583 continue;
1584 }
1585
1586 if (isa<Constant>(I.getOperand(i)) &&
1587 !isa<GlobalValue>(I.getOperand(i))) {
1588 FindConstant(I.getOperand(i));
1589 }
1590 }
1591
1592 continue;
1593 } else if (isa<ExtractElementInst>(I)) {
1594 // Handle ExtractElement with <4 x i8> specially.
1595 Type *CompositeTy = I.getOperand(0)->getType();
1596 if (is4xi8vec(CompositeTy)) {
1597 LLVMContext &Context = CompositeTy->getContext();
1598 if (isa<Constant>(I.getOperand(0))) {
1599 FindConstant(I.getOperand(0));
1600 }
1601
1602 // Add mask constant 0xFF.
1603 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1604 FindConstant(CstFF);
1605
1606 // Add shift amount constant.
1607 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1608 uint64_t Idx = CI->getZExtValue();
1609 Constant *CstShiftAmount =
1610 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1611 FindConstant(CstShiftAmount);
1612 } else {
1613 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
1614 FindConstant(Cst8);
1615 }
1616
1617 continue;
1618 }
1619
1620 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1621 // Ignore constant for index of ExtractElement instruction.
1622 if (i == 1) {
1623 continue;
1624 }
1625
1626 if (isa<Constant>(I.getOperand(i)) &&
1627 !isa<GlobalValue>(I.getOperand(i))) {
1628 FindConstant(I.getOperand(i));
1629 }
1630 }
1631
1632 continue;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001633 } else if ((Instruction::Xor == I.getOpcode()) &&
1634 I.getType()->isIntegerTy(1)) {
1635 // We special case for Xor where the type is i1 and one of the arguments
1636 // is a constant 1 (true), this is an OpLogicalNot in SPIR-V, and we
1637 // don't need the constant
David Neto22f144c2017-06-12 14:26:21 -04001638 bool foundConstantTrue = false;
1639 for (Use &Op : I.operands()) {
1640 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1641 auto CI = cast<ConstantInt>(Op);
1642
1643 if (CI->isZero() || foundConstantTrue) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05001644 // If we already found the true constant, we might (probably only
1645 // on -O0) have an OpLogicalNot which is taking a constant
1646 // argument, so discover it anyway.
David Neto22f144c2017-06-12 14:26:21 -04001647 FindConstant(Op);
1648 } else {
1649 foundConstantTrue = true;
1650 }
1651 }
1652 }
1653
1654 continue;
David Netod2de94a2017-08-28 17:27:47 -04001655 } else if (isa<TruncInst>(I)) {
alan-bakerb39c8262019-03-08 14:03:37 -05001656 // Special case if i8 is not generally handled.
1657 if (!clspv::Option::Int8Support()) {
1658 // For truncation to i8 we mask against 255.
1659 Type *ToTy = I.getType();
1660 if (8u == ToTy->getPrimitiveSizeInBits()) {
1661 LLVMContext &Context = ToTy->getContext();
1662 Constant *Cst255 =
1663 ConstantInt::get(Type::getInt32Ty(Context), 0xff);
1664 FindConstant(Cst255);
1665 }
David Netod2de94a2017-08-28 17:27:47 -04001666 }
Neil Henning39672102017-09-29 14:33:13 +01001667 } else if (isa<AtomicRMWInst>(I)) {
1668 LLVMContext &Context = I.getContext();
1669
1670 FindConstant(
1671 ConstantInt::get(Type::getInt32Ty(Context), spv::ScopeDevice));
1672 FindConstant(ConstantInt::get(
1673 Type::getInt32Ty(Context),
1674 spv::MemorySemanticsUniformMemoryMask |
1675 spv::MemorySemanticsSequentiallyConsistentMask));
David Neto22f144c2017-06-12 14:26:21 -04001676 }
1677
1678 for (Use &Op : I.operands()) {
1679 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1680 FindConstant(Op);
1681 }
1682 }
1683 }
1684 }
1685}
1686
1687void SPIRVProducerPass::FindConstant(Value *V) {
David Neto22f144c2017-06-12 14:26:21 -04001688 ValueList &CstList = getConstantList();
1689
David Netofb9a7972017-08-25 17:08:24 -04001690 // If V is already tracked, ignore it.
1691 if (0 != CstList.idFor(V)) {
David Neto22f144c2017-06-12 14:26:21 -04001692 return;
1693 }
1694
David Neto862b7d82018-06-14 18:48:37 -04001695 if (isa<GlobalValue>(V) && clspv::Option::ModuleConstantsInStorageBuffer()) {
1696 return;
1697 }
1698
David Neto22f144c2017-06-12 14:26:21 -04001699 Constant *Cst = cast<Constant>(V);
David Neto862b7d82018-06-14 18:48:37 -04001700 Type *CstTy = Cst->getType();
David Neto22f144c2017-06-12 14:26:21 -04001701
1702 // Handle constant with <4 x i8> type specially.
David Neto22f144c2017-06-12 14:26:21 -04001703 if (is4xi8vec(CstTy)) {
1704 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001705 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001706 }
1707 }
1708
1709 if (Cst->getNumOperands()) {
1710 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end(); I != E;
1711 ++I) {
1712 FindConstant(*I);
1713 }
1714
David Netofb9a7972017-08-25 17:08:24 -04001715 CstList.insert(Cst);
David Neto22f144c2017-06-12 14:26:21 -04001716 return;
1717 } else if (const ConstantDataSequential *CDS =
1718 dyn_cast<ConstantDataSequential>(Cst)) {
1719 // Add constants for each element to constant list.
1720 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
1721 Constant *EleCst = CDS->getElementAsConstant(i);
1722 FindConstant(EleCst);
1723 }
1724 }
1725
1726 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001727 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001728 }
1729}
1730
1731spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1732 switch (AddrSpace) {
1733 default:
1734 llvm_unreachable("Unsupported OpenCL address space");
1735 case AddressSpace::Private:
1736 return spv::StorageClassFunction;
1737 case AddressSpace::Global:
David Neto22f144c2017-06-12 14:26:21 -04001738 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001739 case AddressSpace::Constant:
1740 return clspv::Option::ConstantArgsInUniformBuffer()
1741 ? spv::StorageClassUniform
1742 : spv::StorageClassStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -04001743 case AddressSpace::Input:
1744 return spv::StorageClassInput;
1745 case AddressSpace::Local:
1746 return spv::StorageClassWorkgroup;
1747 case AddressSpace::UniformConstant:
1748 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001749 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001750 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001751 case AddressSpace::ModuleScopePrivate:
1752 return spv::StorageClassPrivate;
1753 }
1754}
1755
David Neto862b7d82018-06-14 18:48:37 -04001756spv::StorageClass
1757SPIRVProducerPass::GetStorageClassForArgKind(clspv::ArgKind arg_kind) const {
1758 switch (arg_kind) {
1759 case clspv::ArgKind::Buffer:
1760 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001761 case clspv::ArgKind::BufferUBO:
1762 return spv::StorageClassUniform;
David Neto862b7d82018-06-14 18:48:37 -04001763 case clspv::ArgKind::Pod:
1764 return clspv::Option::PodArgsInUniformBuffer()
1765 ? spv::StorageClassUniform
1766 : spv::StorageClassStorageBuffer;
1767 case clspv::ArgKind::Local:
1768 return spv::StorageClassWorkgroup;
1769 case clspv::ArgKind::ReadOnlyImage:
1770 case clspv::ArgKind::WriteOnlyImage:
1771 case clspv::ArgKind::Sampler:
1772 return spv::StorageClassUniformConstant;
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001773 default:
1774 llvm_unreachable("Unsupported storage class for argument kind");
David Neto862b7d82018-06-14 18:48:37 -04001775 }
1776}
1777
David Neto22f144c2017-06-12 14:26:21 -04001778spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1779 return StringSwitch<spv::BuiltIn>(Name)
1780 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1781 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1782 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1783 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1784 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
1785 .Default(spv::BuiltInMax);
1786}
1787
1788void SPIRVProducerPass::GenerateExtInstImport() {
1789 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1790 uint32_t &ExtInstImportID = getOpExtInstImportID();
1791
1792 //
1793 // Generate OpExtInstImport.
1794 //
1795 // Ops[0] ... Ops[n] = Name (Literal String)
David Neto22f144c2017-06-12 14:26:21 -04001796 ExtInstImportID = nextID;
David Neto87846742018-04-11 17:36:22 -04001797 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpExtInstImport, nextID++,
1798 MkString("GLSL.std.450")));
David Neto22f144c2017-06-12 14:26:21 -04001799}
1800
alan-bakerb6b09dc2018-11-08 16:59:28 -05001801void SPIRVProducerPass::GenerateSPIRVTypes(LLVMContext &Context,
1802 Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04001803 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1804 ValueMapType &VMap = getValueMap();
1805 ValueMapType &AllocatedVMap = getAllocatedValueMap();
Alan Bakerfcda9482018-10-02 17:09:59 -04001806 const auto &DL = module.getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04001807
1808 // Map for OpTypeRuntimeArray. If argument has pointer type, 2 spirv type
1809 // instructions are generated. They are OpTypePointer and OpTypeRuntimeArray.
1810 DenseMap<Type *, uint32_t> OpRuntimeTyMap;
1811
1812 for (Type *Ty : getTypeList()) {
1813 // Update TypeMap with nextID for reference later.
1814 TypeMap[Ty] = nextID;
1815
1816 switch (Ty->getTypeID()) {
1817 default: {
1818 Ty->print(errs());
1819 llvm_unreachable("Unsupported type???");
1820 break;
1821 }
1822 case Type::MetadataTyID:
1823 case Type::LabelTyID: {
1824 // Ignore these types.
1825 break;
1826 }
1827 case Type::PointerTyID: {
1828 PointerType *PTy = cast<PointerType>(Ty);
1829 unsigned AddrSpace = PTy->getAddressSpace();
1830
1831 // For the purposes of our Vulkan SPIR-V type system, constant and global
1832 // are conflated.
1833 bool UseExistingOpTypePointer = false;
1834 if (AddressSpace::Constant == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001835 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1836 AddrSpace = AddressSpace::Global;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001837 // Check to see if we already created this type (for instance, if we
1838 // had a constant <type>* and a global <type>*, the type would be
1839 // created by one of these types, and shared by both).
Alan Bakerfcda9482018-10-02 17:09:59 -04001840 auto GlobalTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1841 if (0 < TypeMap.count(GlobalTy)) {
1842 TypeMap[PTy] = TypeMap[GlobalTy];
1843 UseExistingOpTypePointer = true;
1844 break;
1845 }
David Neto22f144c2017-06-12 14:26:21 -04001846 }
1847 } else if (AddressSpace::Global == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001848 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1849 AddrSpace = AddressSpace::Constant;
David Neto22f144c2017-06-12 14:26:21 -04001850
alan-bakerb6b09dc2018-11-08 16:59:28 -05001851 // Check to see if we already created this type (for instance, if we
1852 // had a constant <type>* and a global <type>*, the type would be
1853 // created by one of these types, and shared by both).
1854 auto ConstantTy =
1855 PTy->getPointerElementType()->getPointerTo(AddrSpace);
Alan Bakerfcda9482018-10-02 17:09:59 -04001856 if (0 < TypeMap.count(ConstantTy)) {
1857 TypeMap[PTy] = TypeMap[ConstantTy];
1858 UseExistingOpTypePointer = true;
1859 }
David Neto22f144c2017-06-12 14:26:21 -04001860 }
1861 }
1862
David Neto862b7d82018-06-14 18:48:37 -04001863 const bool HasArgUser = true;
David Neto22f144c2017-06-12 14:26:21 -04001864
David Neto862b7d82018-06-14 18:48:37 -04001865 if (HasArgUser && !UseExistingOpTypePointer) {
David Neto22f144c2017-06-12 14:26:21 -04001866 //
1867 // Generate OpTypePointer.
1868 //
1869
1870 // OpTypePointer
1871 // Ops[0] = Storage Class
1872 // Ops[1] = Element Type ID
1873 SPIRVOperandList Ops;
1874
David Neto257c3892018-04-11 13:19:45 -04001875 Ops << MkNum(GetStorageClass(AddrSpace))
1876 << MkId(lookupType(PTy->getElementType()));
David Neto22f144c2017-06-12 14:26:21 -04001877
David Neto87846742018-04-11 17:36:22 -04001878 auto *Inst = new SPIRVInstruction(spv::OpTypePointer, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001879 SPIRVInstList.push_back(Inst);
1880 }
David Neto22f144c2017-06-12 14:26:21 -04001881 break;
1882 }
1883 case Type::StructTyID: {
David Neto22f144c2017-06-12 14:26:21 -04001884 StructType *STy = cast<StructType>(Ty);
1885
1886 // Handle sampler type.
1887 if (STy->isOpaque()) {
1888 if (STy->getName().equals("opencl.sampler_t")) {
1889 //
1890 // Generate OpTypeSampler
1891 //
1892 // Empty Ops.
1893 SPIRVOperandList Ops;
1894
David Neto87846742018-04-11 17:36:22 -04001895 auto *Inst = new SPIRVInstruction(spv::OpTypeSampler, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001896 SPIRVInstList.push_back(Inst);
1897 break;
1898 } else if (STy->getName().equals("opencl.image2d_ro_t") ||
1899 STy->getName().equals("opencl.image2d_wo_t") ||
1900 STy->getName().equals("opencl.image3d_ro_t") ||
1901 STy->getName().equals("opencl.image3d_wo_t")) {
1902 //
1903 // Generate OpTypeImage
1904 //
1905 // Ops[0] = Sampled Type ID
1906 // Ops[1] = Dim ID
1907 // Ops[2] = Depth (Literal Number)
1908 // Ops[3] = Arrayed (Literal Number)
1909 // Ops[4] = MS (Literal Number)
1910 // Ops[5] = Sampled (Literal Number)
1911 // Ops[6] = Image Format ID
1912 //
1913 SPIRVOperandList Ops;
1914
1915 // TODO: Changed Sampled Type according to situations.
1916 uint32_t SampledTyID = lookupType(Type::getFloatTy(Context));
David Neto257c3892018-04-11 13:19:45 -04001917 Ops << MkId(SampledTyID);
David Neto22f144c2017-06-12 14:26:21 -04001918
1919 spv::Dim DimID = spv::Dim2D;
1920 if (STy->getName().equals("opencl.image3d_ro_t") ||
1921 STy->getName().equals("opencl.image3d_wo_t")) {
1922 DimID = spv::Dim3D;
1923 }
David Neto257c3892018-04-11 13:19:45 -04001924 Ops << MkNum(DimID);
David Neto22f144c2017-06-12 14:26:21 -04001925
1926 // TODO: Set up Depth.
David Neto257c3892018-04-11 13:19:45 -04001927 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001928
1929 // TODO: Set up Arrayed.
David Neto257c3892018-04-11 13:19:45 -04001930 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001931
1932 // TODO: Set up MS.
David Neto257c3892018-04-11 13:19:45 -04001933 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001934
1935 // TODO: Set up Sampled.
1936 //
1937 // From Spec
1938 //
1939 // 0 indicates this is only known at run time, not at compile time
1940 // 1 indicates will be used with sampler
1941 // 2 indicates will be used without a sampler (a storage image)
1942 uint32_t Sampled = 1;
1943 if (STy->getName().equals("opencl.image2d_wo_t") ||
1944 STy->getName().equals("opencl.image3d_wo_t")) {
1945 Sampled = 2;
1946 }
David Neto257c3892018-04-11 13:19:45 -04001947 Ops << MkNum(Sampled);
David Neto22f144c2017-06-12 14:26:21 -04001948
1949 // TODO: Set up Image Format.
David Neto257c3892018-04-11 13:19:45 -04001950 Ops << MkNum(spv::ImageFormatUnknown);
David Neto22f144c2017-06-12 14:26:21 -04001951
David Neto87846742018-04-11 17:36:22 -04001952 auto *Inst = new SPIRVInstruction(spv::OpTypeImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001953 SPIRVInstList.push_back(Inst);
1954 break;
1955 }
1956 }
1957
1958 //
1959 // Generate OpTypeStruct
1960 //
1961 // Ops[0] ... Ops[n] = Member IDs
1962 SPIRVOperandList Ops;
1963
1964 for (auto *EleTy : STy->elements()) {
David Neto862b7d82018-06-14 18:48:37 -04001965 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04001966 }
1967
David Neto22f144c2017-06-12 14:26:21 -04001968 uint32_t STyID = nextID;
1969
alan-bakerb6b09dc2018-11-08 16:59:28 -05001970 auto *Inst = new SPIRVInstruction(spv::OpTypeStruct, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001971 SPIRVInstList.push_back(Inst);
1972
1973 // Generate OpMemberDecorate.
1974 auto DecoInsertPoint =
1975 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
1976 [](SPIRVInstruction *Inst) -> bool {
1977 return Inst->getOpcode() != spv::OpDecorate &&
1978 Inst->getOpcode() != spv::OpMemberDecorate &&
1979 Inst->getOpcode() != spv::OpExtInstImport;
1980 });
1981
David Netoc463b372017-08-10 15:32:21 -04001982 const auto StructLayout = DL.getStructLayout(STy);
Alan Bakerfcda9482018-10-02 17:09:59 -04001983 // Search for the correct offsets if this type was remapped.
1984 std::vector<uint32_t> *offsets = nullptr;
1985 auto iter = RemappedUBOTypeOffsets.find(STy);
1986 if (iter != RemappedUBOTypeOffsets.end()) {
1987 offsets = &iter->second;
1988 }
David Netoc463b372017-08-10 15:32:21 -04001989
David Neto862b7d82018-06-14 18:48:37 -04001990 // #error TODO(dneto): Only do this if in TypesNeedingLayout.
David Neto22f144c2017-06-12 14:26:21 -04001991 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
1992 MemberIdx++) {
1993 // Ops[0] = Structure Type ID
1994 // Ops[1] = Member Index(Literal Number)
1995 // Ops[2] = Decoration (Offset)
1996 // Ops[3] = Byte Offset (Literal Number)
1997 Ops.clear();
1998
David Neto257c3892018-04-11 13:19:45 -04001999 Ops << MkId(STyID) << MkNum(MemberIdx) << MkNum(spv::DecorationOffset);
David Neto22f144c2017-06-12 14:26:21 -04002000
alan-bakerb6b09dc2018-11-08 16:59:28 -05002001 auto ByteOffset =
2002 static_cast<uint32_t>(StructLayout->getElementOffset(MemberIdx));
Alan Bakerfcda9482018-10-02 17:09:59 -04002003 if (offsets) {
2004 ByteOffset = (*offsets)[MemberIdx];
2005 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05002006 // const auto ByteOffset =
Alan Bakerfcda9482018-10-02 17:09:59 -04002007 // uint32_t(StructLayout->getElementOffset(MemberIdx));
David Neto257c3892018-04-11 13:19:45 -04002008 Ops << MkNum(ByteOffset);
David Neto22f144c2017-06-12 14:26:21 -04002009
David Neto87846742018-04-11 17:36:22 -04002010 auto *DecoInst = new SPIRVInstruction(spv::OpMemberDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002011 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04002012 }
2013
2014 // Generate OpDecorate.
David Neto862b7d82018-06-14 18:48:37 -04002015 if (StructTypesNeedingBlock.idFor(STy)) {
2016 Ops.clear();
2017 // Use Block decorations with StorageBuffer storage class.
2018 Ops << MkId(STyID) << MkNum(spv::DecorationBlock);
David Neto22f144c2017-06-12 14:26:21 -04002019
David Neto862b7d82018-06-14 18:48:37 -04002020 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
2021 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04002022 }
2023 break;
2024 }
2025 case Type::IntegerTyID: {
2026 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
2027
2028 if (BitWidth == 1) {
David Neto87846742018-04-11 17:36:22 -04002029 auto *Inst = new SPIRVInstruction(spv::OpTypeBool, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04002030 SPIRVInstList.push_back(Inst);
2031 } else {
alan-bakerb39c8262019-03-08 14:03:37 -05002032 if (!clspv::Option::Int8Support()) {
2033 // i8 is added to TypeMap as i32.
2034 // No matter what LLVM type is requested first, always alias the
2035 // second one's SPIR-V type to be the same as the one we generated
2036 // first.
2037 unsigned aliasToWidth = 0;
2038 if (BitWidth == 8) {
2039 aliasToWidth = 32;
2040 BitWidth = 32;
2041 } else if (BitWidth == 32) {
2042 aliasToWidth = 8;
2043 }
2044 if (aliasToWidth) {
2045 Type *otherType = Type::getIntNTy(Ty->getContext(), aliasToWidth);
2046 auto where = TypeMap.find(otherType);
2047 if (where == TypeMap.end()) {
2048 // Go ahead and make it, but also map the other type to it.
2049 TypeMap[otherType] = nextID;
2050 } else {
2051 // Alias this SPIR-V type the existing type.
2052 TypeMap[Ty] = where->second;
2053 break;
2054 }
David Neto391aeb12017-08-26 15:51:58 -04002055 }
David Neto22f144c2017-06-12 14:26:21 -04002056 }
2057
David Neto257c3892018-04-11 13:19:45 -04002058 SPIRVOperandList Ops;
2059 Ops << MkNum(BitWidth) << MkNum(0 /* not signed */);
David Neto22f144c2017-06-12 14:26:21 -04002060
2061 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002062 new SPIRVInstruction(spv::OpTypeInt, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002063 }
2064 break;
2065 }
2066 case Type::HalfTyID:
2067 case Type::FloatTyID:
2068 case Type::DoubleTyID: {
2069 SPIRVOperand *WidthOp = new SPIRVOperand(
2070 SPIRVOperandType::LITERAL_INTEGER, Ty->getPrimitiveSizeInBits());
2071
2072 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002073 new SPIRVInstruction(spv::OpTypeFloat, nextID++, WidthOp));
David Neto22f144c2017-06-12 14:26:21 -04002074 break;
2075 }
2076 case Type::ArrayTyID: {
David Neto22f144c2017-06-12 14:26:21 -04002077 ArrayType *ArrTy = cast<ArrayType>(Ty);
David Neto862b7d82018-06-14 18:48:37 -04002078 const uint64_t Length = ArrTy->getArrayNumElements();
2079 if (Length == 0) {
2080 // By convention, map it to a RuntimeArray.
David Neto22f144c2017-06-12 14:26:21 -04002081
David Neto862b7d82018-06-14 18:48:37 -04002082 // Only generate the type once.
2083 // TODO(dneto): Can it ever be generated more than once?
2084 // Doesn't LLVM type uniqueness guarantee we'll only see this
2085 // once?
2086 Type *EleTy = ArrTy->getArrayElementType();
2087 if (OpRuntimeTyMap.count(EleTy) == 0) {
2088 uint32_t OpTypeRuntimeArrayID = nextID;
2089 OpRuntimeTyMap[Ty] = nextID;
David Neto22f144c2017-06-12 14:26:21 -04002090
David Neto862b7d82018-06-14 18:48:37 -04002091 //
2092 // Generate OpTypeRuntimeArray.
2093 //
David Neto22f144c2017-06-12 14:26:21 -04002094
David Neto862b7d82018-06-14 18:48:37 -04002095 // OpTypeRuntimeArray
2096 // Ops[0] = Element Type ID
2097 SPIRVOperandList Ops;
2098 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04002099
David Neto862b7d82018-06-14 18:48:37 -04002100 SPIRVInstList.push_back(
2101 new SPIRVInstruction(spv::OpTypeRuntimeArray, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002102
David Neto862b7d82018-06-14 18:48:37 -04002103 if (Hack_generate_runtime_array_stride_early) {
2104 // Generate OpDecorate.
2105 auto DecoInsertPoint = std::find_if(
2106 SPIRVInstList.begin(), SPIRVInstList.end(),
2107 [](SPIRVInstruction *Inst) -> bool {
2108 return Inst->getOpcode() != spv::OpDecorate &&
2109 Inst->getOpcode() != spv::OpMemberDecorate &&
2110 Inst->getOpcode() != spv::OpExtInstImport;
2111 });
David Neto22f144c2017-06-12 14:26:21 -04002112
David Neto862b7d82018-06-14 18:48:37 -04002113 // Ops[0] = Target ID
2114 // Ops[1] = Decoration (ArrayStride)
2115 // Ops[2] = Stride Number(Literal Number)
2116 Ops.clear();
David Neto85082642018-03-24 06:55:20 -07002117
David Neto862b7d82018-06-14 18:48:37 -04002118 Ops << MkId(OpTypeRuntimeArrayID)
2119 << MkNum(spv::DecorationArrayStride)
Alan Bakerfcda9482018-10-02 17:09:59 -04002120 << MkNum(static_cast<uint32_t>(GetTypeAllocSize(EleTy, DL)));
David Neto22f144c2017-06-12 14:26:21 -04002121
David Neto862b7d82018-06-14 18:48:37 -04002122 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
2123 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
2124 }
2125 }
David Neto22f144c2017-06-12 14:26:21 -04002126
David Neto862b7d82018-06-14 18:48:37 -04002127 } else {
David Neto22f144c2017-06-12 14:26:21 -04002128
David Neto862b7d82018-06-14 18:48:37 -04002129 //
2130 // Generate OpConstant and OpTypeArray.
2131 //
2132
2133 //
2134 // Generate OpConstant for array length.
2135 //
2136 // Ops[0] = Result Type ID
2137 // Ops[1] .. Ops[n] = Values LiteralNumber
2138 SPIRVOperandList Ops;
2139
2140 Type *LengthTy = Type::getInt32Ty(Context);
2141 uint32_t ResTyID = lookupType(LengthTy);
2142 Ops << MkId(ResTyID);
2143
2144 assert(Length < UINT32_MAX);
2145 Ops << MkNum(static_cast<uint32_t>(Length));
2146
2147 // Add constant for length to constant list.
2148 Constant *CstLength = ConstantInt::get(LengthTy, Length);
2149 AllocatedVMap[CstLength] = nextID;
2150 VMap[CstLength] = nextID;
2151 uint32_t LengthID = nextID;
2152
2153 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
2154 SPIRVInstList.push_back(CstInst);
2155
2156 // Remember to generate ArrayStride later
2157 getTypesNeedingArrayStride().insert(Ty);
2158
2159 //
2160 // Generate OpTypeArray.
2161 //
2162 // Ops[0] = Element Type ID
2163 // Ops[1] = Array Length Constant ID
2164 Ops.clear();
2165
2166 uint32_t EleTyID = lookupType(ArrTy->getElementType());
2167 Ops << MkId(EleTyID) << MkId(LengthID);
2168
2169 // Update TypeMap with nextID.
2170 TypeMap[Ty] = nextID;
2171
2172 auto *ArrayInst = new SPIRVInstruction(spv::OpTypeArray, nextID++, Ops);
2173 SPIRVInstList.push_back(ArrayInst);
2174 }
David Neto22f144c2017-06-12 14:26:21 -04002175 break;
2176 }
2177 case Type::VectorTyID: {
alan-bakerb39c8262019-03-08 14:03:37 -05002178 // <4 x i8> is changed to i32 if i8 is not generally supported.
2179 if (!clspv::Option::Int8Support() &&
2180 Ty->getVectorElementType() == Type::getInt8Ty(Context)) {
David Neto22f144c2017-06-12 14:26:21 -04002181 if (Ty->getVectorNumElements() == 4) {
2182 TypeMap[Ty] = lookupType(Ty->getVectorElementType());
2183 break;
2184 } else {
2185 Ty->print(errs());
2186 llvm_unreachable("Support above i8 vector type");
2187 }
2188 }
2189
2190 // Ops[0] = Component Type ID
2191 // Ops[1] = Component Count (Literal Number)
David Neto257c3892018-04-11 13:19:45 -04002192 SPIRVOperandList Ops;
2193 Ops << MkId(lookupType(Ty->getVectorElementType()))
2194 << MkNum(Ty->getVectorNumElements());
David Neto22f144c2017-06-12 14:26:21 -04002195
alan-bakerb6b09dc2018-11-08 16:59:28 -05002196 SPIRVInstruction *inst =
2197 new SPIRVInstruction(spv::OpTypeVector, nextID++, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002198 SPIRVInstList.push_back(inst);
David Neto22f144c2017-06-12 14:26:21 -04002199 break;
2200 }
2201 case Type::VoidTyID: {
David Neto87846742018-04-11 17:36:22 -04002202 auto *Inst = new SPIRVInstruction(spv::OpTypeVoid, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04002203 SPIRVInstList.push_back(Inst);
2204 break;
2205 }
2206 case Type::FunctionTyID: {
2207 // Generate SPIRV instruction for function type.
2208 FunctionType *FTy = cast<FunctionType>(Ty);
2209
2210 // Ops[0] = Return Type ID
2211 // Ops[1] ... Ops[n] = Parameter Type IDs
2212 SPIRVOperandList Ops;
2213
2214 // Find SPIRV instruction for return type
David Netoc6f3ab22018-04-06 18:02:31 -04002215 Ops << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04002216
2217 // Find SPIRV instructions for parameter types
2218 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
2219 // Find SPIRV instruction for parameter type.
2220 auto ParamTy = FTy->getParamType(k);
2221 if (ParamTy->isPointerTy()) {
2222 auto PointeeTy = ParamTy->getPointerElementType();
2223 if (PointeeTy->isStructTy() &&
2224 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
2225 ParamTy = PointeeTy;
2226 }
2227 }
2228
David Netoc6f3ab22018-04-06 18:02:31 -04002229 Ops << MkId(lookupType(ParamTy));
David Neto22f144c2017-06-12 14:26:21 -04002230 }
2231
David Neto87846742018-04-11 17:36:22 -04002232 auto *Inst = new SPIRVInstruction(spv::OpTypeFunction, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002233 SPIRVInstList.push_back(Inst);
2234 break;
2235 }
2236 }
2237 }
2238
2239 // Generate OpTypeSampledImage.
2240 TypeMapType &OpImageTypeMap = getImageTypeMap();
2241 for (auto &ImageType : OpImageTypeMap) {
2242 //
2243 // Generate OpTypeSampledImage.
2244 //
2245 // Ops[0] = Image Type ID
2246 //
2247 SPIRVOperandList Ops;
2248
2249 Type *ImgTy = ImageType.first;
David Netoc6f3ab22018-04-06 18:02:31 -04002250 Ops << MkId(TypeMap[ImgTy]);
David Neto22f144c2017-06-12 14:26:21 -04002251
2252 // Update OpImageTypeMap.
2253 ImageType.second = nextID;
2254
David Neto87846742018-04-11 17:36:22 -04002255 auto *Inst = new SPIRVInstruction(spv::OpTypeSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002256 SPIRVInstList.push_back(Inst);
2257 }
David Netoc6f3ab22018-04-06 18:02:31 -04002258
2259 // Generate types for pointer-to-local arguments.
Alan Baker202c8c72018-08-13 13:47:44 -04002260 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2261 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002262 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002263
2264 // Generate the spec constant.
2265 SPIRVOperandList Ops;
2266 Ops << MkId(lookupType(Type::getInt32Ty(Context))) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04002267 SPIRVInstList.push_back(
2268 new SPIRVInstruction(spv::OpSpecConstant, arg_info.array_size_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002269
2270 // Generate the array type.
2271 Ops.clear();
2272 // The element type must have been created.
2273 uint32_t elem_ty_id = lookupType(arg_info.elem_type);
2274 assert(elem_ty_id);
2275 Ops << MkId(elem_ty_id) << MkId(arg_info.array_size_id);
2276
2277 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002278 new SPIRVInstruction(spv::OpTypeArray, arg_info.array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002279
2280 Ops.clear();
2281 Ops << MkNum(spv::StorageClassWorkgroup) << MkId(arg_info.array_type_id);
David Neto87846742018-04-11 17:36:22 -04002282 SPIRVInstList.push_back(new SPIRVInstruction(
2283 spv::OpTypePointer, arg_info.ptr_array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002284 }
David Neto22f144c2017-06-12 14:26:21 -04002285}
2286
2287void SPIRVProducerPass::GenerateSPIRVConstants() {
2288 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2289 ValueMapType &VMap = getValueMap();
2290 ValueMapType &AllocatedVMap = getAllocatedValueMap();
2291 ValueList &CstList = getConstantList();
David Neto482550a2018-03-24 05:21:07 -07002292 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04002293
2294 for (uint32_t i = 0; i < CstList.size(); i++) {
David Netofb9a7972017-08-25 17:08:24 -04002295 // UniqueVector ids are 1-based.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002296 Constant *Cst = cast<Constant>(CstList[i + 1]);
David Neto22f144c2017-06-12 14:26:21 -04002297
2298 // OpTypeArray's constant was already generated.
David Netofb9a7972017-08-25 17:08:24 -04002299 if (AllocatedVMap.find_as(Cst) != AllocatedVMap.end()) {
David Neto22f144c2017-06-12 14:26:21 -04002300 continue;
2301 }
2302
David Netofb9a7972017-08-25 17:08:24 -04002303 // Set ValueMap with nextID for reference later.
David Neto22f144c2017-06-12 14:26:21 -04002304 VMap[Cst] = nextID;
2305
2306 //
2307 // Generate OpConstant.
2308 //
2309
2310 // Ops[0] = Result Type ID
2311 // Ops[1] .. Ops[n] = Values LiteralNumber
2312 SPIRVOperandList Ops;
2313
David Neto257c3892018-04-11 13:19:45 -04002314 Ops << MkId(lookupType(Cst->getType()));
David Neto22f144c2017-06-12 14:26:21 -04002315
2316 std::vector<uint32_t> LiteralNum;
David Neto22f144c2017-06-12 14:26:21 -04002317 spv::Op Opcode = spv::OpNop;
2318
2319 if (isa<UndefValue>(Cst)) {
2320 // Ops[0] = Result Type ID
David Netoc66b3352017-10-20 14:28:46 -04002321 Opcode = spv::OpUndef;
Alan Baker9bf93fb2018-08-28 16:59:26 -04002322 if (hack_undef && IsTypeNullable(Cst->getType())) {
2323 Opcode = spv::OpConstantNull;
David Netoc66b3352017-10-20 14:28:46 -04002324 }
David Neto22f144c2017-06-12 14:26:21 -04002325 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
2326 unsigned BitWidth = CI->getBitWidth();
2327 if (BitWidth == 1) {
2328 // If the bitwidth of constant is 1, generate OpConstantTrue or
2329 // OpConstantFalse.
2330 if (CI->getZExtValue()) {
2331 // Ops[0] = Result Type ID
2332 Opcode = spv::OpConstantTrue;
2333 } else {
2334 // Ops[0] = Result Type ID
2335 Opcode = spv::OpConstantFalse;
2336 }
David Neto22f144c2017-06-12 14:26:21 -04002337 } else {
2338 auto V = CI->getZExtValue();
2339 LiteralNum.push_back(V & 0xFFFFFFFF);
2340
2341 if (BitWidth > 32) {
2342 LiteralNum.push_back(V >> 32);
2343 }
2344
2345 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002346
David Neto257c3892018-04-11 13:19:45 -04002347 Ops << MkInteger(LiteralNum);
2348
2349 if (BitWidth == 32 && V == 0) {
2350 constant_i32_zero_id_ = nextID;
2351 }
David Neto22f144c2017-06-12 14:26:21 -04002352 }
2353 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2354 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2355 Type *CFPTy = CFP->getType();
2356 if (CFPTy->isFloatTy()) {
2357 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2358 } else {
2359 CFPTy->print(errs());
2360 llvm_unreachable("Implement this ConstantFP Type");
2361 }
2362
2363 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002364
David Neto257c3892018-04-11 13:19:45 -04002365 Ops << MkFloat(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002366 } else if (isa<ConstantDataSequential>(Cst) &&
2367 cast<ConstantDataSequential>(Cst)->isString()) {
2368 Cst->print(errs());
2369 llvm_unreachable("Implement this Constant");
2370
2371 } else if (const ConstantDataSequential *CDS =
2372 dyn_cast<ConstantDataSequential>(Cst)) {
David Neto49351ac2017-08-26 17:32:20 -04002373 // Let's convert <4 x i8> constant to int constant specially.
2374 // This case occurs when all the values are specified as constant
2375 // ints.
2376 Type *CstTy = Cst->getType();
2377 if (is4xi8vec(CstTy)) {
2378 LLVMContext &Context = CstTy->getContext();
2379
2380 //
2381 // Generate OpConstant with OpTypeInt 32 0.
2382 //
Neil Henning39672102017-09-29 14:33:13 +01002383 uint32_t IntValue = 0;
2384 for (unsigned k = 0; k < 4; k++) {
2385 const uint64_t Val = CDS->getElementAsInteger(k);
David Neto49351ac2017-08-26 17:32:20 -04002386 IntValue = (IntValue << 8) | (Val & 0xffu);
2387 }
2388
2389 Type *i32 = Type::getInt32Ty(Context);
2390 Constant *CstInt = ConstantInt::get(i32, IntValue);
2391 // If this constant is already registered on VMap, use it.
2392 if (VMap.count(CstInt)) {
2393 uint32_t CstID = VMap[CstInt];
2394 VMap[Cst] = CstID;
2395 continue;
2396 }
2397
David Neto257c3892018-04-11 13:19:45 -04002398 Ops << MkNum(IntValue);
David Neto49351ac2017-08-26 17:32:20 -04002399
David Neto87846742018-04-11 17:36:22 -04002400 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto49351ac2017-08-26 17:32:20 -04002401 SPIRVInstList.push_back(CstInst);
2402
2403 continue;
2404 }
2405
2406 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002407 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
2408 Constant *EleCst = CDS->getElementAsConstant(k);
2409 uint32_t EleCstID = VMap[EleCst];
David Neto257c3892018-04-11 13:19:45 -04002410 Ops << MkId(EleCstID);
David Neto22f144c2017-06-12 14:26:21 -04002411 }
2412
2413 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002414 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2415 // Let's convert <4 x i8> constant to int constant specially.
David Neto49351ac2017-08-26 17:32:20 -04002416 // This case occurs when at least one of the values is an undef.
David Neto22f144c2017-06-12 14:26:21 -04002417 Type *CstTy = Cst->getType();
2418 if (is4xi8vec(CstTy)) {
2419 LLVMContext &Context = CstTy->getContext();
2420
2421 //
2422 // Generate OpConstant with OpTypeInt 32 0.
2423 //
Neil Henning39672102017-09-29 14:33:13 +01002424 uint32_t IntValue = 0;
David Neto22f144c2017-06-12 14:26:21 -04002425 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2426 I != E; ++I) {
2427 uint64_t Val = 0;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002428 const Value *CV = *I;
Neil Henning39672102017-09-29 14:33:13 +01002429 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2430 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002431 }
David Neto49351ac2017-08-26 17:32:20 -04002432 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002433 }
2434
David Neto49351ac2017-08-26 17:32:20 -04002435 Type *i32 = Type::getInt32Ty(Context);
2436 Constant *CstInt = ConstantInt::get(i32, IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002437 // If this constant is already registered on VMap, use it.
2438 if (VMap.count(CstInt)) {
2439 uint32_t CstID = VMap[CstInt];
2440 VMap[Cst] = CstID;
David Neto19a1bad2017-08-25 15:01:41 -04002441 continue;
David Neto22f144c2017-06-12 14:26:21 -04002442 }
2443
David Neto257c3892018-04-11 13:19:45 -04002444 Ops << MkNum(IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002445
David Neto87846742018-04-11 17:36:22 -04002446 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002447 SPIRVInstList.push_back(CstInst);
2448
David Neto19a1bad2017-08-25 15:01:41 -04002449 continue;
David Neto22f144c2017-06-12 14:26:21 -04002450 }
2451
2452 // We use a constant composite in SPIR-V for our constant aggregate in
2453 // LLVM.
2454 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002455
2456 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
2457 // Look up the ID of the element of this aggregate (which we will
2458 // previously have created a constant for).
2459 uint32_t ElementConstantID = VMap[CA->getAggregateElement(k)];
2460
2461 // And add an operand to the composite we are constructing
David Neto257c3892018-04-11 13:19:45 -04002462 Ops << MkId(ElementConstantID);
David Neto22f144c2017-06-12 14:26:21 -04002463 }
2464 } else if (Cst->isNullValue()) {
2465 Opcode = spv::OpConstantNull;
David Neto22f144c2017-06-12 14:26:21 -04002466 } else {
2467 Cst->print(errs());
2468 llvm_unreachable("Unsupported Constant???");
2469 }
2470
alan-baker5b86ed72019-02-15 08:26:50 -05002471 if (Opcode == spv::OpConstantNull && Cst->getType()->isPointerTy()) {
2472 // Null pointer requires variable pointers.
2473 setVariablePointersCapabilities(Cst->getType()->getPointerAddressSpace());
2474 }
2475
David Neto87846742018-04-11 17:36:22 -04002476 auto *CstInst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002477 SPIRVInstList.push_back(CstInst);
2478 }
2479}
2480
2481void SPIRVProducerPass::GenerateSamplers(Module &M) {
2482 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto22f144c2017-06-12 14:26:21 -04002483
alan-bakerb6b09dc2018-11-08 16:59:28 -05002484 auto &sampler_map = getSamplerMap();
David Neto862b7d82018-06-14 18:48:37 -04002485 SamplerMapIndexToIDMap.clear();
David Neto22f144c2017-06-12 14:26:21 -04002486 DenseMap<unsigned, unsigned> SamplerLiteralToIDMap;
David Neto862b7d82018-06-14 18:48:37 -04002487 DenseMap<unsigned, unsigned> SamplerLiteralToDescriptorSetMap;
2488 DenseMap<unsigned, unsigned> SamplerLiteralToBindingMap;
David Neto22f144c2017-06-12 14:26:21 -04002489
David Neto862b7d82018-06-14 18:48:37 -04002490 // We might have samplers in the sampler map that are not used
2491 // in the translation unit. We need to allocate variables
2492 // for them and bindings too.
2493 DenseSet<unsigned> used_bindings;
David Neto22f144c2017-06-12 14:26:21 -04002494
alan-bakerb6b09dc2018-11-08 16:59:28 -05002495 auto *var_fn = M.getFunction("clspv.sampler.var.literal");
2496 if (!var_fn)
2497 return;
David Neto862b7d82018-06-14 18:48:37 -04002498 for (auto user : var_fn->users()) {
2499 // Populate SamplerLiteralToDescriptorSetMap and
2500 // SamplerLiteralToBindingMap.
2501 //
2502 // Look for calls like
2503 // call %opencl.sampler_t addrspace(2)*
2504 // @clspv.sampler.var.literal(
2505 // i32 descriptor,
2506 // i32 binding,
2507 // i32 index-into-sampler-map)
alan-bakerb6b09dc2018-11-08 16:59:28 -05002508 if (auto *call = dyn_cast<CallInst>(user)) {
2509 const size_t index_into_sampler_map = static_cast<size_t>(
2510 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04002511 if (index_into_sampler_map >= sampler_map.size()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002512 errs() << "Out of bounds index to sampler map: "
2513 << index_into_sampler_map;
David Neto862b7d82018-06-14 18:48:37 -04002514 llvm_unreachable("bad sampler init: out of bounds");
2515 }
2516
2517 auto sampler_value = sampler_map[index_into_sampler_map].first;
2518 const auto descriptor_set = static_cast<unsigned>(
2519 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
2520 const auto binding = static_cast<unsigned>(
2521 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
2522
2523 SamplerLiteralToDescriptorSetMap[sampler_value] = descriptor_set;
2524 SamplerLiteralToBindingMap[sampler_value] = binding;
2525 used_bindings.insert(binding);
2526 }
2527 }
2528
2529 unsigned index = 0;
2530 for (auto SamplerLiteral : sampler_map) {
David Neto22f144c2017-06-12 14:26:21 -04002531 // Generate OpVariable.
2532 //
2533 // GIDOps[0] : Result Type ID
2534 // GIDOps[1] : Storage Class
2535 SPIRVOperandList Ops;
2536
David Neto257c3892018-04-11 13:19:45 -04002537 Ops << MkId(lookupType(SamplerTy))
2538 << MkNum(spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002539
David Neto862b7d82018-06-14 18:48:37 -04002540 auto sampler_var_id = nextID++;
2541 auto *Inst = new SPIRVInstruction(spv::OpVariable, sampler_var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002542 SPIRVInstList.push_back(Inst);
2543
David Neto862b7d82018-06-14 18:48:37 -04002544 SamplerMapIndexToIDMap[index] = sampler_var_id;
2545 SamplerLiteralToIDMap[SamplerLiteral.first] = sampler_var_id;
David Neto22f144c2017-06-12 14:26:21 -04002546
2547 // Find Insert Point for OpDecorate.
2548 auto DecoInsertPoint =
2549 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2550 [](SPIRVInstruction *Inst) -> bool {
2551 return Inst->getOpcode() != spv::OpDecorate &&
2552 Inst->getOpcode() != spv::OpMemberDecorate &&
2553 Inst->getOpcode() != spv::OpExtInstImport;
2554 });
2555
2556 // Ops[0] = Target ID
2557 // Ops[1] = Decoration (DescriptorSet)
2558 // Ops[2] = LiteralNumber according to Decoration
2559 Ops.clear();
2560
David Neto862b7d82018-06-14 18:48:37 -04002561 unsigned descriptor_set;
2562 unsigned binding;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002563 if (SamplerLiteralToBindingMap.find(SamplerLiteral.first) ==
2564 SamplerLiteralToBindingMap.end()) {
David Neto862b7d82018-06-14 18:48:37 -04002565 // This sampler is not actually used. Find the next one.
2566 for (binding = 0; used_bindings.count(binding); binding++)
2567 ;
2568 descriptor_set = 0; // Literal samplers always use descriptor set 0.
2569 used_bindings.insert(binding);
2570 } else {
2571 descriptor_set = SamplerLiteralToDescriptorSetMap[SamplerLiteral.first];
2572 binding = SamplerLiteralToBindingMap[SamplerLiteral.first];
2573 }
2574
2575 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationDescriptorSet)
2576 << MkNum(descriptor_set);
David Neto22f144c2017-06-12 14:26:21 -04002577
alan-bakerf5e5f692018-11-27 08:33:24 -05002578 version0::DescriptorMapEntry::SamplerData sampler_data = {SamplerLiteral.first};
2579 descriptorMapEntries->emplace_back(std::move(sampler_data), descriptor_set, binding);
David Neto22f144c2017-06-12 14:26:21 -04002580
David Neto87846742018-04-11 17:36:22 -04002581 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002582 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2583
2584 // Ops[0] = Target ID
2585 // Ops[1] = Decoration (Binding)
2586 // Ops[2] = LiteralNumber according to Decoration
2587 Ops.clear();
David Neto862b7d82018-06-14 18:48:37 -04002588 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationBinding)
2589 << MkNum(binding);
David Neto22f144c2017-06-12 14:26:21 -04002590
David Neto87846742018-04-11 17:36:22 -04002591 auto *BindDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002592 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
David Neto862b7d82018-06-14 18:48:37 -04002593
2594 index++;
David Neto22f144c2017-06-12 14:26:21 -04002595 }
David Neto862b7d82018-06-14 18:48:37 -04002596}
David Neto22f144c2017-06-12 14:26:21 -04002597
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01002598void SPIRVProducerPass::GenerateResourceVars(Module &) {
David Neto862b7d82018-06-14 18:48:37 -04002599 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2600 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04002601
David Neto862b7d82018-06-14 18:48:37 -04002602 // Generate variables. Make one for each of resource var info object.
2603 for (auto *info : ModuleOrderedResourceVars) {
2604 Type *type = info->var_fn->getReturnType();
2605 // Remap the address space for opaque types.
2606 switch (info->arg_kind) {
2607 case clspv::ArgKind::Sampler:
2608 case clspv::ArgKind::ReadOnlyImage:
2609 case clspv::ArgKind::WriteOnlyImage:
2610 type = PointerType::get(type->getPointerElementType(),
2611 clspv::AddressSpace::UniformConstant);
2612 break;
2613 default:
2614 break;
2615 }
David Neto22f144c2017-06-12 14:26:21 -04002616
David Neto862b7d82018-06-14 18:48:37 -04002617 info->var_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04002618
David Neto862b7d82018-06-14 18:48:37 -04002619 const auto type_id = lookupType(type);
2620 const auto sc = GetStorageClassForArgKind(info->arg_kind);
2621 SPIRVOperandList Ops;
2622 Ops << MkId(type_id) << MkNum(sc);
David Neto22f144c2017-06-12 14:26:21 -04002623
David Neto862b7d82018-06-14 18:48:37 -04002624 auto *Inst = new SPIRVInstruction(spv::OpVariable, info->var_id, Ops);
2625 SPIRVInstList.push_back(Inst);
2626
2627 // Map calls to the variable-builtin-function.
2628 for (auto &U : info->var_fn->uses()) {
2629 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
2630 const auto set = unsigned(
2631 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
2632 const auto binding = unsigned(
2633 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
2634 if (set == info->descriptor_set && binding == info->binding) {
2635 switch (info->arg_kind) {
2636 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002637 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002638 case clspv::ArgKind::Pod:
2639 // The call maps to the variable directly.
2640 VMap[call] = info->var_id;
2641 break;
2642 case clspv::ArgKind::Sampler:
2643 case clspv::ArgKind::ReadOnlyImage:
2644 case clspv::ArgKind::WriteOnlyImage:
2645 // The call maps to a load we generate later.
2646 ResourceVarDeferredLoadCalls[call] = info->var_id;
2647 break;
2648 default:
2649 llvm_unreachable("Unhandled arg kind");
2650 }
2651 }
David Neto22f144c2017-06-12 14:26:21 -04002652 }
David Neto862b7d82018-06-14 18:48:37 -04002653 }
2654 }
David Neto22f144c2017-06-12 14:26:21 -04002655
David Neto862b7d82018-06-14 18:48:37 -04002656 // Generate associated decorations.
David Neto22f144c2017-06-12 14:26:21 -04002657
David Neto862b7d82018-06-14 18:48:37 -04002658 // Find Insert Point for OpDecorate.
2659 auto DecoInsertPoint =
2660 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2661 [](SPIRVInstruction *Inst) -> bool {
2662 return Inst->getOpcode() != spv::OpDecorate &&
2663 Inst->getOpcode() != spv::OpMemberDecorate &&
2664 Inst->getOpcode() != spv::OpExtInstImport;
2665 });
2666
2667 SPIRVOperandList Ops;
2668 for (auto *info : ModuleOrderedResourceVars) {
2669 // Decorate with DescriptorSet and Binding.
2670 Ops.clear();
2671 Ops << MkId(info->var_id) << MkNum(spv::DecorationDescriptorSet)
2672 << MkNum(info->descriptor_set);
2673 SPIRVInstList.insert(DecoInsertPoint,
2674 new SPIRVInstruction(spv::OpDecorate, Ops));
2675
2676 Ops.clear();
2677 Ops << MkId(info->var_id) << MkNum(spv::DecorationBinding)
2678 << MkNum(info->binding);
2679 SPIRVInstList.insert(DecoInsertPoint,
2680 new SPIRVInstruction(spv::OpDecorate, Ops));
2681
2682 // Generate NonWritable and NonReadable
2683 switch (info->arg_kind) {
2684 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002685 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002686 if (info->var_fn->getReturnType()->getPointerAddressSpace() ==
2687 clspv::AddressSpace::Constant) {
2688 Ops.clear();
2689 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
2690 SPIRVInstList.insert(DecoInsertPoint,
2691 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002692 }
David Neto862b7d82018-06-14 18:48:37 -04002693 break;
David Neto862b7d82018-06-14 18:48:37 -04002694 case clspv::ArgKind::WriteOnlyImage:
2695 Ops.clear();
2696 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonReadable);
2697 SPIRVInstList.insert(DecoInsertPoint,
2698 new SPIRVInstruction(spv::OpDecorate, Ops));
2699 break;
2700 default:
2701 break;
David Neto22f144c2017-06-12 14:26:21 -04002702 }
2703 }
2704}
2705
2706void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002707 Module &M = *GV.getParent();
David Neto22f144c2017-06-12 14:26:21 -04002708 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2709 ValueMapType &VMap = getValueMap();
2710 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07002711 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002712
2713 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2714 Type *Ty = GV.getType();
2715 PointerType *PTy = cast<PointerType>(Ty);
2716
2717 uint32_t InitializerID = 0;
2718
2719 // Workgroup size is handled differently (it goes into a constant)
2720 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2721 std::vector<bool> HasMDVec;
2722 uint32_t PrevXDimCst = 0xFFFFFFFF;
2723 uint32_t PrevYDimCst = 0xFFFFFFFF;
2724 uint32_t PrevZDimCst = 0xFFFFFFFF;
2725 for (Function &Func : *GV.getParent()) {
2726 if (Func.isDeclaration()) {
2727 continue;
2728 }
2729
2730 // We only need to check kernels.
2731 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2732 continue;
2733 }
2734
2735 if (const MDNode *MD =
2736 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2737 uint32_t CurXDimCst = static_cast<uint32_t>(
2738 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2739 uint32_t CurYDimCst = static_cast<uint32_t>(
2740 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2741 uint32_t CurZDimCst = static_cast<uint32_t>(
2742 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2743
2744 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2745 PrevZDimCst == 0xFFFFFFFF) {
2746 PrevXDimCst = CurXDimCst;
2747 PrevYDimCst = CurYDimCst;
2748 PrevZDimCst = CurZDimCst;
2749 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2750 CurZDimCst != PrevZDimCst) {
2751 llvm_unreachable(
2752 "reqd_work_group_size must be the same across all kernels");
2753 } else {
2754 continue;
2755 }
2756
2757 //
2758 // Generate OpConstantComposite.
2759 //
2760 // Ops[0] : Result Type ID
2761 // Ops[1] : Constant size for x dimension.
2762 // Ops[2] : Constant size for y dimension.
2763 // Ops[3] : Constant size for z dimension.
2764 SPIRVOperandList Ops;
2765
2766 uint32_t XDimCstID =
2767 VMap[mdconst::extract<ConstantInt>(MD->getOperand(0))];
2768 uint32_t YDimCstID =
2769 VMap[mdconst::extract<ConstantInt>(MD->getOperand(1))];
2770 uint32_t ZDimCstID =
2771 VMap[mdconst::extract<ConstantInt>(MD->getOperand(2))];
2772
2773 InitializerID = nextID;
2774
David Neto257c3892018-04-11 13:19:45 -04002775 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2776 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002777
David Neto87846742018-04-11 17:36:22 -04002778 auto *Inst =
2779 new SPIRVInstruction(spv::OpConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002780 SPIRVInstList.push_back(Inst);
2781
2782 HasMDVec.push_back(true);
2783 } else {
2784 HasMDVec.push_back(false);
2785 }
2786 }
2787
2788 // Check all kernels have same definitions for work_group_size.
2789 bool HasMD = false;
2790 if (!HasMDVec.empty()) {
2791 HasMD = HasMDVec[0];
2792 for (uint32_t i = 1; i < HasMDVec.size(); i++) {
2793 if (HasMD != HasMDVec[i]) {
2794 llvm_unreachable(
2795 "Kernels should have consistent work group size definition");
2796 }
2797 }
2798 }
2799
2800 // If all kernels do not have metadata for reqd_work_group_size, generate
2801 // OpSpecConstants for x/y/z dimension.
2802 if (!HasMD) {
2803 //
2804 // Generate OpSpecConstants for x/y/z dimension.
2805 //
2806 // Ops[0] : Result Type ID
2807 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
2808 uint32_t XDimCstID = 0;
2809 uint32_t YDimCstID = 0;
2810 uint32_t ZDimCstID = 0;
2811
David Neto22f144c2017-06-12 14:26:21 -04002812 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04002813 uint32_t result_type_id =
2814 lookupType(Ty->getPointerElementType()->getSequentialElementType());
David Neto22f144c2017-06-12 14:26:21 -04002815
David Neto257c3892018-04-11 13:19:45 -04002816 // X Dimension
2817 Ops << MkId(result_type_id) << MkNum(1);
2818 XDimCstID = nextID++;
2819 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002820 new SPIRVInstruction(spv::OpSpecConstant, XDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002821
2822 // Y Dimension
2823 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002824 Ops << MkId(result_type_id) << MkNum(1);
2825 YDimCstID = nextID++;
2826 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002827 new SPIRVInstruction(spv::OpSpecConstant, YDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002828
2829 // Z Dimension
2830 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002831 Ops << MkId(result_type_id) << MkNum(1);
2832 ZDimCstID = nextID++;
2833 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002834 new SPIRVInstruction(spv::OpSpecConstant, ZDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002835
David Neto257c3892018-04-11 13:19:45 -04002836 BuiltinDimVec.push_back(XDimCstID);
2837 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002838 BuiltinDimVec.push_back(ZDimCstID);
2839
David Neto22f144c2017-06-12 14:26:21 -04002840 //
2841 // Generate OpSpecConstantComposite.
2842 //
2843 // Ops[0] : Result Type ID
2844 // Ops[1] : Constant size for x dimension.
2845 // Ops[2] : Constant size for y dimension.
2846 // Ops[3] : Constant size for z dimension.
2847 InitializerID = nextID;
2848
2849 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002850 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2851 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002852
David Neto87846742018-04-11 17:36:22 -04002853 auto *Inst =
2854 new SPIRVInstruction(spv::OpSpecConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002855 SPIRVInstList.push_back(Inst);
2856 }
2857 }
2858
David Neto22f144c2017-06-12 14:26:21 -04002859 VMap[&GV] = nextID;
2860
2861 //
2862 // Generate OpVariable.
2863 //
2864 // GIDOps[0] : Result Type ID
2865 // GIDOps[1] : Storage Class
2866 SPIRVOperandList Ops;
2867
David Neto85082642018-03-24 06:55:20 -07002868 const auto AS = PTy->getAddressSpace();
David Netoc6f3ab22018-04-06 18:02:31 -04002869 Ops << MkId(lookupType(Ty)) << MkNum(GetStorageClass(AS));
David Neto22f144c2017-06-12 14:26:21 -04002870
David Neto85082642018-03-24 06:55:20 -07002871 if (GV.hasInitializer()) {
2872 InitializerID = VMap[GV.getInitializer()];
David Neto22f144c2017-06-12 14:26:21 -04002873 }
2874
David Neto85082642018-03-24 06:55:20 -07002875 const bool module_scope_constant_external_init =
David Neto862b7d82018-06-14 18:48:37 -04002876 (AS == AddressSpace::Constant) && GV.hasInitializer() &&
David Neto85082642018-03-24 06:55:20 -07002877 clspv::Option::ModuleConstantsInStorageBuffer();
2878
2879 if (0 != InitializerID) {
2880 if (!module_scope_constant_external_init) {
2881 // Emit the ID of the intiializer as part of the variable definition.
David Netoc6f3ab22018-04-06 18:02:31 -04002882 Ops << MkId(InitializerID);
David Neto85082642018-03-24 06:55:20 -07002883 }
2884 }
2885 const uint32_t var_id = nextID++;
2886
David Neto87846742018-04-11 17:36:22 -04002887 auto *Inst = new SPIRVInstruction(spv::OpVariable, var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002888 SPIRVInstList.push_back(Inst);
2889
2890 // If we have a builtin.
2891 if (spv::BuiltInMax != BuiltinType) {
2892 // Find Insert Point for OpDecorate.
2893 auto DecoInsertPoint =
2894 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2895 [](SPIRVInstruction *Inst) -> bool {
2896 return Inst->getOpcode() != spv::OpDecorate &&
2897 Inst->getOpcode() != spv::OpMemberDecorate &&
2898 Inst->getOpcode() != spv::OpExtInstImport;
2899 });
2900 //
2901 // Generate OpDecorate.
2902 //
2903 // DOps[0] = Target ID
2904 // DOps[1] = Decoration (Builtin)
2905 // DOps[2] = BuiltIn ID
2906 uint32_t ResultID;
2907
2908 // WorkgroupSize is different, we decorate the constant composite that has
2909 // its value, rather than the variable that we use to access the value.
2910 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2911 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04002912 // Save both the value and variable IDs for later.
2913 WorkgroupSizeValueID = InitializerID;
2914 WorkgroupSizeVarID = VMap[&GV];
David Neto22f144c2017-06-12 14:26:21 -04002915 } else {
2916 ResultID = VMap[&GV];
2917 }
2918
2919 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002920 DOps << MkId(ResultID) << MkNum(spv::DecorationBuiltIn)
2921 << MkNum(BuiltinType);
David Neto22f144c2017-06-12 14:26:21 -04002922
David Neto87846742018-04-11 17:36:22 -04002923 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, DOps);
David Neto22f144c2017-06-12 14:26:21 -04002924 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
David Neto85082642018-03-24 06:55:20 -07002925 } else if (module_scope_constant_external_init) {
2926 // This module scope constant is initialized from a storage buffer with data
2927 // provided by the host at binding 0 of the next descriptor set.
David Neto78383442018-06-15 20:31:56 -04002928 const uint32_t descriptor_set = TakeDescriptorIndex(&M);
David Neto85082642018-03-24 06:55:20 -07002929
David Neto862b7d82018-06-14 18:48:37 -04002930 // Emit the intializer to the descriptor map file.
David Neto85082642018-03-24 06:55:20 -07002931 // Use "kind,buffer" to indicate storage buffer. We might want to expand
2932 // that later to other types, like uniform buffer.
alan-bakerf5e5f692018-11-27 08:33:24 -05002933 std::string hexbytes;
2934 llvm::raw_string_ostream str(hexbytes);
2935 clspv::ConstantEmitter(DL, str).Emit(GV.getInitializer());
2936 version0::DescriptorMapEntry::ConstantData constant_data = {ArgKind::Buffer, str.str()};
2937 descriptorMapEntries->emplace_back(std::move(constant_data), descriptor_set, 0);
David Neto85082642018-03-24 06:55:20 -07002938
2939 // Find Insert Point for OpDecorate.
2940 auto DecoInsertPoint =
2941 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2942 [](SPIRVInstruction *Inst) -> bool {
2943 return Inst->getOpcode() != spv::OpDecorate &&
2944 Inst->getOpcode() != spv::OpMemberDecorate &&
2945 Inst->getOpcode() != spv::OpExtInstImport;
2946 });
2947
David Neto257c3892018-04-11 13:19:45 -04002948 // OpDecorate %var Binding <binding>
David Neto85082642018-03-24 06:55:20 -07002949 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002950 DOps << MkId(var_id) << MkNum(spv::DecorationBinding) << MkNum(0);
2951 DecoInsertPoint = SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04002952 DecoInsertPoint, new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto85082642018-03-24 06:55:20 -07002953
2954 // OpDecorate %var DescriptorSet <descriptor_set>
2955 DOps.clear();
David Neto257c3892018-04-11 13:19:45 -04002956 DOps << MkId(var_id) << MkNum(spv::DecorationDescriptorSet)
2957 << MkNum(descriptor_set);
David Netoc6f3ab22018-04-06 18:02:31 -04002958 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04002959 new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto22f144c2017-06-12 14:26:21 -04002960 }
2961}
2962
David Netoc6f3ab22018-04-06 18:02:31 -04002963void SPIRVProducerPass::GenerateWorkgroupVars() {
2964 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
Alan Baker202c8c72018-08-13 13:47:44 -04002965 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2966 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002967 LocalArgInfo &info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002968
2969 // Generate OpVariable.
2970 //
2971 // GIDOps[0] : Result Type ID
2972 // GIDOps[1] : Storage Class
2973 SPIRVOperandList Ops;
2974 Ops << MkId(info.ptr_array_type_id) << MkNum(spv::StorageClassWorkgroup);
2975
2976 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002977 new SPIRVInstruction(spv::OpVariable, info.variable_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002978 }
2979}
2980
David Neto862b7d82018-06-14 18:48:37 -04002981void SPIRVProducerPass::GenerateDescriptorMapInfo(const DataLayout &DL,
2982 Function &F) {
David Netoc5fb5242018-07-30 13:28:31 -04002983 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2984 return;
2985 }
David Neto862b7d82018-06-14 18:48:37 -04002986 // Gather the list of resources that are used by this function's arguments.
2987 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
2988
alan-bakerf5e5f692018-11-27 08:33:24 -05002989 // TODO(alan-baker): This should become unnecessary by fixing the rest of the
2990 // flow to generate pod_ubo arguments earlier.
David Neto862b7d82018-06-14 18:48:37 -04002991 auto remap_arg_kind = [](StringRef argKind) {
alan-bakerf5e5f692018-11-27 08:33:24 -05002992 std::string kind =
2993 clspv::Option::PodArgsInUniformBuffer() && argKind.equals("pod")
2994 ? "pod_ubo"
2995 : argKind;
2996 return GetArgKindFromName(kind);
David Neto862b7d82018-06-14 18:48:37 -04002997 };
2998
2999 auto *fty = F.getType()->getPointerElementType();
3000 auto *func_ty = dyn_cast<FunctionType>(fty);
3001
3002 // If we've clustereed POD arguments, then argument details are in metadata.
3003 // If an argument maps to a resource variable, then get descriptor set and
3004 // binding from the resoure variable. Other info comes from the metadata.
3005 const auto *arg_map = F.getMetadata("kernel_arg_map");
3006 if (arg_map) {
3007 for (const auto &arg : arg_map->operands()) {
3008 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
Kévin PETITa353c832018-03-20 23:21:21 +00003009 assert(arg_node->getNumOperands() == 7);
David Neto862b7d82018-06-14 18:48:37 -04003010 const auto name =
3011 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
3012 const auto old_index =
3013 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
3014 // Remapped argument index
alan-bakerb6b09dc2018-11-08 16:59:28 -05003015 const size_t new_index = static_cast<size_t>(
3016 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04003017 const auto offset =
3018 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
Kévin PETITa353c832018-03-20 23:21:21 +00003019 const auto arg_size =
3020 dyn_extract<ConstantInt>(arg_node->getOperand(4))->getZExtValue();
David Neto862b7d82018-06-14 18:48:37 -04003021 const auto argKind = remap_arg_kind(
Kévin PETITa353c832018-03-20 23:21:21 +00003022 dyn_cast<MDString>(arg_node->getOperand(5))->getString());
David Neto862b7d82018-06-14 18:48:37 -04003023 const auto spec_id =
Kévin PETITa353c832018-03-20 23:21:21 +00003024 dyn_extract<ConstantInt>(arg_node->getOperand(6))->getSExtValue();
alan-bakerf5e5f692018-11-27 08:33:24 -05003025
3026 uint32_t descriptor_set = 0;
3027 uint32_t binding = 0;
3028 version0::DescriptorMapEntry::KernelArgData kernel_data = {
3029 F.getName(),
3030 name,
3031 static_cast<uint32_t>(old_index),
3032 argKind,
3033 static_cast<uint32_t>(spec_id),
3034 // This will be set below for pointer-to-local args.
3035 0,
3036 static_cast<uint32_t>(offset),
3037 static_cast<uint32_t>(arg_size)};
David Neto862b7d82018-06-14 18:48:37 -04003038 if (spec_id > 0) {
alan-bakerf5e5f692018-11-27 08:33:24 -05003039 kernel_data.local_element_size = static_cast<uint32_t>(GetTypeAllocSize(
3040 func_ty->getParamType(unsigned(new_index))->getPointerElementType(),
3041 DL));
David Neto862b7d82018-06-14 18:48:37 -04003042 } else {
3043 auto *info = resource_var_at_index[new_index];
3044 assert(info);
alan-bakerf5e5f692018-11-27 08:33:24 -05003045 descriptor_set = info->descriptor_set;
3046 binding = info->binding;
David Neto862b7d82018-06-14 18:48:37 -04003047 }
alan-bakerf5e5f692018-11-27 08:33:24 -05003048 descriptorMapEntries->emplace_back(std::move(kernel_data), descriptor_set, binding);
David Neto862b7d82018-06-14 18:48:37 -04003049 }
3050 } else {
3051 // There is no argument map.
3052 // Take descriptor info from the resource variable calls.
Kévin PETITa353c832018-03-20 23:21:21 +00003053 // Take argument name and size from the arguments list.
David Neto862b7d82018-06-14 18:48:37 -04003054
3055 SmallVector<Argument *, 4> arguments;
3056 for (auto &arg : F.args()) {
3057 arguments.push_back(&arg);
3058 }
3059
3060 unsigned arg_index = 0;
3061 for (auto *info : resource_var_at_index) {
3062 if (info) {
Kévin PETITa353c832018-03-20 23:21:21 +00003063 auto arg = arguments[arg_index];
alan-bakerb6b09dc2018-11-08 16:59:28 -05003064 unsigned arg_size = 0;
Kévin PETITa353c832018-03-20 23:21:21 +00003065 if (info->arg_kind == clspv::ArgKind::Pod) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05003066 arg_size = static_cast<uint32_t>(DL.getTypeStoreSize(arg->getType()));
Kévin PETITa353c832018-03-20 23:21:21 +00003067 }
3068
alan-bakerf5e5f692018-11-27 08:33:24 -05003069 // Local pointer arguments are unused in this case. Offset is always zero.
3070 version0::DescriptorMapEntry::KernelArgData kernel_data = {
3071 F.getName(), arg->getName(),
3072 arg_index, remap_arg_kind(clspv::GetArgKindName(info->arg_kind)),
3073 0, 0,
3074 0, arg_size};
3075 descriptorMapEntries->emplace_back(std::move(kernel_data),
3076 info->descriptor_set, info->binding);
David Neto862b7d82018-06-14 18:48:37 -04003077 }
3078 arg_index++;
3079 }
3080 // Generate mappings for pointer-to-local arguments.
3081 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
3082 Argument *arg = arguments[arg_index];
Alan Baker202c8c72018-08-13 13:47:44 -04003083 auto where = LocalArgSpecIds.find(arg);
3084 if (where != LocalArgSpecIds.end()) {
3085 auto &local_arg_info = LocalSpecIdInfoMap[where->second];
alan-bakerf5e5f692018-11-27 08:33:24 -05003086 // Pod arguments members are unused in this case.
3087 version0::DescriptorMapEntry::KernelArgData kernel_data = {
3088 F.getName(),
3089 arg->getName(),
3090 arg_index,
3091 ArgKind::Local,
3092 static_cast<uint32_t>(local_arg_info.spec_id),
3093 static_cast<uint32_t>(GetTypeAllocSize(local_arg_info.elem_type, DL)),
3094 0,
3095 0};
3096 // Pointer-to-local arguments do not utilize descriptor set and binding.
3097 descriptorMapEntries->emplace_back(std::move(kernel_data), 0, 0);
David Neto862b7d82018-06-14 18:48:37 -04003098 }
3099 }
3100 }
3101}
3102
David Neto22f144c2017-06-12 14:26:21 -04003103void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
3104 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3105 ValueMapType &VMap = getValueMap();
3106 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04003107 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
3108 auto &GlobalConstArgSet = getGlobalConstArgSet();
3109
3110 FunctionType *FTy = F.getFunctionType();
3111
3112 //
David Neto22f144c2017-06-12 14:26:21 -04003113 // Generate OPFunction.
3114 //
3115
3116 // FOps[0] : Result Type ID
3117 // FOps[1] : Function Control
3118 // FOps[2] : Function Type ID
3119 SPIRVOperandList FOps;
3120
3121 // Find SPIRV instruction for return type.
David Neto257c3892018-04-11 13:19:45 -04003122 FOps << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04003123
3124 // Check function attributes for SPIRV Function Control.
3125 uint32_t FuncControl = spv::FunctionControlMaskNone;
3126 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
3127 FuncControl |= spv::FunctionControlInlineMask;
3128 }
3129 if (F.hasFnAttribute(Attribute::NoInline)) {
3130 FuncControl |= spv::FunctionControlDontInlineMask;
3131 }
3132 // TODO: Check llvm attribute for Function Control Pure.
3133 if (F.hasFnAttribute(Attribute::ReadOnly)) {
3134 FuncControl |= spv::FunctionControlPureMask;
3135 }
3136 // TODO: Check llvm attribute for Function Control Const.
3137 if (F.hasFnAttribute(Attribute::ReadNone)) {
3138 FuncControl |= spv::FunctionControlConstMask;
3139 }
3140
David Neto257c3892018-04-11 13:19:45 -04003141 FOps << MkNum(FuncControl);
David Neto22f144c2017-06-12 14:26:21 -04003142
3143 uint32_t FTyID;
3144 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3145 SmallVector<Type *, 4> NewFuncParamTys;
3146 FunctionType *NewFTy =
3147 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
3148 FTyID = lookupType(NewFTy);
3149 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07003150 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04003151 if (GlobalConstFuncTyMap.count(FTy)) {
3152 FTyID = lookupType(GlobalConstFuncTyMap[FTy].first);
3153 } else {
3154 FTyID = lookupType(FTy);
3155 }
3156 }
3157
David Neto257c3892018-04-11 13:19:45 -04003158 FOps << MkId(FTyID);
David Neto22f144c2017-06-12 14:26:21 -04003159
3160 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3161 EntryPoints.push_back(std::make_pair(&F, nextID));
3162 }
3163
3164 VMap[&F] = nextID;
3165
David Neto482550a2018-03-24 05:21:07 -07003166 if (clspv::Option::ShowIDs()) {
David Netob05675d2018-02-16 12:37:49 -05003167 errs() << "Function " << F.getName() << " is " << nextID << "\n";
3168 }
David Neto22f144c2017-06-12 14:26:21 -04003169 // Generate SPIRV instruction for function.
David Neto87846742018-04-11 17:36:22 -04003170 auto *FuncInst = new SPIRVInstruction(spv::OpFunction, nextID++, FOps);
David Neto22f144c2017-06-12 14:26:21 -04003171 SPIRVInstList.push_back(FuncInst);
3172
3173 //
3174 // Generate OpFunctionParameter for Normal function.
3175 //
3176
3177 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3178 // Iterate Argument for name instead of param type from function type.
3179 unsigned ArgIdx = 0;
3180 for (Argument &Arg : F.args()) {
3181 VMap[&Arg] = nextID;
3182
3183 // ParamOps[0] : Result Type ID
3184 SPIRVOperandList ParamOps;
3185
3186 // Find SPIRV instruction for parameter type.
3187 uint32_t ParamTyID = lookupType(Arg.getType());
3188 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
3189 if (GlobalConstFuncTyMap.count(FTy)) {
3190 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
3191 Type *EleTy = PTy->getPointerElementType();
3192 Type *ArgTy =
3193 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
3194 ParamTyID = lookupType(ArgTy);
3195 GlobalConstArgSet.insert(&Arg);
3196 }
3197 }
3198 }
David Neto257c3892018-04-11 13:19:45 -04003199 ParamOps << MkId(ParamTyID);
David Neto22f144c2017-06-12 14:26:21 -04003200
3201 // Generate SPIRV instruction for parameter.
David Neto87846742018-04-11 17:36:22 -04003202 auto *ParamInst =
3203 new SPIRVInstruction(spv::OpFunctionParameter, nextID++, ParamOps);
David Neto22f144c2017-06-12 14:26:21 -04003204 SPIRVInstList.push_back(ParamInst);
3205
3206 ArgIdx++;
3207 }
3208 }
3209}
3210
alan-bakerb6b09dc2018-11-08 16:59:28 -05003211void SPIRVProducerPass::GenerateModuleInfo(Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04003212 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3213 EntryPointVecType &EntryPoints = getEntryPointVec();
3214 ValueMapType &VMap = getValueMap();
3215 ValueList &EntryPointInterfaces = getEntryPointInterfacesVec();
3216 uint32_t &ExtInstImportID = getOpExtInstImportID();
3217 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
3218
3219 // Set up insert point.
3220 auto InsertPoint = SPIRVInstList.begin();
3221
3222 //
3223 // Generate OpCapability
3224 //
3225 // TODO: Which llvm information is mapped to SPIRV Capapbility?
3226
3227 // Ops[0] = Capability
3228 SPIRVOperandList Ops;
3229
David Neto87846742018-04-11 17:36:22 -04003230 auto *CapInst =
3231 new SPIRVInstruction(spv::OpCapability, {MkNum(spv::CapabilityShader)});
David Neto22f144c2017-06-12 14:26:21 -04003232 SPIRVInstList.insert(InsertPoint, CapInst);
3233
3234 for (Type *Ty : getTypeList()) {
alan-bakerb39c8262019-03-08 14:03:37 -05003235 if (clspv::Option::Int8Support() && Ty->isIntegerTy(8)) {
3236 // Generate OpCapability for i8 type.
3237 SPIRVInstList.insert(InsertPoint,
3238 new SPIRVInstruction(spv::OpCapability,
3239 {MkNum(spv::CapabilityInt8)}));
3240 } else if (Ty->isIntegerTy(16)) {
David Neto22f144c2017-06-12 14:26:21 -04003241 // Generate OpCapability for i16 type.
David Neto87846742018-04-11 17:36:22 -04003242 SPIRVInstList.insert(InsertPoint,
3243 new SPIRVInstruction(spv::OpCapability,
3244 {MkNum(spv::CapabilityInt16)}));
David Neto22f144c2017-06-12 14:26:21 -04003245 } else if (Ty->isIntegerTy(64)) {
3246 // Generate OpCapability for i64 type.
David Neto87846742018-04-11 17:36:22 -04003247 SPIRVInstList.insert(InsertPoint,
3248 new SPIRVInstruction(spv::OpCapability,
3249 {MkNum(spv::CapabilityInt64)}));
David Neto22f144c2017-06-12 14:26:21 -04003250 } else if (Ty->isHalfTy()) {
3251 // Generate OpCapability for half type.
3252 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003253 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3254 {MkNum(spv::CapabilityFloat16)}));
David Neto22f144c2017-06-12 14:26:21 -04003255 } else if (Ty->isDoubleTy()) {
3256 // Generate OpCapability for double type.
3257 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003258 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3259 {MkNum(spv::CapabilityFloat64)}));
David Neto22f144c2017-06-12 14:26:21 -04003260 } else if (auto *STy = dyn_cast<StructType>(Ty)) {
3261 if (STy->isOpaque()) {
David Neto565571c2017-08-21 12:00:05 -04003262 if (STy->getName().equals("opencl.image2d_wo_t") ||
3263 STy->getName().equals("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04003264 // Generate OpCapability for write only image type.
3265 SPIRVInstList.insert(
3266 InsertPoint,
3267 new SPIRVInstruction(
David Neto87846742018-04-11 17:36:22 -04003268 spv::OpCapability,
3269 {MkNum(spv::CapabilityStorageImageWriteWithoutFormat)}));
David Neto22f144c2017-06-12 14:26:21 -04003270 }
3271 }
3272 }
3273 }
3274
David Neto5c22a252018-03-15 16:07:41 -04003275 { // OpCapability ImageQuery
3276 bool hasImageQuery = false;
3277 for (const char *imageQuery : {
3278 "_Z15get_image_width14ocl_image2d_ro",
3279 "_Z15get_image_width14ocl_image2d_wo",
3280 "_Z16get_image_height14ocl_image2d_ro",
3281 "_Z16get_image_height14ocl_image2d_wo",
3282 }) {
3283 if (module.getFunction(imageQuery)) {
3284 hasImageQuery = true;
3285 break;
3286 }
3287 }
3288 if (hasImageQuery) {
David Neto87846742018-04-11 17:36:22 -04003289 auto *ImageQueryCapInst = new SPIRVInstruction(
3290 spv::OpCapability, {MkNum(spv::CapabilityImageQuery)});
David Neto5c22a252018-03-15 16:07:41 -04003291 SPIRVInstList.insert(InsertPoint, ImageQueryCapInst);
3292 }
3293 }
3294
David Neto22f144c2017-06-12 14:26:21 -04003295 if (hasVariablePointers()) {
3296 //
David Neto22f144c2017-06-12 14:26:21 -04003297 // Generate OpCapability.
3298 //
3299 // Ops[0] = Capability
3300 //
3301 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003302 Ops << MkNum(spv::CapabilityVariablePointers);
David Neto22f144c2017-06-12 14:26:21 -04003303
David Neto87846742018-04-11 17:36:22 -04003304 SPIRVInstList.insert(InsertPoint,
3305 new SPIRVInstruction(spv::OpCapability, Ops));
alan-baker5b86ed72019-02-15 08:26:50 -05003306 } else if (hasVariablePointersStorageBuffer()) {
3307 //
3308 // Generate OpCapability.
3309 //
3310 // Ops[0] = Capability
3311 //
3312 Ops.clear();
3313 Ops << MkNum(spv::CapabilityVariablePointersStorageBuffer);
David Neto22f144c2017-06-12 14:26:21 -04003314
alan-baker5b86ed72019-02-15 08:26:50 -05003315 SPIRVInstList.insert(InsertPoint,
3316 new SPIRVInstruction(spv::OpCapability, Ops));
3317 }
3318
3319 // Always add the storage buffer extension
3320 {
David Neto22f144c2017-06-12 14:26:21 -04003321 //
3322 // Generate OpExtension.
3323 //
3324 // Ops[0] = Name (Literal String)
3325 //
alan-baker5b86ed72019-02-15 08:26:50 -05003326 auto *ExtensionInst = new SPIRVInstruction(
3327 spv::OpExtension, {MkString("SPV_KHR_storage_buffer_storage_class")});
3328 SPIRVInstList.insert(InsertPoint, ExtensionInst);
3329 }
David Neto22f144c2017-06-12 14:26:21 -04003330
alan-baker5b86ed72019-02-15 08:26:50 -05003331 if (hasVariablePointers() || hasVariablePointersStorageBuffer()) {
3332 //
3333 // Generate OpExtension.
3334 //
3335 // Ops[0] = Name (Literal String)
3336 //
3337 auto *ExtensionInst = new SPIRVInstruction(
3338 spv::OpExtension, {MkString("SPV_KHR_variable_pointers")});
3339 SPIRVInstList.insert(InsertPoint, ExtensionInst);
David Neto22f144c2017-06-12 14:26:21 -04003340 }
3341
3342 if (ExtInstImportID) {
3343 ++InsertPoint;
3344 }
3345
3346 //
3347 // Generate OpMemoryModel
3348 //
3349 // Memory model for Vulkan will always be GLSL450.
3350
3351 // Ops[0] = Addressing Model
3352 // Ops[1] = Memory Model
3353 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003354 Ops << MkNum(spv::AddressingModelLogical) << MkNum(spv::MemoryModelGLSL450);
David Neto22f144c2017-06-12 14:26:21 -04003355
David Neto87846742018-04-11 17:36:22 -04003356 auto *MemModelInst = new SPIRVInstruction(spv::OpMemoryModel, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003357 SPIRVInstList.insert(InsertPoint, MemModelInst);
3358
3359 //
3360 // Generate OpEntryPoint
3361 //
3362 for (auto EntryPoint : EntryPoints) {
3363 // Ops[0] = Execution Model
3364 // Ops[1] = EntryPoint ID
3365 // Ops[2] = Name (Literal String)
3366 // ...
3367 //
3368 // TODO: Do we need to consider Interface ID for forward references???
3369 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003370 const StringRef &name = EntryPoint.first->getName();
David Neto257c3892018-04-11 13:19:45 -04003371 Ops << MkNum(spv::ExecutionModelGLCompute) << MkId(EntryPoint.second)
3372 << MkString(name);
David Neto22f144c2017-06-12 14:26:21 -04003373
David Neto22f144c2017-06-12 14:26:21 -04003374 for (Value *Interface : EntryPointInterfaces) {
David Neto257c3892018-04-11 13:19:45 -04003375 Ops << MkId(VMap[Interface]);
David Neto22f144c2017-06-12 14:26:21 -04003376 }
3377
David Neto87846742018-04-11 17:36:22 -04003378 auto *EntryPointInst = new SPIRVInstruction(spv::OpEntryPoint, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003379 SPIRVInstList.insert(InsertPoint, EntryPointInst);
3380 }
3381
3382 for (auto EntryPoint : EntryPoints) {
3383 if (const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
3384 ->getMetadata("reqd_work_group_size")) {
3385
3386 if (!BuiltinDimVec.empty()) {
3387 llvm_unreachable(
3388 "Kernels should have consistent work group size definition");
3389 }
3390
3391 //
3392 // Generate OpExecutionMode
3393 //
3394
3395 // Ops[0] = Entry Point ID
3396 // Ops[1] = Execution Mode
3397 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
3398 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003399 Ops << MkId(EntryPoint.second) << MkNum(spv::ExecutionModeLocalSize);
David Neto22f144c2017-06-12 14:26:21 -04003400
3401 uint32_t XDim = static_cast<uint32_t>(
3402 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3403 uint32_t YDim = static_cast<uint32_t>(
3404 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3405 uint32_t ZDim = static_cast<uint32_t>(
3406 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3407
David Neto257c3892018-04-11 13:19:45 -04003408 Ops << MkNum(XDim) << MkNum(YDim) << MkNum(ZDim);
David Neto22f144c2017-06-12 14:26:21 -04003409
David Neto87846742018-04-11 17:36:22 -04003410 auto *ExecModeInst = new SPIRVInstruction(spv::OpExecutionMode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003411 SPIRVInstList.insert(InsertPoint, ExecModeInst);
3412 }
3413 }
3414
3415 //
3416 // Generate OpSource.
3417 //
3418 // Ops[0] = SourceLanguage ID
3419 // Ops[1] = Version (LiteralNum)
3420 //
3421 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003422 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(120);
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()) {
3496 setVariablePointersCapabilities(alloca->getAllocatedType()->getPointerAddressSpace());
3497 }
David Neto6dcd4712017-06-23 11:06:47 -04003498 GenerateInstruction(I);
3499 }
3500 }
3501
David Neto22f144c2017-06-12 14:26:21 -04003502 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04003503 if (clspv::Option::HackInitializers()) {
3504 GenerateEntryPointInitialStores();
3505 }
David Neto22f144c2017-06-12 14:26:21 -04003506 }
3507
3508 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003509 if (!isa<AllocaInst>(I)) {
3510 GenerateInstruction(I);
3511 }
David Neto22f144c2017-06-12 14:26:21 -04003512 }
3513 }
3514}
3515
3516spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3517 const std::map<CmpInst::Predicate, spv::Op> Map = {
3518 {CmpInst::ICMP_EQ, spv::OpIEqual},
3519 {CmpInst::ICMP_NE, spv::OpINotEqual},
3520 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3521 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3522 {CmpInst::ICMP_ULT, spv::OpULessThan},
3523 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3524 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3525 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3526 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3527 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3528 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3529 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3530 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3531 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3532 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3533 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3534 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3535 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3536 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3537 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3538 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3539 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3540
3541 assert(0 != Map.count(I->getPredicate()));
3542
3543 return Map.at(I->getPredicate());
3544}
3545
3546spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3547 const std::map<unsigned, spv::Op> Map{
3548 {Instruction::Trunc, spv::OpUConvert},
3549 {Instruction::ZExt, spv::OpUConvert},
3550 {Instruction::SExt, spv::OpSConvert},
3551 {Instruction::FPToUI, spv::OpConvertFToU},
3552 {Instruction::FPToSI, spv::OpConvertFToS},
3553 {Instruction::UIToFP, spv::OpConvertUToF},
3554 {Instruction::SIToFP, spv::OpConvertSToF},
3555 {Instruction::FPTrunc, spv::OpFConvert},
3556 {Instruction::FPExt, spv::OpFConvert},
3557 {Instruction::BitCast, spv::OpBitcast}};
3558
3559 assert(0 != Map.count(I.getOpcode()));
3560
3561 return Map.at(I.getOpcode());
3562}
3563
3564spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
Kévin Petit24272b62018-10-18 19:16:12 +00003565 if (I.getType()->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003566 switch (I.getOpcode()) {
3567 default:
3568 break;
3569 case Instruction::Or:
3570 return spv::OpLogicalOr;
3571 case Instruction::And:
3572 return spv::OpLogicalAnd;
3573 case Instruction::Xor:
3574 return spv::OpLogicalNotEqual;
3575 }
3576 }
3577
alan-bakerb6b09dc2018-11-08 16:59:28 -05003578 const std::map<unsigned, spv::Op> Map{
David Neto22f144c2017-06-12 14:26:21 -04003579 {Instruction::Add, spv::OpIAdd},
3580 {Instruction::FAdd, spv::OpFAdd},
3581 {Instruction::Sub, spv::OpISub},
3582 {Instruction::FSub, spv::OpFSub},
3583 {Instruction::Mul, spv::OpIMul},
3584 {Instruction::FMul, spv::OpFMul},
3585 {Instruction::UDiv, spv::OpUDiv},
3586 {Instruction::SDiv, spv::OpSDiv},
3587 {Instruction::FDiv, spv::OpFDiv},
3588 {Instruction::URem, spv::OpUMod},
3589 {Instruction::SRem, spv::OpSRem},
3590 {Instruction::FRem, spv::OpFRem},
3591 {Instruction::Or, spv::OpBitwiseOr},
3592 {Instruction::Xor, spv::OpBitwiseXor},
3593 {Instruction::And, spv::OpBitwiseAnd},
3594 {Instruction::Shl, spv::OpShiftLeftLogical},
3595 {Instruction::LShr, spv::OpShiftRightLogical},
3596 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3597
3598 assert(0 != Map.count(I.getOpcode()));
3599
3600 return Map.at(I.getOpcode());
3601}
3602
3603void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
3604 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3605 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04003606 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
3607 LLVMContext &Context = I.getParent()->getParent()->getParent()->getContext();
3608
3609 // Register Instruction to ValueMap.
3610 if (0 == VMap[&I]) {
3611 VMap[&I] = nextID;
3612 }
3613
3614 switch (I.getOpcode()) {
3615 default: {
3616 if (Instruction::isCast(I.getOpcode())) {
3617 //
3618 // Generate SPIRV instructions for cast operators.
3619 //
3620
David Netod2de94a2017-08-28 17:27:47 -04003621 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003622 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003623 auto toI8 = Ty == Type::getInt8Ty(Context);
3624 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003625 // Handle zext, sext and uitofp with i1 type specially.
3626 if ((I.getOpcode() == Instruction::ZExt ||
3627 I.getOpcode() == Instruction::SExt ||
3628 I.getOpcode() == Instruction::UIToFP) &&
alan-bakerb6b09dc2018-11-08 16:59:28 -05003629 OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003630 //
3631 // Generate OpSelect.
3632 //
3633
3634 // Ops[0] = Result Type ID
3635 // Ops[1] = Condition ID
3636 // Ops[2] = True Constant ID
3637 // Ops[3] = False Constant ID
3638 SPIRVOperandList Ops;
3639
David Neto257c3892018-04-11 13:19:45 -04003640 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003641
David Neto22f144c2017-06-12 14:26:21 -04003642 uint32_t CondID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003643 Ops << MkId(CondID);
David Neto22f144c2017-06-12 14:26:21 -04003644
3645 uint32_t TrueID = 0;
3646 if (I.getOpcode() == Instruction::ZExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00003647 TrueID = VMap[ConstantInt::get(I.getType(), 1)];
David Neto22f144c2017-06-12 14:26:21 -04003648 } else if (I.getOpcode() == Instruction::SExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00003649 TrueID = VMap[ConstantInt::getSigned(I.getType(), -1)];
David Neto22f144c2017-06-12 14:26:21 -04003650 } else {
3651 TrueID = VMap[ConstantFP::get(Context, APFloat(1.0f))];
3652 }
David Neto257c3892018-04-11 13:19:45 -04003653 Ops << MkId(TrueID);
David Neto22f144c2017-06-12 14:26:21 -04003654
3655 uint32_t FalseID = 0;
3656 if (I.getOpcode() == Instruction::ZExt) {
3657 FalseID = VMap[Constant::getNullValue(I.getType())];
3658 } else if (I.getOpcode() == Instruction::SExt) {
3659 FalseID = VMap[Constant::getNullValue(I.getType())];
3660 } else {
3661 FalseID = VMap[ConstantFP::get(Context, APFloat(0.0f))];
3662 }
David Neto257c3892018-04-11 13:19:45 -04003663 Ops << MkId(FalseID);
David Neto22f144c2017-06-12 14:26:21 -04003664
David Neto87846742018-04-11 17:36:22 -04003665 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003666 SPIRVInstList.push_back(Inst);
alan-bakerb39c8262019-03-08 14:03:37 -05003667 } else if (!clspv::Option::Int8Support() &&
3668 I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
David Netod2de94a2017-08-28 17:27:47 -04003669 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3670 // 8 bits.
3671 // Before:
3672 // %result = trunc i32 %a to i8
3673 // After
3674 // %result = OpBitwiseAnd %uint %a %uint_255
3675
3676 SPIRVOperandList Ops;
3677
David Neto257c3892018-04-11 13:19:45 -04003678 Ops << MkId(lookupType(OpTy)) << MkId(VMap[I.getOperand(0)]);
David Netod2de94a2017-08-28 17:27:47 -04003679
3680 Type *UintTy = Type::getInt32Ty(Context);
3681 uint32_t MaskID = VMap[ConstantInt::get(UintTy, 255)];
David Neto257c3892018-04-11 13:19:45 -04003682 Ops << MkId(MaskID);
David Netod2de94a2017-08-28 17:27:47 -04003683
David Neto87846742018-04-11 17:36:22 -04003684 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Netod2de94a2017-08-28 17:27:47 -04003685 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003686 } else {
3687 // Ops[0] = Result Type ID
3688 // Ops[1] = Source Value ID
3689 SPIRVOperandList Ops;
3690
David Neto257c3892018-04-11 13:19:45 -04003691 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003692
David Neto87846742018-04-11 17:36:22 -04003693 auto *Inst = new SPIRVInstruction(GetSPIRVCastOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003694 SPIRVInstList.push_back(Inst);
3695 }
3696 } else if (isa<BinaryOperator>(I)) {
3697 //
3698 // Generate SPIRV instructions for binary operators.
3699 //
3700
3701 // Handle xor with i1 type specially.
3702 if (I.getOpcode() == Instruction::Xor &&
3703 I.getType() == Type::getInt1Ty(Context) &&
Kévin Petit24272b62018-10-18 19:16:12 +00003704 ((isa<ConstantInt>(I.getOperand(0)) &&
3705 !cast<ConstantInt>(I.getOperand(0))->isZero()) ||
3706 (isa<ConstantInt>(I.getOperand(1)) &&
3707 !cast<ConstantInt>(I.getOperand(1))->isZero()))) {
David Neto22f144c2017-06-12 14:26:21 -04003708 //
3709 // Generate OpLogicalNot.
3710 //
3711 // Ops[0] = Result Type ID
3712 // Ops[1] = Operand
3713 SPIRVOperandList Ops;
3714
David Neto257c3892018-04-11 13:19:45 -04003715 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003716
3717 Value *CondV = I.getOperand(0);
3718 if (isa<Constant>(I.getOperand(0))) {
3719 CondV = I.getOperand(1);
3720 }
David Neto257c3892018-04-11 13:19:45 -04003721 Ops << MkId(VMap[CondV]);
David Neto22f144c2017-06-12 14:26:21 -04003722
David Neto87846742018-04-11 17:36:22 -04003723 auto *Inst = new SPIRVInstruction(spv::OpLogicalNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003724 SPIRVInstList.push_back(Inst);
3725 } else {
3726 // Ops[0] = Result Type ID
3727 // Ops[1] = Operand 0
3728 // Ops[2] = Operand 1
3729 SPIRVOperandList Ops;
3730
David Neto257c3892018-04-11 13:19:45 -04003731 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
3732 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003733
David Neto87846742018-04-11 17:36:22 -04003734 auto *Inst =
3735 new SPIRVInstruction(GetSPIRVBinaryOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003736 SPIRVInstList.push_back(Inst);
3737 }
3738 } else {
3739 I.print(errs());
3740 llvm_unreachable("Unsupported instruction???");
3741 }
3742 break;
3743 }
3744 case Instruction::GetElementPtr: {
3745 auto &GlobalConstArgSet = getGlobalConstArgSet();
3746
3747 //
3748 // Generate OpAccessChain.
3749 //
3750 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
3751
3752 //
3753 // Generate OpAccessChain.
3754 //
3755
3756 // Ops[0] = Result Type ID
3757 // Ops[1] = Base ID
3758 // Ops[2] ... Ops[n] = Indexes ID
3759 SPIRVOperandList Ops;
3760
alan-bakerb6b09dc2018-11-08 16:59:28 -05003761 PointerType *ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04003762 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
3763 GlobalConstArgSet.count(GEP->getPointerOperand())) {
3764 // Use pointer type with private address space for global constant.
3765 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04003766 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04003767 }
David Neto257c3892018-04-11 13:19:45 -04003768
3769 Ops << MkId(lookupType(ResultType));
David Neto22f144c2017-06-12 14:26:21 -04003770
David Neto862b7d82018-06-14 18:48:37 -04003771 // Generate the base pointer.
3772 Ops << MkId(VMap[GEP->getPointerOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04003773
David Neto862b7d82018-06-14 18:48:37 -04003774 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04003775
3776 //
3777 // Follows below rules for gep.
3778 //
David Neto862b7d82018-06-14 18:48:37 -04003779 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
3780 // first index.
David Neto22f144c2017-06-12 14:26:21 -04003781 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
3782 // first index.
3783 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
3784 // use gep's first index.
3785 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
3786 // gep's first index.
3787 //
3788 spv::Op Opcode = spv::OpAccessChain;
3789 unsigned offset = 0;
3790 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04003791 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04003792 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04003793 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04003794 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04003795 }
David Neto862b7d82018-06-14 18:48:37 -04003796 } else {
David Neto22f144c2017-06-12 14:26:21 -04003797 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04003798 }
3799
3800 if (Opcode == spv::OpPtrAccessChain) {
David Neto1a1a0582017-07-07 12:01:44 -04003801 // Do we need to generate ArrayStride? Check against the GEP result type
3802 // rather than the pointer type of the base because when indexing into
3803 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
3804 // for something else in the SPIR-V.
3805 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
alan-baker5b86ed72019-02-15 08:26:50 -05003806 auto address_space = ResultType->getAddressSpace();
3807 setVariablePointersCapabilities(address_space);
3808 switch (GetStorageClass(address_space)) {
Alan Bakerfcda9482018-10-02 17:09:59 -04003809 case spv::StorageClassStorageBuffer:
3810 case spv::StorageClassUniform:
David Neto1a1a0582017-07-07 12:01:44 -04003811 // Save the need to generate an ArrayStride decoration. But defer
3812 // generation until later, so we only make one decoration.
David Neto85082642018-03-24 06:55:20 -07003813 getTypesNeedingArrayStride().insert(ResultType);
Alan Bakerfcda9482018-10-02 17:09:59 -04003814 break;
3815 default:
3816 break;
David Neto1a1a0582017-07-07 12:01:44 -04003817 }
David Neto22f144c2017-06-12 14:26:21 -04003818 }
3819
3820 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
David Neto257c3892018-04-11 13:19:45 -04003821 Ops << MkId(VMap[*II]);
David Neto22f144c2017-06-12 14:26:21 -04003822 }
3823
David Neto87846742018-04-11 17:36:22 -04003824 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003825 SPIRVInstList.push_back(Inst);
3826 break;
3827 }
3828 case Instruction::ExtractValue: {
3829 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3830 // Ops[0] = Result Type ID
3831 // Ops[1] = Composite ID
3832 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3833 SPIRVOperandList Ops;
3834
David Neto257c3892018-04-11 13:19:45 -04003835 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003836
3837 uint32_t CompositeID = VMap[EVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003838 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003839
3840 for (auto &Index : EVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003841 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003842 }
3843
David Neto87846742018-04-11 17:36:22 -04003844 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003845 SPIRVInstList.push_back(Inst);
3846 break;
3847 }
3848 case Instruction::InsertValue: {
3849 InsertValueInst *IVI = cast<InsertValueInst>(&I);
3850 // Ops[0] = Result Type ID
3851 // Ops[1] = Object ID
3852 // Ops[2] = Composite ID
3853 // Ops[3] ... Ops[n] = Indexes (Literal Number)
3854 SPIRVOperandList Ops;
3855
3856 uint32_t ResTyID = lookupType(I.getType());
David Neto257c3892018-04-11 13:19:45 -04003857 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04003858
3859 uint32_t ObjectID = VMap[IVI->getInsertedValueOperand()];
David Neto257c3892018-04-11 13:19:45 -04003860 Ops << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04003861
3862 uint32_t CompositeID = VMap[IVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003863 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003864
3865 for (auto &Index : IVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003866 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003867 }
3868
David Neto87846742018-04-11 17:36:22 -04003869 auto *Inst = new SPIRVInstruction(spv::OpCompositeInsert, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003870 SPIRVInstList.push_back(Inst);
3871 break;
3872 }
3873 case Instruction::Select: {
3874 //
3875 // Generate OpSelect.
3876 //
3877
3878 // Ops[0] = Result Type ID
3879 // Ops[1] = Condition ID
3880 // Ops[2] = True Constant ID
3881 // Ops[3] = False Constant ID
3882 SPIRVOperandList Ops;
3883
3884 // Find SPIRV instruction for parameter type.
3885 auto Ty = I.getType();
3886 if (Ty->isPointerTy()) {
3887 auto PointeeTy = Ty->getPointerElementType();
3888 if (PointeeTy->isStructTy() &&
3889 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
3890 Ty = PointeeTy;
alan-baker5b86ed72019-02-15 08:26:50 -05003891 } else {
3892 // Selecting between pointers requires variable pointers.
3893 setVariablePointersCapabilities(Ty->getPointerAddressSpace());
3894 if (!hasVariablePointers() && !selectFromSameObject(&I)) {
3895 setVariablePointers(true);
3896 }
David Neto22f144c2017-06-12 14:26:21 -04003897 }
3898 }
3899
David Neto257c3892018-04-11 13:19:45 -04003900 Ops << MkId(lookupType(Ty)) << MkId(VMap[I.getOperand(0)])
3901 << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003902
David Neto87846742018-04-11 17:36:22 -04003903 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003904 SPIRVInstList.push_back(Inst);
3905 break;
3906 }
3907 case Instruction::ExtractElement: {
3908 // Handle <4 x i8> type manually.
3909 Type *CompositeTy = I.getOperand(0)->getType();
3910 if (is4xi8vec(CompositeTy)) {
3911 //
3912 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
3913 // <4 x i8>.
3914 //
3915
3916 //
3917 // Generate OpShiftRightLogical
3918 //
3919 // Ops[0] = Result Type ID
3920 // Ops[1] = Operand 0
3921 // Ops[2] = Operand 1
3922 //
3923 SPIRVOperandList Ops;
3924
David Neto257c3892018-04-11 13:19:45 -04003925 Ops << MkId(lookupType(CompositeTy));
David Neto22f144c2017-06-12 14:26:21 -04003926
3927 uint32_t Op0ID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003928 Ops << MkId(Op0ID);
David Neto22f144c2017-06-12 14:26:21 -04003929
3930 uint32_t Op1ID = 0;
3931 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
3932 // Handle constant index.
3933 uint64_t Idx = CI->getZExtValue();
3934 Value *ShiftAmount =
3935 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3936 Op1ID = VMap[ShiftAmount];
3937 } else {
3938 // Handle variable index.
3939 SPIRVOperandList TmpOps;
3940
David Neto257c3892018-04-11 13:19:45 -04003941 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3942 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003943
3944 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003945 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003946
3947 Op1ID = nextID;
3948
David Neto87846742018-04-11 17:36:22 -04003949 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003950 SPIRVInstList.push_back(TmpInst);
3951 }
David Neto257c3892018-04-11 13:19:45 -04003952 Ops << MkId(Op1ID);
David Neto22f144c2017-06-12 14:26:21 -04003953
3954 uint32_t ShiftID = nextID;
3955
David Neto87846742018-04-11 17:36:22 -04003956 auto *Inst =
3957 new SPIRVInstruction(spv::OpShiftRightLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003958 SPIRVInstList.push_back(Inst);
3959
3960 //
3961 // Generate OpBitwiseAnd
3962 //
3963 // Ops[0] = Result Type ID
3964 // Ops[1] = Operand 0
3965 // Ops[2] = Operand 1
3966 //
3967 Ops.clear();
3968
David Neto257c3892018-04-11 13:19:45 -04003969 Ops << MkId(lookupType(CompositeTy)) << MkId(ShiftID);
David Neto22f144c2017-06-12 14:26:21 -04003970
3971 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
David Neto257c3892018-04-11 13:19:45 -04003972 Ops << MkId(VMap[CstFF]);
David Neto22f144c2017-06-12 14:26:21 -04003973
David Neto9b2d6252017-09-06 15:47:37 -04003974 // Reset mapping for this value to the result of the bitwise and.
3975 VMap[&I] = nextID;
3976
David Neto87846742018-04-11 17:36:22 -04003977 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003978 SPIRVInstList.push_back(Inst);
3979 break;
3980 }
3981
3982 // Ops[0] = Result Type ID
3983 // Ops[1] = Composite ID
3984 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3985 SPIRVOperandList Ops;
3986
David Neto257c3892018-04-11 13:19:45 -04003987 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003988
3989 spv::Op Opcode = spv::OpCompositeExtract;
3990 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
David Neto257c3892018-04-11 13:19:45 -04003991 Ops << MkNum(static_cast<uint32_t>(CI->getZExtValue()));
David Neto22f144c2017-06-12 14:26:21 -04003992 } else {
David Neto257c3892018-04-11 13:19:45 -04003993 Ops << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003994 Opcode = spv::OpVectorExtractDynamic;
3995 }
3996
David Neto87846742018-04-11 17:36:22 -04003997 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003998 SPIRVInstList.push_back(Inst);
3999 break;
4000 }
4001 case Instruction::InsertElement: {
4002 // Handle <4 x i8> type manually.
4003 Type *CompositeTy = I.getOperand(0)->getType();
4004 if (is4xi8vec(CompositeTy)) {
4005 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
4006 uint32_t CstFFID = VMap[CstFF];
4007
4008 uint32_t ShiftAmountID = 0;
4009 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
4010 // Handle constant index.
4011 uint64_t Idx = CI->getZExtValue();
4012 Value *ShiftAmount =
4013 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
4014 ShiftAmountID = VMap[ShiftAmount];
4015 } else {
4016 // Handle variable index.
4017 SPIRVOperandList TmpOps;
4018
David Neto257c3892018-04-11 13:19:45 -04004019 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
4020 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004021
4022 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04004023 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04004024
4025 ShiftAmountID = nextID;
4026
David Neto87846742018-04-11 17:36:22 -04004027 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004028 SPIRVInstList.push_back(TmpInst);
4029 }
4030
4031 //
4032 // Generate mask operations.
4033 //
4034
4035 // ShiftLeft mask according to index of insertelement.
4036 SPIRVOperandList Ops;
4037
David Neto257c3892018-04-11 13:19:45 -04004038 const uint32_t ResTyID = lookupType(CompositeTy);
4039 Ops << MkId(ResTyID) << MkId(CstFFID) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004040
4041 uint32_t MaskID = nextID;
4042
David Neto87846742018-04-11 17:36:22 -04004043 auto *Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004044 SPIRVInstList.push_back(Inst);
4045
4046 // Inverse mask.
4047 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004048 Ops << MkId(ResTyID) << MkId(MaskID);
David Neto22f144c2017-06-12 14:26:21 -04004049
4050 uint32_t InvMaskID = nextID;
4051
David Neto87846742018-04-11 17:36:22 -04004052 Inst = new SPIRVInstruction(spv::OpNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004053 SPIRVInstList.push_back(Inst);
4054
4055 // Apply mask.
4056 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004057 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(0)]) << MkId(InvMaskID);
David Neto22f144c2017-06-12 14:26:21 -04004058
4059 uint32_t OrgValID = nextID;
4060
David Neto87846742018-04-11 17:36:22 -04004061 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004062 SPIRVInstList.push_back(Inst);
4063
4064 // Create correct value according to index of insertelement.
4065 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05004066 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(1)])
4067 << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004068
4069 uint32_t InsertValID = nextID;
4070
David Neto87846742018-04-11 17:36:22 -04004071 Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004072 SPIRVInstList.push_back(Inst);
4073
4074 // Insert value to original value.
4075 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004076 Ops << MkId(ResTyID) << MkId(OrgValID) << MkId(InsertValID);
David Neto22f144c2017-06-12 14:26:21 -04004077
David Netoa394f392017-08-26 20:45:29 -04004078 VMap[&I] = nextID;
4079
David Neto87846742018-04-11 17:36:22 -04004080 Inst = new SPIRVInstruction(spv::OpBitwiseOr, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004081 SPIRVInstList.push_back(Inst);
4082
4083 break;
4084 }
4085
David Neto22f144c2017-06-12 14:26:21 -04004086 SPIRVOperandList Ops;
4087
James Priced26efea2018-06-09 23:28:32 +01004088 // Ops[0] = Result Type ID
4089 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004090
4091 spv::Op Opcode = spv::OpCompositeInsert;
4092 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04004093 const auto value = CI->getZExtValue();
4094 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01004095 // Ops[1] = Object ID
4096 // Ops[2] = Composite ID
4097 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004098 Ops << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(0)])
James Priced26efea2018-06-09 23:28:32 +01004099 << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004100 } else {
James Priced26efea2018-06-09 23:28:32 +01004101 // Ops[1] = Composite ID
4102 // Ops[2] = Object ID
4103 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004104 Ops << MkId(VMap[I.getOperand(0)]) << MkId(VMap[I.getOperand(1)])
James Priced26efea2018-06-09 23:28:32 +01004105 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004106 Opcode = spv::OpVectorInsertDynamic;
4107 }
4108
David Neto87846742018-04-11 17:36:22 -04004109 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004110 SPIRVInstList.push_back(Inst);
4111 break;
4112 }
4113 case Instruction::ShuffleVector: {
4114 // Ops[0] = Result Type ID
4115 // Ops[1] = Vector 1 ID
4116 // Ops[2] = Vector 2 ID
4117 // Ops[3] ... Ops[n] = Components (Literal Number)
4118 SPIRVOperandList Ops;
4119
David Neto257c3892018-04-11 13:19:45 -04004120 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4121 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004122
4123 uint64_t NumElements = 0;
4124 if (Constant *Cst = dyn_cast<Constant>(I.getOperand(2))) {
4125 NumElements = cast<VectorType>(Cst->getType())->getNumElements();
4126
4127 if (Cst->isNullValue()) {
4128 for (unsigned i = 0; i < NumElements; i++) {
David Neto257c3892018-04-11 13:19:45 -04004129 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04004130 }
4131 } else if (const ConstantDataSequential *CDS =
4132 dyn_cast<ConstantDataSequential>(Cst)) {
4133 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
4134 std::vector<uint32_t> LiteralNum;
David Neto257c3892018-04-11 13:19:45 -04004135 const auto value = CDS->getElementAsInteger(i);
4136 assert(value <= UINT32_MAX);
4137 Ops << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004138 }
4139 } else if (const ConstantVector *CV = dyn_cast<ConstantVector>(Cst)) {
4140 for (unsigned i = 0; i < CV->getNumOperands(); i++) {
4141 auto Op = CV->getOperand(i);
4142
4143 uint32_t literal = 0;
4144
4145 if (auto CI = dyn_cast<ConstantInt>(Op)) {
4146 literal = static_cast<uint32_t>(CI->getZExtValue());
4147 } else if (auto UI = dyn_cast<UndefValue>(Op)) {
4148 literal = 0xFFFFFFFFu;
4149 } else {
4150 Op->print(errs());
4151 llvm_unreachable("Unsupported element in ConstantVector!");
4152 }
4153
David Neto257c3892018-04-11 13:19:45 -04004154 Ops << MkNum(literal);
David Neto22f144c2017-06-12 14:26:21 -04004155 }
4156 } else {
4157 Cst->print(errs());
4158 llvm_unreachable("Unsupported constant mask in ShuffleVector!");
4159 }
4160 }
4161
David Neto87846742018-04-11 17:36:22 -04004162 auto *Inst = new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004163 SPIRVInstList.push_back(Inst);
4164 break;
4165 }
4166 case Instruction::ICmp:
4167 case Instruction::FCmp: {
4168 CmpInst *CmpI = cast<CmpInst>(&I);
4169
David Netod4ca2e62017-07-06 18:47:35 -04004170 // Pointer equality is invalid.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004171 Type *ArgTy = CmpI->getOperand(0)->getType();
David Netod4ca2e62017-07-06 18:47:35 -04004172 if (isa<PointerType>(ArgTy)) {
4173 CmpI->print(errs());
4174 std::string name = I.getParent()->getParent()->getName();
4175 errs()
4176 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4177 << "in function " << name << "\n";
4178 llvm_unreachable("Pointer equality check is invalid");
4179 break;
4180 }
4181
David Neto257c3892018-04-11 13:19:45 -04004182 // Ops[0] = Result Type ID
4183 // Ops[1] = Operand 1 ID
4184 // Ops[2] = Operand 2 ID
4185 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004186
David Neto257c3892018-04-11 13:19:45 -04004187 Ops << MkId(lookupType(CmpI->getType())) << MkId(VMap[CmpI->getOperand(0)])
4188 << MkId(VMap[CmpI->getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004189
4190 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
David Neto87846742018-04-11 17:36:22 -04004191 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004192 SPIRVInstList.push_back(Inst);
4193 break;
4194 }
4195 case Instruction::Br: {
4196 // Branch instrucion is deferred because it needs label's ID. Record slot's
4197 // location on SPIRVInstructionList.
4198 DeferredInsts.push_back(
4199 std::make_tuple(&I, --SPIRVInstList.end(), 0 /* No id */));
4200 break;
4201 }
4202 case Instruction::Switch: {
4203 I.print(errs());
4204 llvm_unreachable("Unsupported instruction???");
4205 break;
4206 }
4207 case Instruction::IndirectBr: {
4208 I.print(errs());
4209 llvm_unreachable("Unsupported instruction???");
4210 break;
4211 }
4212 case Instruction::PHI: {
4213 // Branch instrucion is deferred because it needs label's ID. Record slot's
4214 // location on SPIRVInstructionList.
4215 DeferredInsts.push_back(
4216 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4217 break;
4218 }
4219 case Instruction::Alloca: {
4220 //
4221 // Generate OpVariable.
4222 //
4223 // Ops[0] : Result Type ID
4224 // Ops[1] : Storage Class
4225 SPIRVOperandList Ops;
4226
David Neto257c3892018-04-11 13:19:45 -04004227 Ops << MkId(lookupType(I.getType())) << MkNum(spv::StorageClassFunction);
David Neto22f144c2017-06-12 14:26:21 -04004228
David Neto87846742018-04-11 17:36:22 -04004229 auto *Inst = new SPIRVInstruction(spv::OpVariable, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004230 SPIRVInstList.push_back(Inst);
4231 break;
4232 }
4233 case Instruction::Load: {
4234 LoadInst *LD = cast<LoadInst>(&I);
4235 //
4236 // Generate OpLoad.
4237 //
alan-baker5b86ed72019-02-15 08:26:50 -05004238
4239 if (LD->getType()->isPointerTy()) {
4240 // Loading a pointer requires variable pointers.
4241 setVariablePointersCapabilities(LD->getType()->getPointerAddressSpace());
4242 }
David Neto22f144c2017-06-12 14:26:21 -04004243
David Neto0a2f98d2017-09-15 19:38:40 -04004244 uint32_t ResTyID = lookupType(LD->getType());
David Netoa60b00b2017-09-15 16:34:09 -04004245 uint32_t PointerID = VMap[LD->getPointerOperand()];
4246
4247 // This is a hack to work around what looks like a driver bug.
4248 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004249 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4250 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004251 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004252 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004253 // Generate a bitwise-and of the original value with itself.
4254 // We should have been able to get away with just an OpCopyObject,
4255 // but we need something more complex to get past certain driver bugs.
4256 // This is ridiculous, but necessary.
4257 // TODO(dneto): Revisit this once drivers fix their bugs.
4258
4259 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004260 Ops << MkId(ResTyID) << MkId(WorkgroupSizeValueID)
4261 << MkId(WorkgroupSizeValueID);
David Neto0a2f98d2017-09-15 19:38:40 -04004262
David Neto87846742018-04-11 17:36:22 -04004263 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto0a2f98d2017-09-15 19:38:40 -04004264 SPIRVInstList.push_back(Inst);
David Netoa60b00b2017-09-15 16:34:09 -04004265 break;
4266 }
4267
4268 // This is the normal path. Generate a load.
4269
David Neto22f144c2017-06-12 14:26:21 -04004270 // Ops[0] = Result Type ID
4271 // Ops[1] = Pointer ID
4272 // Ops[2] ... Ops[n] = Optional Memory Access
4273 //
4274 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004275
David Neto22f144c2017-06-12 14:26:21 -04004276 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004277 Ops << MkId(ResTyID) << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04004278
David Neto87846742018-04-11 17:36:22 -04004279 auto *Inst = new SPIRVInstruction(spv::OpLoad, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004280 SPIRVInstList.push_back(Inst);
4281 break;
4282 }
4283 case Instruction::Store: {
4284 StoreInst *ST = cast<StoreInst>(&I);
4285 //
4286 // Generate OpStore.
4287 //
4288
alan-baker5b86ed72019-02-15 08:26:50 -05004289 if (ST->getValueOperand()->getType()->isPointerTy()) {
4290 // Storing a pointer requires variable pointers.
4291 setVariablePointersCapabilities(
4292 ST->getValueOperand()->getType()->getPointerAddressSpace());
4293 }
4294
David Neto22f144c2017-06-12 14:26:21 -04004295 // Ops[0] = Pointer ID
4296 // Ops[1] = Object ID
4297 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4298 //
4299 // TODO: Do we need to implement Optional Memory Access???
David Neto257c3892018-04-11 13:19:45 -04004300 SPIRVOperandList Ops;
4301 Ops << MkId(VMap[ST->getPointerOperand()])
4302 << MkId(VMap[ST->getValueOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004303
David Neto87846742018-04-11 17:36:22 -04004304 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004305 SPIRVInstList.push_back(Inst);
4306 break;
4307 }
4308 case Instruction::AtomicCmpXchg: {
4309 I.print(errs());
4310 llvm_unreachable("Unsupported instruction???");
4311 break;
4312 }
4313 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004314 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4315
4316 spv::Op opcode;
4317
4318 switch (AtomicRMW->getOperation()) {
4319 default:
4320 I.print(errs());
4321 llvm_unreachable("Unsupported instruction???");
4322 case llvm::AtomicRMWInst::Add:
4323 opcode = spv::OpAtomicIAdd;
4324 break;
4325 case llvm::AtomicRMWInst::Sub:
4326 opcode = spv::OpAtomicISub;
4327 break;
4328 case llvm::AtomicRMWInst::Xchg:
4329 opcode = spv::OpAtomicExchange;
4330 break;
4331 case llvm::AtomicRMWInst::Min:
4332 opcode = spv::OpAtomicSMin;
4333 break;
4334 case llvm::AtomicRMWInst::Max:
4335 opcode = spv::OpAtomicSMax;
4336 break;
4337 case llvm::AtomicRMWInst::UMin:
4338 opcode = spv::OpAtomicUMin;
4339 break;
4340 case llvm::AtomicRMWInst::UMax:
4341 opcode = spv::OpAtomicUMax;
4342 break;
4343 case llvm::AtomicRMWInst::And:
4344 opcode = spv::OpAtomicAnd;
4345 break;
4346 case llvm::AtomicRMWInst::Or:
4347 opcode = spv::OpAtomicOr;
4348 break;
4349 case llvm::AtomicRMWInst::Xor:
4350 opcode = spv::OpAtomicXor;
4351 break;
4352 }
4353
4354 //
4355 // Generate OpAtomic*.
4356 //
4357 SPIRVOperandList Ops;
4358
David Neto257c3892018-04-11 13:19:45 -04004359 Ops << MkId(lookupType(I.getType()))
4360 << MkId(VMap[AtomicRMW->getPointerOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004361
4362 auto IntTy = Type::getInt32Ty(I.getContext());
Neil Henning39672102017-09-29 14:33:13 +01004363 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
David Neto257c3892018-04-11 13:19:45 -04004364 Ops << MkId(VMap[ConstantScopeDevice]);
Neil Henning39672102017-09-29 14:33:13 +01004365
4366 const auto ConstantMemorySemantics = ConstantInt::get(
4367 IntTy, spv::MemorySemanticsUniformMemoryMask |
4368 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto257c3892018-04-11 13:19:45 -04004369 Ops << MkId(VMap[ConstantMemorySemantics]);
Neil Henning39672102017-09-29 14:33:13 +01004370
David Neto257c3892018-04-11 13:19:45 -04004371 Ops << MkId(VMap[AtomicRMW->getValOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004372
4373 VMap[&I] = nextID;
4374
David Neto87846742018-04-11 17:36:22 -04004375 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
Neil Henning39672102017-09-29 14:33:13 +01004376 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004377 break;
4378 }
4379 case Instruction::Fence: {
4380 I.print(errs());
4381 llvm_unreachable("Unsupported instruction???");
4382 break;
4383 }
4384 case Instruction::Call: {
4385 CallInst *Call = dyn_cast<CallInst>(&I);
4386 Function *Callee = Call->getCalledFunction();
4387
Alan Baker202c8c72018-08-13 13:47:44 -04004388 if (Callee->getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004389 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
4390 // Generate an OpLoad
4391 SPIRVOperandList Ops;
4392 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004393
David Neto862b7d82018-06-14 18:48:37 -04004394 Ops << MkId(lookupType(Call->getType()->getPointerElementType()))
4395 << MkId(ResourceVarDeferredLoadCalls[Call]);
4396
4397 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
4398 SPIRVInstList.push_back(Inst);
4399 VMap[Call] = load_id;
4400 break;
4401
4402 } else {
4403 // This maps to an OpVariable we've already generated.
4404 // No code is generated for the call.
4405 }
4406 break;
alan-bakerb6b09dc2018-11-08 16:59:28 -05004407 } else if (Callee->getName().startswith(
4408 clspv::WorkgroupAccessorFunction())) {
Alan Baker202c8c72018-08-13 13:47:44 -04004409 // Don't codegen an instruction here, but instead map this call directly
4410 // to the workgroup variable id.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004411 int spec_id = static_cast<int>(
4412 cast<ConstantInt>(Call->getOperand(0))->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04004413 const auto &info = LocalSpecIdInfoMap[spec_id];
4414 VMap[Call] = info.variable_id;
4415 break;
David Neto862b7d82018-06-14 18:48:37 -04004416 }
4417
4418 // Sampler initializers become a load of the corresponding sampler.
4419
4420 if (Callee->getName().equals("clspv.sampler.var.literal")) {
4421 // Map this to a load from the variable.
4422 const auto index_into_sampler_map =
4423 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4424
4425 // Generate an OpLoad
David Neto22f144c2017-06-12 14:26:21 -04004426 SPIRVOperandList Ops;
David Neto862b7d82018-06-14 18:48:37 -04004427 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004428
David Neto257c3892018-04-11 13:19:45 -04004429 Ops << MkId(lookupType(SamplerTy->getPointerElementType()))
alan-bakerb6b09dc2018-11-08 16:59:28 -05004430 << MkId(SamplerMapIndexToIDMap[static_cast<unsigned>(
4431 index_into_sampler_map)]);
David Neto22f144c2017-06-12 14:26:21 -04004432
David Neto862b7d82018-06-14 18:48:37 -04004433 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004434 SPIRVInstList.push_back(Inst);
David Neto862b7d82018-06-14 18:48:37 -04004435 VMap[Call] = load_id;
David Neto22f144c2017-06-12 14:26:21 -04004436 break;
4437 }
4438
4439 if (Callee->getName().startswith("spirv.atomic")) {
4440 spv::Op opcode = StringSwitch<spv::Op>(Callee->getName())
4441 .Case("spirv.atomic_add", spv::OpAtomicIAdd)
4442 .Case("spirv.atomic_sub", spv::OpAtomicISub)
4443 .Case("spirv.atomic_exchange", spv::OpAtomicExchange)
4444 .Case("spirv.atomic_inc", spv::OpAtomicIIncrement)
4445 .Case("spirv.atomic_dec", spv::OpAtomicIDecrement)
4446 .Case("spirv.atomic_compare_exchange",
4447 spv::OpAtomicCompareExchange)
4448 .Case("spirv.atomic_umin", spv::OpAtomicUMin)
4449 .Case("spirv.atomic_smin", spv::OpAtomicSMin)
4450 .Case("spirv.atomic_umax", spv::OpAtomicUMax)
4451 .Case("spirv.atomic_smax", spv::OpAtomicSMax)
4452 .Case("spirv.atomic_and", spv::OpAtomicAnd)
4453 .Case("spirv.atomic_or", spv::OpAtomicOr)
4454 .Case("spirv.atomic_xor", spv::OpAtomicXor)
4455 .Default(spv::OpNop);
4456
4457 //
4458 // Generate OpAtomic*.
4459 //
4460 SPIRVOperandList Ops;
4461
David Neto257c3892018-04-11 13:19:45 -04004462 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004463
4464 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004465 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004466 }
4467
4468 VMap[&I] = nextID;
4469
David Neto87846742018-04-11 17:36:22 -04004470 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004471 SPIRVInstList.push_back(Inst);
4472 break;
4473 }
4474
4475 if (Callee->getName().startswith("_Z3dot")) {
4476 // If the argument is a vector type, generate OpDot
4477 if (Call->getArgOperand(0)->getType()->isVectorTy()) {
4478 //
4479 // Generate OpDot.
4480 //
4481 SPIRVOperandList Ops;
4482
David Neto257c3892018-04-11 13:19:45 -04004483 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004484
4485 for (unsigned i = 0; 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
4489 VMap[&I] = nextID;
4490
David Neto87846742018-04-11 17:36:22 -04004491 auto *Inst = new SPIRVInstruction(spv::OpDot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004492 SPIRVInstList.push_back(Inst);
4493 } else {
4494 //
4495 // Generate OpFMul.
4496 //
4497 SPIRVOperandList Ops;
4498
David Neto257c3892018-04-11 13:19:45 -04004499 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004500
4501 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004502 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004503 }
4504
4505 VMap[&I] = nextID;
4506
David Neto87846742018-04-11 17:36:22 -04004507 auto *Inst = new SPIRVInstruction(spv::OpFMul, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004508 SPIRVInstList.push_back(Inst);
4509 }
4510 break;
4511 }
4512
David Neto8505ebf2017-10-13 18:50:50 -04004513 if (Callee->getName().startswith("_Z4fmod")) {
4514 // OpenCL fmod(x,y) is x - y * trunc(x/y)
4515 // The sign for a non-zero result is taken from x.
4516 // (Try an example.)
4517 // So translate to OpFRem
4518
4519 SPIRVOperandList Ops;
4520
David Neto257c3892018-04-11 13:19:45 -04004521 Ops << MkId(lookupType(I.getType()));
David Neto8505ebf2017-10-13 18:50:50 -04004522
4523 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004524 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto8505ebf2017-10-13 18:50:50 -04004525 }
4526
4527 VMap[&I] = nextID;
4528
David Neto87846742018-04-11 17:36:22 -04004529 auto *Inst = new SPIRVInstruction(spv::OpFRem, nextID++, Ops);
David Neto8505ebf2017-10-13 18:50:50 -04004530 SPIRVInstList.push_back(Inst);
4531 break;
4532 }
4533
David Neto22f144c2017-06-12 14:26:21 -04004534 // spirv.store_null.* intrinsics become OpStore's.
4535 if (Callee->getName().startswith("spirv.store_null")) {
4536 //
4537 // Generate OpStore.
4538 //
4539
4540 // Ops[0] = Pointer ID
4541 // Ops[1] = Object ID
4542 // Ops[2] ... Ops[n]
4543 SPIRVOperandList Ops;
4544
4545 uint32_t PointerID = VMap[Call->getArgOperand(0)];
David Neto22f144c2017-06-12 14:26:21 -04004546 uint32_t ObjectID = VMap[Call->getArgOperand(1)];
David Neto257c3892018-04-11 13:19:45 -04004547 Ops << MkId(PointerID) << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04004548
David Neto87846742018-04-11 17:36:22 -04004549 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpStore, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004550
4551 break;
4552 }
4553
4554 // spirv.copy_memory.* intrinsics become OpMemoryMemory's.
4555 if (Callee->getName().startswith("spirv.copy_memory")) {
4556 //
4557 // Generate OpCopyMemory.
4558 //
4559
4560 // Ops[0] = Dst ID
4561 // Ops[1] = Src ID
4562 // Ops[2] = Memory Access
4563 // Ops[3] = Alignment
4564
4565 auto IsVolatile =
4566 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
4567
4568 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
4569 : spv::MemoryAccessMaskNone;
4570
4571 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
4572
4573 auto Alignment =
4574 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4575
David Neto257c3892018-04-11 13:19:45 -04004576 SPIRVOperandList Ops;
4577 Ops << MkId(VMap[Call->getArgOperand(0)])
4578 << MkId(VMap[Call->getArgOperand(1)]) << MkNum(MemoryAccess)
4579 << MkNum(static_cast<uint32_t>(Alignment));
David Neto22f144c2017-06-12 14:26:21 -04004580
David Neto87846742018-04-11 17:36:22 -04004581 auto *Inst = new SPIRVInstruction(spv::OpCopyMemory, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004582
4583 SPIRVInstList.push_back(Inst);
4584
4585 break;
4586 }
4587
4588 // Nothing to do for abs with uint. Map abs's operand ID to VMap for abs
4589 // with unit.
4590 if (Callee->getName().equals("_Z3absj") ||
4591 Callee->getName().equals("_Z3absDv2_j") ||
4592 Callee->getName().equals("_Z3absDv3_j") ||
alan-bakerb39c8262019-03-08 14:03:37 -05004593 Callee->getName().equals("_Z3absDv4_j") ||
4594 Callee->getName().equals("_Z3absh") ||
4595 Callee->getName().equals("_Z3absDv2_h") ||
4596 Callee->getName().equals("_Z3absDv3_h") ||
4597 Callee->getName().equals("_Z3absDv4_h")) {
David Neto22f144c2017-06-12 14:26:21 -04004598 VMap[&I] = VMap[Call->getOperand(0)];
4599 break;
4600 }
4601
4602 // barrier is converted to OpControlBarrier
4603 if (Callee->getName().equals("__spirv_control_barrier")) {
4604 //
4605 // Generate OpControlBarrier.
4606 //
4607 // Ops[0] = Execution Scope ID
4608 // Ops[1] = Memory Scope ID
4609 // Ops[2] = Memory Semantics ID
4610 //
4611 Value *ExecutionScope = Call->getArgOperand(0);
4612 Value *MemoryScope = Call->getArgOperand(1);
4613 Value *MemorySemantics = Call->getArgOperand(2);
4614
David Neto257c3892018-04-11 13:19:45 -04004615 SPIRVOperandList Ops;
4616 Ops << MkId(VMap[ExecutionScope]) << MkId(VMap[MemoryScope])
4617 << MkId(VMap[MemorySemantics]);
David Neto22f144c2017-06-12 14:26:21 -04004618
David Neto87846742018-04-11 17:36:22 -04004619 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpControlBarrier, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004620 break;
4621 }
4622
4623 // memory barrier is converted to OpMemoryBarrier
4624 if (Callee->getName().equals("__spirv_memory_barrier")) {
4625 //
4626 // Generate OpMemoryBarrier.
4627 //
4628 // Ops[0] = Memory Scope ID
4629 // Ops[1] = Memory Semantics ID
4630 //
4631 SPIRVOperandList Ops;
4632
David Neto257c3892018-04-11 13:19:45 -04004633 uint32_t MemoryScopeID = VMap[Call->getArgOperand(0)];
4634 uint32_t MemorySemanticsID = VMap[Call->getArgOperand(1)];
David Neto22f144c2017-06-12 14:26:21 -04004635
David Neto257c3892018-04-11 13:19:45 -04004636 Ops << MkId(MemoryScopeID) << MkId(MemorySemanticsID);
David Neto22f144c2017-06-12 14:26:21 -04004637
David Neto87846742018-04-11 17:36:22 -04004638 auto *Inst = new SPIRVInstruction(spv::OpMemoryBarrier, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004639 SPIRVInstList.push_back(Inst);
4640 break;
4641 }
4642
4643 // isinf is converted to OpIsInf
4644 if (Callee->getName().equals("__spirv_isinff") ||
4645 Callee->getName().equals("__spirv_isinfDv2_f") ||
4646 Callee->getName().equals("__spirv_isinfDv3_f") ||
4647 Callee->getName().equals("__spirv_isinfDv4_f")) {
4648 //
4649 // Generate OpIsInf.
4650 //
4651 // Ops[0] = Result Type ID
4652 // Ops[1] = X ID
4653 //
4654 SPIRVOperandList Ops;
4655
David Neto257c3892018-04-11 13:19:45 -04004656 Ops << MkId(lookupType(I.getType()))
4657 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004658
4659 VMap[&I] = nextID;
4660
David Neto87846742018-04-11 17:36:22 -04004661 auto *Inst = new SPIRVInstruction(spv::OpIsInf, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004662 SPIRVInstList.push_back(Inst);
4663 break;
4664 }
4665
4666 // isnan is converted to OpIsNan
4667 if (Callee->getName().equals("__spirv_isnanf") ||
4668 Callee->getName().equals("__spirv_isnanDv2_f") ||
4669 Callee->getName().equals("__spirv_isnanDv3_f") ||
4670 Callee->getName().equals("__spirv_isnanDv4_f")) {
4671 //
4672 // Generate OpIsInf.
4673 //
4674 // Ops[0] = Result Type ID
4675 // Ops[1] = X ID
4676 //
4677 SPIRVOperandList Ops;
4678
David Neto257c3892018-04-11 13:19:45 -04004679 Ops << MkId(lookupType(I.getType()))
4680 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004681
4682 VMap[&I] = nextID;
4683
David Neto87846742018-04-11 17:36:22 -04004684 auto *Inst = new SPIRVInstruction(spv::OpIsNan, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004685 SPIRVInstList.push_back(Inst);
4686 break;
4687 }
4688
4689 // all is converted to OpAll
Kévin Petitfd27cca2018-10-31 13:00:17 +00004690 if (Callee->getName().startswith("__spirv_allDv")) {
David Neto22f144c2017-06-12 14:26:21 -04004691 //
4692 // Generate OpAll.
4693 //
4694 // Ops[0] = Result Type ID
4695 // Ops[1] = Vector ID
4696 //
4697 SPIRVOperandList Ops;
4698
David Neto257c3892018-04-11 13:19:45 -04004699 Ops << MkId(lookupType(I.getType()))
4700 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004701
4702 VMap[&I] = nextID;
4703
David Neto87846742018-04-11 17:36:22 -04004704 auto *Inst = new SPIRVInstruction(spv::OpAll, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004705 SPIRVInstList.push_back(Inst);
4706 break;
4707 }
4708
4709 // any is converted to OpAny
Kévin Petitfd27cca2018-10-31 13:00:17 +00004710 if (Callee->getName().startswith("__spirv_anyDv")) {
David Neto22f144c2017-06-12 14:26:21 -04004711 //
4712 // Generate OpAny.
4713 //
4714 // Ops[0] = Result Type ID
4715 // Ops[1] = Vector ID
4716 //
4717 SPIRVOperandList Ops;
4718
David Neto257c3892018-04-11 13:19:45 -04004719 Ops << MkId(lookupType(I.getType()))
4720 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004721
4722 VMap[&I] = nextID;
4723
David Neto87846742018-04-11 17:36:22 -04004724 auto *Inst = new SPIRVInstruction(spv::OpAny, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004725 SPIRVInstList.push_back(Inst);
4726 break;
4727 }
4728
4729 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
4730 // Additionally, OpTypeSampledImage is generated.
4731 if (Callee->getName().equals(
4732 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
4733 Callee->getName().equals(
4734 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
4735 //
4736 // Generate OpSampledImage.
4737 //
4738 // Ops[0] = Result Type ID
4739 // Ops[1] = Image ID
4740 // Ops[2] = Sampler ID
4741 //
4742 SPIRVOperandList Ops;
4743
4744 Value *Image = Call->getArgOperand(0);
4745 Value *Sampler = Call->getArgOperand(1);
4746 Value *Coordinate = Call->getArgOperand(2);
4747
4748 TypeMapType &OpImageTypeMap = getImageTypeMap();
4749 Type *ImageTy = Image->getType()->getPointerElementType();
4750 uint32_t ImageTyID = OpImageTypeMap[ImageTy];
David Neto22f144c2017-06-12 14:26:21 -04004751 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004752 uint32_t SamplerID = VMap[Sampler];
David Neto257c3892018-04-11 13:19:45 -04004753
4754 Ops << MkId(ImageTyID) << MkId(ImageID) << MkId(SamplerID);
David Neto22f144c2017-06-12 14:26:21 -04004755
4756 uint32_t SampledImageID = nextID;
4757
David Neto87846742018-04-11 17:36:22 -04004758 auto *Inst = new SPIRVInstruction(spv::OpSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004759 SPIRVInstList.push_back(Inst);
4760
4761 //
4762 // Generate OpImageSampleExplicitLod.
4763 //
4764 // Ops[0] = Result Type ID
4765 // Ops[1] = Sampled Image ID
4766 // Ops[2] = Coordinate ID
4767 // Ops[3] = Image Operands Type ID
4768 // Ops[4] ... Ops[n] = Operands ID
4769 //
4770 Ops.clear();
4771
David Neto257c3892018-04-11 13:19:45 -04004772 Ops << MkId(lookupType(Call->getType())) << MkId(SampledImageID)
4773 << MkId(VMap[Coordinate]) << MkNum(spv::ImageOperandsLodMask);
David Neto22f144c2017-06-12 14:26:21 -04004774
4775 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
David Neto257c3892018-04-11 13:19:45 -04004776 Ops << MkId(VMap[CstFP0]);
David Neto22f144c2017-06-12 14:26:21 -04004777
4778 VMap[&I] = nextID;
4779
David Neto87846742018-04-11 17:36:22 -04004780 Inst = new SPIRVInstruction(spv::OpImageSampleExplicitLod, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004781 SPIRVInstList.push_back(Inst);
4782 break;
4783 }
4784
4785 // write_imagef is mapped to OpImageWrite.
4786 if (Callee->getName().equals(
4787 "_Z12write_imagef14ocl_image2d_woDv2_iDv4_f") ||
4788 Callee->getName().equals(
4789 "_Z12write_imagef14ocl_image3d_woDv4_iDv4_f")) {
4790 //
4791 // Generate OpImageWrite.
4792 //
4793 // Ops[0] = Image ID
4794 // Ops[1] = Coordinate ID
4795 // Ops[2] = Texel ID
4796 // Ops[3] = (Optional) Image Operands Type (Literal Number)
4797 // Ops[4] ... Ops[n] = (Optional) Operands ID
4798 //
4799 SPIRVOperandList Ops;
4800
4801 Value *Image = Call->getArgOperand(0);
4802 Value *Coordinate = Call->getArgOperand(1);
4803 Value *Texel = Call->getArgOperand(2);
4804
4805 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004806 uint32_t CoordinateID = VMap[Coordinate];
David Neto22f144c2017-06-12 14:26:21 -04004807 uint32_t TexelID = VMap[Texel];
David Neto257c3892018-04-11 13:19:45 -04004808 Ops << MkId(ImageID) << MkId(CoordinateID) << MkId(TexelID);
David Neto22f144c2017-06-12 14:26:21 -04004809
David Neto87846742018-04-11 17:36:22 -04004810 auto *Inst = new SPIRVInstruction(spv::OpImageWrite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004811 SPIRVInstList.push_back(Inst);
4812 break;
4813 }
4814
David Neto5c22a252018-03-15 16:07:41 -04004815 // get_image_width is mapped to OpImageQuerySize
4816 if (Callee->getName().equals("_Z15get_image_width14ocl_image2d_ro") ||
4817 Callee->getName().equals("_Z15get_image_width14ocl_image2d_wo") ||
4818 Callee->getName().equals("_Z16get_image_height14ocl_image2d_ro") ||
4819 Callee->getName().equals("_Z16get_image_height14ocl_image2d_wo")) {
4820 //
4821 // Generate OpImageQuerySize, then pull out the right component.
4822 // Assume 2D image for now.
4823 //
4824 // Ops[0] = Image ID
4825 //
4826 // %sizes = OpImageQuerySizes %uint2 %im
4827 // %result = OpCompositeExtract %uint %sizes 0-or-1
4828 SPIRVOperandList Ops;
4829
4830 // Implement:
4831 // %sizes = OpImageQuerySizes %uint2 %im
4832 uint32_t SizesTypeID =
4833 TypeMap[VectorType::get(Type::getInt32Ty(Context), 2)];
David Neto5c22a252018-03-15 16:07:41 -04004834 Value *Image = Call->getArgOperand(0);
4835 uint32_t ImageID = VMap[Image];
David Neto257c3892018-04-11 13:19:45 -04004836 Ops << MkId(SizesTypeID) << MkId(ImageID);
David Neto5c22a252018-03-15 16:07:41 -04004837
4838 uint32_t SizesID = nextID++;
David Neto87846742018-04-11 17:36:22 -04004839 auto *QueryInst =
4840 new SPIRVInstruction(spv::OpImageQuerySize, SizesID, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004841 SPIRVInstList.push_back(QueryInst);
4842
4843 // Reset value map entry since we generated an intermediate instruction.
4844 VMap[&I] = nextID;
4845
4846 // Implement:
4847 // %result = OpCompositeExtract %uint %sizes 0-or-1
4848 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004849 Ops << MkId(TypeMap[I.getType()]) << MkId(SizesID);
David Neto5c22a252018-03-15 16:07:41 -04004850
4851 uint32_t component = Callee->getName().contains("height") ? 1 : 0;
David Neto257c3892018-04-11 13:19:45 -04004852 Ops << MkNum(component);
David Neto5c22a252018-03-15 16:07:41 -04004853
David Neto87846742018-04-11 17:36:22 -04004854 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004855 SPIRVInstList.push_back(Inst);
4856 break;
4857 }
4858
David Neto22f144c2017-06-12 14:26:21 -04004859 // Call instrucion is deferred because it needs function's ID. Record
4860 // slot's location on SPIRVInstructionList.
4861 DeferredInsts.push_back(
4862 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4863
David Neto3fbb4072017-10-16 11:28:14 -04004864 // Check whether the implementation of this call uses an extended
4865 // instruction plus one more value-producing instruction. If so, then
4866 // reserve the id for the extra value-producing slot.
4867 glsl::ExtInst EInst = getIndirectExtInstEnum(Callee->getName());
4868 if (EInst != kGlslExtInstBad) {
4869 // Reserve a spot for the extra value.
David Neto4d02a532017-09-17 12:57:44 -04004870 // Increase nextID.
David Neto22f144c2017-06-12 14:26:21 -04004871 VMap[&I] = nextID;
4872 nextID++;
4873 }
4874 break;
4875 }
4876 case Instruction::Ret: {
4877 unsigned NumOps = I.getNumOperands();
4878 if (NumOps == 0) {
4879 //
4880 // Generate OpReturn.
4881 //
David Neto87846742018-04-11 17:36:22 -04004882 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpReturn, {}));
David Neto22f144c2017-06-12 14:26:21 -04004883 } else {
4884 //
4885 // Generate OpReturnValue.
4886 //
4887
4888 // Ops[0] = Return Value ID
4889 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004890
4891 Ops << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004892
David Neto87846742018-04-11 17:36:22 -04004893 auto *Inst = new SPIRVInstruction(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004894 SPIRVInstList.push_back(Inst);
4895 break;
4896 }
4897 break;
4898 }
4899 }
4900}
4901
4902void SPIRVProducerPass::GenerateFuncEpilogue() {
4903 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4904
4905 //
4906 // Generate OpFunctionEnd
4907 //
4908
David Neto87846742018-04-11 17:36:22 -04004909 auto *Inst = new SPIRVInstruction(spv::OpFunctionEnd, {});
David Neto22f144c2017-06-12 14:26:21 -04004910 SPIRVInstList.push_back(Inst);
4911}
4912
4913bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
alan-bakerb39c8262019-03-08 14:03:37 -05004914 // Don't specialize <4 x i8> if i8 is generally supported.
4915 if (clspv::Option::Int8Support())
4916 return false;
4917
David Neto22f144c2017-06-12 14:26:21 -04004918 LLVMContext &Context = Ty->getContext();
4919 if (Ty->isVectorTy()) {
4920 if (Ty->getVectorElementType() == Type::getInt8Ty(Context) &&
4921 Ty->getVectorNumElements() == 4) {
4922 return true;
4923 }
4924 }
4925
4926 return false;
4927}
4928
David Neto257c3892018-04-11 13:19:45 -04004929uint32_t SPIRVProducerPass::GetI32Zero() {
4930 if (0 == constant_i32_zero_id_) {
4931 llvm_unreachable("Requesting a 32-bit integer constant but it is not "
4932 "defined in the SPIR-V module");
4933 }
4934 return constant_i32_zero_id_;
4935}
4936
David Neto22f144c2017-06-12 14:26:21 -04004937void SPIRVProducerPass::HandleDeferredInstruction() {
4938 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4939 ValueMapType &VMap = getValueMap();
4940 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4941
4942 for (auto DeferredInst = DeferredInsts.rbegin();
4943 DeferredInst != DeferredInsts.rend(); ++DeferredInst) {
4944 Value *Inst = std::get<0>(*DeferredInst);
4945 SPIRVInstructionList::iterator InsertPoint = ++std::get<1>(*DeferredInst);
4946 if (InsertPoint != SPIRVInstList.end()) {
4947 while ((*InsertPoint)->getOpcode() == spv::OpPhi) {
4948 ++InsertPoint;
4949 }
4950 }
4951
4952 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
4953 // Check whether basic block, which has this branch instruction, is loop
4954 // header or not. If it is loop header, generate OpLoopMerge and
4955 // OpBranchConditional.
4956 Function *Func = Br->getParent()->getParent();
4957 DominatorTree &DT =
4958 getAnalysis<DominatorTreeWrapperPass>(*Func).getDomTree();
4959 const LoopInfo &LI =
4960 getAnalysis<LoopInfoWrapperPass>(*Func).getLoopInfo();
4961
4962 BasicBlock *BrBB = Br->getParent();
4963 if (LI.isLoopHeader(BrBB)) {
4964 Value *ContinueBB = nullptr;
4965 Value *MergeBB = nullptr;
4966
4967 Loop *L = LI.getLoopFor(BrBB);
4968 MergeBB = L->getExitBlock();
4969 if (!MergeBB) {
4970 // StructurizeCFG pass converts CFG into triangle shape and the cfg
4971 // has regions with single entry/exit. As a result, loop should not
4972 // have multiple exits.
4973 llvm_unreachable("Loop has multiple exits???");
4974 }
4975
4976 if (L->isLoopLatch(BrBB)) {
4977 ContinueBB = BrBB;
4978 } else {
4979 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
4980 // block.
4981 BasicBlock *Header = L->getHeader();
4982 BasicBlock *Latch = L->getLoopLatch();
4983 for (BasicBlock *BB : L->blocks()) {
4984 if (BB == Header) {
4985 continue;
4986 }
4987
4988 // Check whether block dominates block with back-edge.
4989 if (DT.dominates(BB, Latch)) {
4990 ContinueBB = BB;
4991 }
4992 }
4993
4994 if (!ContinueBB) {
4995 llvm_unreachable("Wrong continue block from loop");
4996 }
4997 }
4998
4999 //
5000 // Generate OpLoopMerge.
5001 //
5002 // Ops[0] = Merge Block ID
5003 // Ops[1] = Continue Target ID
5004 // Ops[2] = Selection Control
5005 SPIRVOperandList Ops;
5006
5007 // StructurizeCFG pass already manipulated CFG. Just use false block of
5008 // branch instruction as merge block.
5009 uint32_t MergeBBID = VMap[MergeBB];
David Neto22f144c2017-06-12 14:26:21 -04005010 uint32_t ContinueBBID = VMap[ContinueBB];
David Neto257c3892018-04-11 13:19:45 -04005011 Ops << MkId(MergeBBID) << MkId(ContinueBBID)
5012 << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04005013
David Neto87846742018-04-11 17:36:22 -04005014 auto *MergeInst = new SPIRVInstruction(spv::OpLoopMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005015 SPIRVInstList.insert(InsertPoint, MergeInst);
5016
5017 } else if (Br->isConditional()) {
5018 bool HasBackEdge = false;
5019
5020 for (unsigned i = 0; i < Br->getNumSuccessors(); i++) {
5021 if (LI.isLoopHeader(Br->getSuccessor(i))) {
5022 HasBackEdge = true;
5023 }
5024 }
5025 if (!HasBackEdge) {
5026 //
5027 // Generate OpSelectionMerge.
5028 //
5029 // Ops[0] = Merge Block ID
5030 // Ops[1] = Selection Control
5031 SPIRVOperandList Ops;
5032
5033 // StructurizeCFG pass already manipulated CFG. Just use false block
5034 // of branch instruction as merge block.
5035 uint32_t MergeBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04005036 Ops << MkId(MergeBBID) << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04005037
David Neto87846742018-04-11 17:36:22 -04005038 auto *MergeInst = new SPIRVInstruction(spv::OpSelectionMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005039 SPIRVInstList.insert(InsertPoint, MergeInst);
5040 }
5041 }
5042
5043 if (Br->isConditional()) {
5044 //
5045 // Generate OpBranchConditional.
5046 //
5047 // Ops[0] = Condition ID
5048 // Ops[1] = True Label ID
5049 // Ops[2] = False Label ID
5050 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
5051 SPIRVOperandList Ops;
5052
5053 uint32_t CondID = VMap[Br->getCondition()];
David Neto22f144c2017-06-12 14:26:21 -04005054 uint32_t TrueBBID = VMap[Br->getSuccessor(0)];
David Neto22f144c2017-06-12 14:26:21 -04005055 uint32_t FalseBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04005056
5057 Ops << MkId(CondID) << MkId(TrueBBID) << MkId(FalseBBID);
David Neto22f144c2017-06-12 14:26:21 -04005058
David Neto87846742018-04-11 17:36:22 -04005059 auto *BrInst = new SPIRVInstruction(spv::OpBranchConditional, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005060 SPIRVInstList.insert(InsertPoint, BrInst);
5061 } else {
5062 //
5063 // Generate OpBranch.
5064 //
5065 // Ops[0] = Target Label ID
5066 SPIRVOperandList Ops;
5067
5068 uint32_t TargetID = VMap[Br->getSuccessor(0)];
David Neto257c3892018-04-11 13:19:45 -04005069 Ops << MkId(TargetID);
David Neto22f144c2017-06-12 14:26:21 -04005070
David Neto87846742018-04-11 17:36:22 -04005071 SPIRVInstList.insert(InsertPoint,
5072 new SPIRVInstruction(spv::OpBranch, Ops));
David Neto22f144c2017-06-12 14:26:21 -04005073 }
5074 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
alan-baker5b86ed72019-02-15 08:26:50 -05005075 if (PHI->getType()->isPointerTy()) {
5076 // OpPhi on pointers requires variable pointers.
5077 setVariablePointersCapabilities(
5078 PHI->getType()->getPointerAddressSpace());
5079 if (!hasVariablePointers() && !selectFromSameObject(PHI)) {
5080 setVariablePointers(true);
5081 }
5082 }
5083
David Neto22f144c2017-06-12 14:26:21 -04005084 //
5085 // Generate OpPhi.
5086 //
5087 // Ops[0] = Result Type ID
5088 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
5089 SPIRVOperandList Ops;
5090
David Neto257c3892018-04-11 13:19:45 -04005091 Ops << MkId(lookupType(PHI->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005092
David Neto22f144c2017-06-12 14:26:21 -04005093 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
5094 uint32_t VarID = VMap[PHI->getIncomingValue(i)];
David Neto22f144c2017-06-12 14:26:21 -04005095 uint32_t ParentID = VMap[PHI->getIncomingBlock(i)];
David Neto257c3892018-04-11 13:19:45 -04005096 Ops << MkId(VarID) << MkId(ParentID);
David Neto22f144c2017-06-12 14:26:21 -04005097 }
5098
5099 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005100 InsertPoint,
5101 new SPIRVInstruction(spv::OpPhi, std::get<2>(*DeferredInst), Ops));
David Neto22f144c2017-06-12 14:26:21 -04005102 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
5103 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04005104 auto callee_name = Callee->getName();
5105 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04005106
5107 if (EInst) {
5108 uint32_t &ExtInstImportID = getOpExtInstImportID();
5109
5110 //
5111 // Generate OpExtInst.
5112 //
5113
5114 // Ops[0] = Result Type ID
5115 // Ops[1] = Set ID (OpExtInstImport ID)
5116 // Ops[2] = Instruction Number (Literal Number)
5117 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5118 SPIRVOperandList Ops;
5119
David Neto862b7d82018-06-14 18:48:37 -04005120 Ops << MkId(lookupType(Call->getType())) << MkId(ExtInstImportID)
5121 << MkNum(EInst);
David Neto22f144c2017-06-12 14:26:21 -04005122
David Neto22f144c2017-06-12 14:26:21 -04005123 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5124 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04005125 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04005126 }
5127
David Neto87846742018-04-11 17:36:22 -04005128 auto *ExtInst = new SPIRVInstruction(spv::OpExtInst,
5129 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005130 SPIRVInstList.insert(InsertPoint, ExtInst);
5131
David Neto3fbb4072017-10-16 11:28:14 -04005132 const auto IndirectExtInst = getIndirectExtInstEnum(callee_name);
5133 if (IndirectExtInst != kGlslExtInstBad) {
5134 // Generate one more instruction that uses the result of the extended
5135 // instruction. Its result id is one more than the id of the
5136 // extended instruction.
David Neto22f144c2017-06-12 14:26:21 -04005137 LLVMContext &Context =
5138 Call->getParent()->getParent()->getParent()->getContext();
David Neto22f144c2017-06-12 14:26:21 -04005139
David Neto3fbb4072017-10-16 11:28:14 -04005140 auto generate_extra_inst = [this, &Context, &Call, &DeferredInst,
5141 &VMap, &SPIRVInstList, &InsertPoint](
5142 spv::Op opcode, Constant *constant) {
5143 //
5144 // Generate instruction like:
5145 // result = opcode constant <extinst-result>
5146 //
5147 // Ops[0] = Result Type ID
5148 // Ops[1] = Operand 0 ;; the constant, suitably splatted
5149 // Ops[2] = Operand 1 ;; the result of the extended instruction
5150 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04005151
David Neto3fbb4072017-10-16 11:28:14 -04005152 Type *resultTy = Call->getType();
David Neto257c3892018-04-11 13:19:45 -04005153 Ops << MkId(lookupType(resultTy));
David Neto3fbb4072017-10-16 11:28:14 -04005154
5155 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
5156 constant = ConstantVector::getSplat(
5157 static_cast<unsigned>(vectorTy->getNumElements()), constant);
5158 }
David Neto257c3892018-04-11 13:19:45 -04005159 Ops << MkId(VMap[constant]) << MkId(std::get<2>(*DeferredInst));
David Neto3fbb4072017-10-16 11:28:14 -04005160
5161 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005162 InsertPoint, new SPIRVInstruction(
5163 opcode, std::get<2>(*DeferredInst) + 1, Ops));
David Neto3fbb4072017-10-16 11:28:14 -04005164 };
5165
5166 switch (IndirectExtInst) {
5167 case glsl::ExtInstFindUMsb: // Implementing clz
5168 generate_extra_inst(
5169 spv::OpISub, ConstantInt::get(Type::getInt32Ty(Context), 31));
5170 break;
5171 case glsl::ExtInstAcos: // Implementing acospi
5172 case glsl::ExtInstAsin: // Implementing asinpi
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005173 case glsl::ExtInstAtan: // Implementing atanpi
David Neto3fbb4072017-10-16 11:28:14 -04005174 case glsl::ExtInstAtan2: // Implementing atan2pi
5175 generate_extra_inst(
5176 spv::OpFMul,
5177 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
5178 break;
5179
5180 default:
5181 assert(false && "internally inconsistent");
David Neto4d02a532017-09-17 12:57:44 -04005182 }
David Neto22f144c2017-06-12 14:26:21 -04005183 }
David Neto3fbb4072017-10-16 11:28:14 -04005184
alan-bakerb39c8262019-03-08 14:03:37 -05005185 } else if (callee_name.startswith("_Z8popcount")) {
David Neto22f144c2017-06-12 14:26:21 -04005186 //
5187 // Generate OpBitCount
5188 //
5189 // Ops[0] = Result Type ID
5190 // Ops[1] = Base ID
David Neto257c3892018-04-11 13:19:45 -04005191 SPIRVOperandList Ops;
5192 Ops << MkId(lookupType(Call->getType()))
5193 << MkId(VMap[Call->getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04005194
5195 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005196 InsertPoint, new SPIRVInstruction(spv::OpBitCount,
David Neto22f144c2017-06-12 14:26:21 -04005197 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005198
David Neto862b7d82018-06-14 18:48:37 -04005199 } else if (callee_name.startswith(kCompositeConstructFunctionPrefix)) {
David Netoab03f432017-11-03 17:00:44 -04005200
5201 // Generate an OpCompositeConstruct
5202 SPIRVOperandList Ops;
5203
5204 // The result type.
David Neto257c3892018-04-11 13:19:45 -04005205 Ops << MkId(lookupType(Call->getType()));
David Netoab03f432017-11-03 17:00:44 -04005206
5207 for (Use &use : Call->arg_operands()) {
David Neto257c3892018-04-11 13:19:45 -04005208 Ops << MkId(VMap[use.get()]);
David Netoab03f432017-11-03 17:00:44 -04005209 }
5210
5211 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005212 InsertPoint, new SPIRVInstruction(spv::OpCompositeConstruct,
5213 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005214
Alan Baker202c8c72018-08-13 13:47:44 -04005215 } else if (callee_name.startswith(clspv::ResourceAccessorFunction())) {
5216
5217 // We have already mapped the call's result value to an ID.
5218 // Don't generate any code now.
5219
5220 } else if (callee_name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04005221
5222 // We have already mapped the call's result value to an ID.
5223 // Don't generate any code now.
5224
David Neto22f144c2017-06-12 14:26:21 -04005225 } else {
alan-baker5b86ed72019-02-15 08:26:50 -05005226 if (Call->getType()->isPointerTy()) {
5227 // Functions returning pointers require variable pointers.
5228 setVariablePointersCapabilities(
5229 Call->getType()->getPointerAddressSpace());
5230 }
5231
David Neto22f144c2017-06-12 14:26:21 -04005232 //
5233 // Generate OpFunctionCall.
5234 //
5235
5236 // Ops[0] = Result Type ID
5237 // Ops[1] = Callee Function ID
5238 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
5239 SPIRVOperandList Ops;
5240
David Neto862b7d82018-06-14 18:48:37 -04005241 Ops << MkId(lookupType(Call->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005242
5243 uint32_t CalleeID = VMap[Callee];
David Neto43568eb2017-10-13 18:25:25 -04005244 if (CalleeID == 0) {
5245 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04005246 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04005247 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
5248 // causes an infinite loop. Instead, go ahead and generate
5249 // the bad function call. A validator will catch the 0-Id.
5250 // llvm_unreachable("Can't translate function call");
5251 }
David Neto22f144c2017-06-12 14:26:21 -04005252
David Neto257c3892018-04-11 13:19:45 -04005253 Ops << MkId(CalleeID);
David Neto22f144c2017-06-12 14:26:21 -04005254
David Neto22f144c2017-06-12 14:26:21 -04005255 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5256 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
alan-baker5b86ed72019-02-15 08:26:50 -05005257 auto *operand = Call->getOperand(i);
5258 if (operand->getType()->isPointerTy()) {
5259 auto sc =
5260 GetStorageClass(operand->getType()->getPointerAddressSpace());
5261 if (sc == spv::StorageClassStorageBuffer) {
5262 // Passing SSBO by reference requires variable pointers storage
5263 // buffer.
5264 setVariablePointersStorageBuffer(true);
5265 } else if (sc == spv::StorageClassWorkgroup) {
5266 // Workgroup references require variable pointers if they are not
5267 // memory object declarations.
5268 if (auto *operand_call = dyn_cast<CallInst>(operand)) {
5269 // Workgroup accessor represents a variable reference.
5270 if (!operand_call->getCalledFunction()->getName().startswith(
5271 clspv::WorkgroupAccessorFunction()))
5272 setVariablePointers(true);
5273 } else {
5274 // Arguments are function parameters.
5275 if (!isa<Argument>(operand))
5276 setVariablePointers(true);
5277 }
5278 }
5279 }
5280 Ops << MkId(VMap[operand]);
David Neto22f144c2017-06-12 14:26:21 -04005281 }
5282
David Neto87846742018-04-11 17:36:22 -04005283 auto *CallInst = new SPIRVInstruction(spv::OpFunctionCall,
5284 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005285 SPIRVInstList.insert(InsertPoint, CallInst);
5286 }
5287 }
5288 }
5289}
5290
David Neto1a1a0582017-07-07 12:01:44 -04005291void SPIRVProducerPass::HandleDeferredDecorations(const DataLayout &DL) {
Alan Baker202c8c72018-08-13 13:47:44 -04005292 if (getTypesNeedingArrayStride().empty() && LocalArgSpecIds.empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04005293 return;
David Netoc6f3ab22018-04-06 18:02:31 -04005294 }
David Neto1a1a0582017-07-07 12:01:44 -04005295
5296 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto1a1a0582017-07-07 12:01:44 -04005297
5298 // Find an iterator pointing just past the last decoration.
5299 bool seen_decorations = false;
5300 auto DecoInsertPoint =
5301 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
5302 [&seen_decorations](SPIRVInstruction *Inst) -> bool {
5303 const bool is_decoration =
5304 Inst->getOpcode() == spv::OpDecorate ||
5305 Inst->getOpcode() == spv::OpMemberDecorate;
5306 if (is_decoration) {
5307 seen_decorations = true;
5308 return false;
5309 } else {
5310 return seen_decorations;
5311 }
5312 });
5313
David Netoc6f3ab22018-04-06 18:02:31 -04005314 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
5315 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07005316 for (auto *type : getTypesNeedingArrayStride()) {
5317 Type *elemTy = nullptr;
5318 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
5319 elemTy = ptrTy->getElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005320 } else if (auto *arrayTy = dyn_cast<ArrayType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005321 elemTy = arrayTy->getArrayElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005322 } else if (auto *seqTy = dyn_cast<SequentialType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005323 elemTy = seqTy->getSequentialElementType();
5324 } else {
5325 errs() << "Unhandled strided type " << *type << "\n";
5326 llvm_unreachable("Unhandled strided type");
5327 }
David Neto1a1a0582017-07-07 12:01:44 -04005328
5329 // Ops[0] = Target ID
5330 // Ops[1] = Decoration (ArrayStride)
5331 // Ops[2] = Stride number (Literal Number)
5332 SPIRVOperandList Ops;
5333
David Neto85082642018-03-24 06:55:20 -07005334 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Alan Bakerfcda9482018-10-02 17:09:59 -04005335 const uint32_t stride = static_cast<uint32_t>(GetTypeAllocSize(elemTy, DL));
David Neto257c3892018-04-11 13:19:45 -04005336
5337 Ops << MkId(lookupType(type)) << MkNum(spv::DecorationArrayStride)
5338 << MkNum(stride);
David Neto1a1a0582017-07-07 12:01:44 -04005339
David Neto87846742018-04-11 17:36:22 -04005340 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto1a1a0582017-07-07 12:01:44 -04005341 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
5342 }
David Netoc6f3ab22018-04-06 18:02:31 -04005343
5344 // Emit SpecId decorations targeting the array size value.
Alan Baker202c8c72018-08-13 13:47:44 -04005345 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
5346 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005347 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04005348 SPIRVOperandList Ops;
5349 Ops << MkId(arg_info.array_size_id) << MkNum(spv::DecorationSpecId)
5350 << MkNum(arg_info.spec_id);
5351 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04005352 new SPIRVInstruction(spv::OpDecorate, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04005353 }
David Neto1a1a0582017-07-07 12:01:44 -04005354}
5355
David Neto22f144c2017-06-12 14:26:21 -04005356glsl::ExtInst SPIRVProducerPass::getExtInstEnum(StringRef Name) {
5357 return StringSwitch<glsl::ExtInst>(Name)
alan-bakerb39c8262019-03-08 14:03:37 -05005358 .Case("_Z3absc", glsl::ExtInst::ExtInstSAbs)
5359 .Case("_Z3absDv2_c", glsl::ExtInst::ExtInstSAbs)
5360 .Case("_Z3absDv3_c", glsl::ExtInst::ExtInstSAbs)
5361 .Case("_Z3absDv4_c", glsl::ExtInst::ExtInstSAbs)
Kévin Petit2444e9b2018-11-09 14:14:37 +00005362 .Case("_Z3abss", glsl::ExtInst::ExtInstSAbs)
5363 .Case("_Z3absDv2_s", glsl::ExtInst::ExtInstSAbs)
5364 .Case("_Z3absDv3_s", glsl::ExtInst::ExtInstSAbs)
5365 .Case("_Z3absDv4_s", glsl::ExtInst::ExtInstSAbs)
David Neto22f144c2017-06-12 14:26:21 -04005366 .Case("_Z3absi", glsl::ExtInst::ExtInstSAbs)
5367 .Case("_Z3absDv2_i", glsl::ExtInst::ExtInstSAbs)
5368 .Case("_Z3absDv3_i", glsl::ExtInst::ExtInstSAbs)
5369 .Case("_Z3absDv4_i", glsl::ExtInst::ExtInstSAbs)
Kévin Petit2444e9b2018-11-09 14:14:37 +00005370 .Case("_Z3absl", glsl::ExtInst::ExtInstSAbs)
5371 .Case("_Z3absDv2_l", glsl::ExtInst::ExtInstSAbs)
5372 .Case("_Z3absDv3_l", glsl::ExtInst::ExtInstSAbs)
5373 .Case("_Z3absDv4_l", glsl::ExtInst::ExtInstSAbs)
alan-bakerb39c8262019-03-08 14:03:37 -05005374 .Case("_Z5clampccc", glsl::ExtInst::ExtInstSClamp)
5375 .Case("_Z5clampDv2_cS_S_", glsl::ExtInst::ExtInstSClamp)
5376 .Case("_Z5clampDv3_cS_S_", glsl::ExtInst::ExtInstSClamp)
5377 .Case("_Z5clampDv4_cS_S_", glsl::ExtInst::ExtInstSClamp)
5378 .Case("_Z5clamphhh", glsl::ExtInst::ExtInstUClamp)
5379 .Case("_Z5clampDv2_hS_S_", glsl::ExtInst::ExtInstUClamp)
5380 .Case("_Z5clampDv3_hS_S_", glsl::ExtInst::ExtInstUClamp)
5381 .Case("_Z5clampDv4_hS_S_", glsl::ExtInst::ExtInstUClamp)
Kévin Petit495255d2019-03-06 13:56:48 +00005382 .Case("_Z5clampsss", glsl::ExtInst::ExtInstSClamp)
5383 .Case("_Z5clampDv2_sS_S_", glsl::ExtInst::ExtInstSClamp)
5384 .Case("_Z5clampDv3_sS_S_", glsl::ExtInst::ExtInstSClamp)
5385 .Case("_Z5clampDv4_sS_S_", glsl::ExtInst::ExtInstSClamp)
5386 .Case("_Z5clampttt", glsl::ExtInst::ExtInstUClamp)
5387 .Case("_Z5clampDv2_tS_S_", glsl::ExtInst::ExtInstUClamp)
5388 .Case("_Z5clampDv3_tS_S_", glsl::ExtInst::ExtInstUClamp)
5389 .Case("_Z5clampDv4_tS_S_", glsl::ExtInst::ExtInstUClamp)
David Neto22f144c2017-06-12 14:26:21 -04005390 .Case("_Z5clampiii", glsl::ExtInst::ExtInstSClamp)
5391 .Case("_Z5clampDv2_iS_S_", glsl::ExtInst::ExtInstSClamp)
5392 .Case("_Z5clampDv3_iS_S_", glsl::ExtInst::ExtInstSClamp)
5393 .Case("_Z5clampDv4_iS_S_", glsl::ExtInst::ExtInstSClamp)
5394 .Case("_Z5clampjjj", glsl::ExtInst::ExtInstUClamp)
5395 .Case("_Z5clampDv2_jS_S_", glsl::ExtInst::ExtInstUClamp)
5396 .Case("_Z5clampDv3_jS_S_", glsl::ExtInst::ExtInstUClamp)
5397 .Case("_Z5clampDv4_jS_S_", glsl::ExtInst::ExtInstUClamp)
Kévin Petit495255d2019-03-06 13:56:48 +00005398 .Case("_Z5clamplll", glsl::ExtInst::ExtInstSClamp)
5399 .Case("_Z5clampDv2_lS_S_", glsl::ExtInst::ExtInstSClamp)
5400 .Case("_Z5clampDv3_lS_S_", glsl::ExtInst::ExtInstSClamp)
5401 .Case("_Z5clampDv4_lS_S_", glsl::ExtInst::ExtInstSClamp)
5402 .Case("_Z5clampmmm", glsl::ExtInst::ExtInstUClamp)
5403 .Case("_Z5clampDv2_mS_S_", glsl::ExtInst::ExtInstUClamp)
5404 .Case("_Z5clampDv3_mS_S_", glsl::ExtInst::ExtInstUClamp)
5405 .Case("_Z5clampDv4_mS_S_", glsl::ExtInst::ExtInstUClamp)
David Neto22f144c2017-06-12 14:26:21 -04005406 .Case("_Z5clampfff", glsl::ExtInst::ExtInstFClamp)
5407 .Case("_Z5clampDv2_fS_S_", glsl::ExtInst::ExtInstFClamp)
5408 .Case("_Z5clampDv3_fS_S_", glsl::ExtInst::ExtInstFClamp)
5409 .Case("_Z5clampDv4_fS_S_", glsl::ExtInst::ExtInstFClamp)
alan-bakerb39c8262019-03-08 14:03:37 -05005410 .Case("_Z3maxcc", glsl::ExtInst::ExtInstSMax)
5411 .Case("_Z3maxDv2_cS_", glsl::ExtInst::ExtInstSMax)
5412 .Case("_Z3maxDv3_cS_", glsl::ExtInst::ExtInstSMax)
5413 .Case("_Z3maxDv4_cS_", glsl::ExtInst::ExtInstSMax)
5414 .Case("_Z3maxhh", glsl::ExtInst::ExtInstUMax)
5415 .Case("_Z3maxDv2_hS_", glsl::ExtInst::ExtInstUMax)
5416 .Case("_Z3maxDv3_hS_", glsl::ExtInst::ExtInstUMax)
5417 .Case("_Z3maxDv4_hS_", glsl::ExtInst::ExtInstUMax)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005418 .Case("_Z3maxss", glsl::ExtInst::ExtInstSMax)
5419 .Case("_Z3maxDv2_sS_", glsl::ExtInst::ExtInstSMax)
5420 .Case("_Z3maxDv3_sS_", glsl::ExtInst::ExtInstSMax)
5421 .Case("_Z3maxDv4_sS_", glsl::ExtInst::ExtInstSMax)
5422 .Case("_Z3maxtt", glsl::ExtInst::ExtInstUMax)
5423 .Case("_Z3maxDv2_tS_", glsl::ExtInst::ExtInstUMax)
5424 .Case("_Z3maxDv3_tS_", glsl::ExtInst::ExtInstUMax)
5425 .Case("_Z3maxDv4_tS_", glsl::ExtInst::ExtInstUMax)
David Neto22f144c2017-06-12 14:26:21 -04005426 .Case("_Z3maxii", glsl::ExtInst::ExtInstSMax)
5427 .Case("_Z3maxDv2_iS_", glsl::ExtInst::ExtInstSMax)
5428 .Case("_Z3maxDv3_iS_", glsl::ExtInst::ExtInstSMax)
5429 .Case("_Z3maxDv4_iS_", glsl::ExtInst::ExtInstSMax)
5430 .Case("_Z3maxjj", glsl::ExtInst::ExtInstUMax)
5431 .Case("_Z3maxDv2_jS_", glsl::ExtInst::ExtInstUMax)
5432 .Case("_Z3maxDv3_jS_", glsl::ExtInst::ExtInstUMax)
5433 .Case("_Z3maxDv4_jS_", glsl::ExtInst::ExtInstUMax)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005434 .Case("_Z3maxll", glsl::ExtInst::ExtInstSMax)
5435 .Case("_Z3maxDv2_lS_", glsl::ExtInst::ExtInstSMax)
5436 .Case("_Z3maxDv3_lS_", glsl::ExtInst::ExtInstSMax)
5437 .Case("_Z3maxDv4_lS_", glsl::ExtInst::ExtInstSMax)
5438 .Case("_Z3maxmm", glsl::ExtInst::ExtInstUMax)
5439 .Case("_Z3maxDv2_mS_", glsl::ExtInst::ExtInstUMax)
5440 .Case("_Z3maxDv3_mS_", glsl::ExtInst::ExtInstUMax)
5441 .Case("_Z3maxDv4_mS_", glsl::ExtInst::ExtInstUMax)
David Neto22f144c2017-06-12 14:26:21 -04005442 .Case("_Z3maxff", glsl::ExtInst::ExtInstFMax)
5443 .Case("_Z3maxDv2_fS_", glsl::ExtInst::ExtInstFMax)
5444 .Case("_Z3maxDv3_fS_", glsl::ExtInst::ExtInstFMax)
5445 .Case("_Z3maxDv4_fS_", glsl::ExtInst::ExtInstFMax)
5446 .StartsWith("_Z4fmax", glsl::ExtInst::ExtInstFMax)
alan-bakerb39c8262019-03-08 14:03:37 -05005447 .Case("_Z3mincc", glsl::ExtInst::ExtInstSMin)
5448 .Case("_Z3minDv2_cS_", glsl::ExtInst::ExtInstSMin)
5449 .Case("_Z3minDv3_cS_", glsl::ExtInst::ExtInstSMin)
5450 .Case("_Z3minDv4_cS_", glsl::ExtInst::ExtInstSMin)
5451 .Case("_Z3minhh", glsl::ExtInst::ExtInstUMin)
5452 .Case("_Z3minDv2_hS_", glsl::ExtInst::ExtInstUMin)
5453 .Case("_Z3minDv3_hS_", glsl::ExtInst::ExtInstUMin)
5454 .Case("_Z3minDv4_hS_", glsl::ExtInst::ExtInstUMin)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005455 .Case("_Z3minss", glsl::ExtInst::ExtInstSMin)
5456 .Case("_Z3minDv2_sS_", glsl::ExtInst::ExtInstSMin)
5457 .Case("_Z3minDv3_sS_", glsl::ExtInst::ExtInstSMin)
5458 .Case("_Z3minDv4_sS_", glsl::ExtInst::ExtInstSMin)
5459 .Case("_Z3mintt", glsl::ExtInst::ExtInstUMin)
5460 .Case("_Z3minDv2_tS_", glsl::ExtInst::ExtInstUMin)
5461 .Case("_Z3minDv3_tS_", glsl::ExtInst::ExtInstUMin)
5462 .Case("_Z3minDv4_tS_", glsl::ExtInst::ExtInstUMin)
David Neto22f144c2017-06-12 14:26:21 -04005463 .Case("_Z3minii", glsl::ExtInst::ExtInstSMin)
5464 .Case("_Z3minDv2_iS_", glsl::ExtInst::ExtInstSMin)
5465 .Case("_Z3minDv3_iS_", glsl::ExtInst::ExtInstSMin)
5466 .Case("_Z3minDv4_iS_", glsl::ExtInst::ExtInstSMin)
5467 .Case("_Z3minjj", glsl::ExtInst::ExtInstUMin)
5468 .Case("_Z3minDv2_jS_", glsl::ExtInst::ExtInstUMin)
5469 .Case("_Z3minDv3_jS_", glsl::ExtInst::ExtInstUMin)
5470 .Case("_Z3minDv4_jS_", glsl::ExtInst::ExtInstUMin)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005471 .Case("_Z3minll", glsl::ExtInst::ExtInstSMin)
5472 .Case("_Z3minDv2_lS_", glsl::ExtInst::ExtInstSMin)
5473 .Case("_Z3minDv3_lS_", glsl::ExtInst::ExtInstSMin)
5474 .Case("_Z3minDv4_lS_", glsl::ExtInst::ExtInstSMin)
5475 .Case("_Z3minmm", glsl::ExtInst::ExtInstUMin)
5476 .Case("_Z3minDv2_mS_", glsl::ExtInst::ExtInstUMin)
5477 .Case("_Z3minDv3_mS_", glsl::ExtInst::ExtInstUMin)
5478 .Case("_Z3minDv4_mS_", glsl::ExtInst::ExtInstUMin)
David Neto22f144c2017-06-12 14:26:21 -04005479 .Case("_Z3minff", glsl::ExtInst::ExtInstFMin)
5480 .Case("_Z3minDv2_fS_", glsl::ExtInst::ExtInstFMin)
5481 .Case("_Z3minDv3_fS_", glsl::ExtInst::ExtInstFMin)
5482 .Case("_Z3minDv4_fS_", glsl::ExtInst::ExtInstFMin)
5483 .StartsWith("_Z4fmin", glsl::ExtInst::ExtInstFMin)
5484 .StartsWith("_Z7degrees", glsl::ExtInst::ExtInstDegrees)
5485 .StartsWith("_Z7radians", glsl::ExtInst::ExtInstRadians)
5486 .StartsWith("_Z3mix", glsl::ExtInst::ExtInstFMix)
5487 .StartsWith("_Z4acos", glsl::ExtInst::ExtInstAcos)
5488 .StartsWith("_Z5acosh", glsl::ExtInst::ExtInstAcosh)
5489 .StartsWith("_Z4asin", glsl::ExtInst::ExtInstAsin)
5490 .StartsWith("_Z5asinh", glsl::ExtInst::ExtInstAsinh)
5491 .StartsWith("_Z4atan", glsl::ExtInst::ExtInstAtan)
5492 .StartsWith("_Z5atan2", glsl::ExtInst::ExtInstAtan2)
5493 .StartsWith("_Z5atanh", glsl::ExtInst::ExtInstAtanh)
5494 .StartsWith("_Z4ceil", glsl::ExtInst::ExtInstCeil)
5495 .StartsWith("_Z3sin", glsl::ExtInst::ExtInstSin)
5496 .StartsWith("_Z4sinh", glsl::ExtInst::ExtInstSinh)
5497 .StartsWith("_Z8half_sin", glsl::ExtInst::ExtInstSin)
5498 .StartsWith("_Z10native_sin", glsl::ExtInst::ExtInstSin)
5499 .StartsWith("_Z3cos", glsl::ExtInst::ExtInstCos)
5500 .StartsWith("_Z4cosh", glsl::ExtInst::ExtInstCosh)
5501 .StartsWith("_Z8half_cos", glsl::ExtInst::ExtInstCos)
5502 .StartsWith("_Z10native_cos", glsl::ExtInst::ExtInstCos)
5503 .StartsWith("_Z3tan", glsl::ExtInst::ExtInstTan)
5504 .StartsWith("_Z4tanh", glsl::ExtInst::ExtInstTanh)
5505 .StartsWith("_Z8half_tan", glsl::ExtInst::ExtInstTan)
5506 .StartsWith("_Z10native_tan", glsl::ExtInst::ExtInstTan)
5507 .StartsWith("_Z3exp", glsl::ExtInst::ExtInstExp)
5508 .StartsWith("_Z8half_exp", glsl::ExtInst::ExtInstExp)
5509 .StartsWith("_Z10native_exp", glsl::ExtInst::ExtInstExp)
5510 .StartsWith("_Z4exp2", glsl::ExtInst::ExtInstExp2)
5511 .StartsWith("_Z9half_exp2", glsl::ExtInst::ExtInstExp2)
5512 .StartsWith("_Z11native_exp2", glsl::ExtInst::ExtInstExp2)
5513 .StartsWith("_Z3log", glsl::ExtInst::ExtInstLog)
5514 .StartsWith("_Z8half_log", glsl::ExtInst::ExtInstLog)
5515 .StartsWith("_Z10native_log", glsl::ExtInst::ExtInstLog)
5516 .StartsWith("_Z4log2", glsl::ExtInst::ExtInstLog2)
5517 .StartsWith("_Z9half_log2", glsl::ExtInst::ExtInstLog2)
5518 .StartsWith("_Z11native_log2", glsl::ExtInst::ExtInstLog2)
5519 .StartsWith("_Z4fabs", glsl::ExtInst::ExtInstFAbs)
kpet3458e942018-10-03 14:35:21 +01005520 .StartsWith("_Z3fma", glsl::ExtInst::ExtInstFma)
David Neto22f144c2017-06-12 14:26:21 -04005521 .StartsWith("_Z5floor", glsl::ExtInst::ExtInstFloor)
5522 .StartsWith("_Z5ldexp", glsl::ExtInst::ExtInstLdexp)
5523 .StartsWith("_Z3pow", glsl::ExtInst::ExtInstPow)
5524 .StartsWith("_Z4powr", glsl::ExtInst::ExtInstPow)
5525 .StartsWith("_Z9half_powr", glsl::ExtInst::ExtInstPow)
5526 .StartsWith("_Z11native_powr", glsl::ExtInst::ExtInstPow)
5527 .StartsWith("_Z5round", glsl::ExtInst::ExtInstRound)
5528 .StartsWith("_Z4sqrt", glsl::ExtInst::ExtInstSqrt)
5529 .StartsWith("_Z9half_sqrt", glsl::ExtInst::ExtInstSqrt)
5530 .StartsWith("_Z11native_sqrt", glsl::ExtInst::ExtInstSqrt)
5531 .StartsWith("_Z5rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5532 .StartsWith("_Z10half_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5533 .StartsWith("_Z12native_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5534 .StartsWith("_Z5trunc", glsl::ExtInst::ExtInstTrunc)
5535 .StartsWith("_Z5frexp", glsl::ExtInst::ExtInstFrexp)
5536 .StartsWith("_Z4sign", glsl::ExtInst::ExtInstFSign)
5537 .StartsWith("_Z6length", glsl::ExtInst::ExtInstLength)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005538 .StartsWith("_Z11fast_length", glsl::ExtInst::ExtInstLength)
David Neto22f144c2017-06-12 14:26:21 -04005539 .StartsWith("_Z8distance", glsl::ExtInst::ExtInstDistance)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005540 .StartsWith("_Z13fast_distance", glsl::ExtInst::ExtInstDistance)
David Netoe9a03512017-10-16 10:08:27 -04005541 .StartsWith("_Z4step", glsl::ExtInst::ExtInstStep)
kpet6fd2a262018-10-03 14:48:01 +01005542 .StartsWith("_Z10smoothstep", glsl::ExtInst::ExtInstSmoothStep)
David Neto22f144c2017-06-12 14:26:21 -04005543 .Case("_Z5crossDv3_fS_", glsl::ExtInst::ExtInstCross)
5544 .StartsWith("_Z9normalize", glsl::ExtInst::ExtInstNormalize)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005545 .StartsWith("_Z14fast_normalize", glsl::ExtInst::ExtInstNormalize)
David Neto22f144c2017-06-12 14:26:21 -04005546 .StartsWith("llvm.fmuladd.", glsl::ExtInst::ExtInstFma)
5547 .Case("spirv.unpack.v2f16", glsl::ExtInst::ExtInstUnpackHalf2x16)
5548 .Case("spirv.pack.v2f16", glsl::ExtInst::ExtInstPackHalf2x16)
David Neto62653202017-10-16 19:05:18 -04005549 .Case("clspv.fract.f", glsl::ExtInst::ExtInstFract)
5550 .Case("clspv.fract.v2f", glsl::ExtInst::ExtInstFract)
5551 .Case("clspv.fract.v3f", glsl::ExtInst::ExtInstFract)
5552 .Case("clspv.fract.v4f", glsl::ExtInst::ExtInstFract)
David Neto3fbb4072017-10-16 11:28:14 -04005553 .Default(kGlslExtInstBad);
5554}
5555
5556glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(StringRef Name) {
5557 // Check indirect cases.
5558 return StringSwitch<glsl::ExtInst>(Name)
5559 .StartsWith("_Z3clz", glsl::ExtInst::ExtInstFindUMsb)
5560 // Use exact match on float arg because these need a multiply
5561 // of a constant of the right floating point type.
5562 .Case("_Z6acospif", glsl::ExtInst::ExtInstAcos)
5563 .Case("_Z6acospiDv2_f", glsl::ExtInst::ExtInstAcos)
5564 .Case("_Z6acospiDv3_f", glsl::ExtInst::ExtInstAcos)
5565 .Case("_Z6acospiDv4_f", glsl::ExtInst::ExtInstAcos)
5566 .Case("_Z6asinpif", glsl::ExtInst::ExtInstAsin)
5567 .Case("_Z6asinpiDv2_f", glsl::ExtInst::ExtInstAsin)
5568 .Case("_Z6asinpiDv3_f", glsl::ExtInst::ExtInstAsin)
5569 .Case("_Z6asinpiDv4_f", glsl::ExtInst::ExtInstAsin)
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005570 .Case("_Z6atanpif", glsl::ExtInst::ExtInstAtan)
5571 .Case("_Z6atanpiDv2_f", glsl::ExtInst::ExtInstAtan)
5572 .Case("_Z6atanpiDv3_f", glsl::ExtInst::ExtInstAtan)
5573 .Case("_Z6atanpiDv4_f", glsl::ExtInst::ExtInstAtan)
David Neto3fbb4072017-10-16 11:28:14 -04005574 .Case("_Z7atan2piff", glsl::ExtInst::ExtInstAtan2)
5575 .Case("_Z7atan2piDv2_fS_", glsl::ExtInst::ExtInstAtan2)
5576 .Case("_Z7atan2piDv3_fS_", glsl::ExtInst::ExtInstAtan2)
5577 .Case("_Z7atan2piDv4_fS_", glsl::ExtInst::ExtInstAtan2)
5578 .Default(kGlslExtInstBad);
5579}
5580
alan-bakerb6b09dc2018-11-08 16:59:28 -05005581glsl::ExtInst
5582SPIRVProducerPass::getDirectOrIndirectExtInstEnum(StringRef Name) {
David Neto3fbb4072017-10-16 11:28:14 -04005583 auto direct = getExtInstEnum(Name);
5584 if (direct != kGlslExtInstBad)
5585 return direct;
5586 return getIndirectExtInstEnum(Name);
David Neto22f144c2017-06-12 14:26:21 -04005587}
5588
5589void SPIRVProducerPass::PrintResID(SPIRVInstruction *Inst) {
5590 out << "%" << Inst->getResultID();
5591}
5592
5593void SPIRVProducerPass::PrintOpcode(SPIRVInstruction *Inst) {
5594 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5595 out << "\t" << spv::getOpName(Opcode);
5596}
5597
5598void SPIRVProducerPass::PrintOperand(SPIRVOperand *Op) {
5599 SPIRVOperandType OpTy = Op->getType();
5600 switch (OpTy) {
5601 default: {
5602 llvm_unreachable("Unsupported SPIRV Operand Type???");
5603 break;
5604 }
5605 case SPIRVOperandType::NUMBERID: {
5606 out << "%" << Op->getNumID();
5607 break;
5608 }
5609 case SPIRVOperandType::LITERAL_STRING: {
5610 out << "\"" << Op->getLiteralStr() << "\"";
5611 break;
5612 }
5613 case SPIRVOperandType::LITERAL_INTEGER: {
5614 // TODO: Handle LiteralNum carefully.
Kévin Petite7d0cce2018-10-31 12:38:56 +00005615 auto Words = Op->getLiteralNum();
5616 auto NumWords = Words.size();
5617
5618 if (NumWords == 1) {
5619 out << Words[0];
5620 } else if (NumWords == 2) {
5621 uint64_t Val = (static_cast<uint64_t>(Words[1]) << 32) | Words[0];
5622 out << Val;
5623 } else {
5624 llvm_unreachable("Handle printing arbitrary precision integer literals.");
David Neto22f144c2017-06-12 14:26:21 -04005625 }
5626 break;
5627 }
5628 case SPIRVOperandType::LITERAL_FLOAT: {
5629 // TODO: Handle LiteralNum carefully.
5630 for (auto Word : Op->getLiteralNum()) {
5631 APFloat APF = APFloat(APFloat::IEEEsingle(), APInt(32, Word));
5632 SmallString<8> Str;
5633 APF.toString(Str, 6, 2);
5634 out << Str;
5635 }
5636 break;
5637 }
5638 }
5639}
5640
5641void SPIRVProducerPass::PrintCapability(SPIRVOperand *Op) {
5642 spv::Capability Cap = static_cast<spv::Capability>(Op->getNumID());
5643 out << spv::getCapabilityName(Cap);
5644}
5645
5646void SPIRVProducerPass::PrintExtInst(SPIRVOperand *Op) {
5647 auto LiteralNum = Op->getLiteralNum();
5648 glsl::ExtInst Ext = static_cast<glsl::ExtInst>(LiteralNum[0]);
5649 out << glsl::getExtInstName(Ext);
5650}
5651
5652void SPIRVProducerPass::PrintAddrModel(SPIRVOperand *Op) {
5653 spv::AddressingModel AddrModel =
5654 static_cast<spv::AddressingModel>(Op->getNumID());
5655 out << spv::getAddressingModelName(AddrModel);
5656}
5657
5658void SPIRVProducerPass::PrintMemModel(SPIRVOperand *Op) {
5659 spv::MemoryModel MemModel = static_cast<spv::MemoryModel>(Op->getNumID());
5660 out << spv::getMemoryModelName(MemModel);
5661}
5662
5663void SPIRVProducerPass::PrintExecModel(SPIRVOperand *Op) {
5664 spv::ExecutionModel ExecModel =
5665 static_cast<spv::ExecutionModel>(Op->getNumID());
5666 out << spv::getExecutionModelName(ExecModel);
5667}
5668
5669void SPIRVProducerPass::PrintExecMode(SPIRVOperand *Op) {
5670 spv::ExecutionMode ExecMode = static_cast<spv::ExecutionMode>(Op->getNumID());
5671 out << spv::getExecutionModeName(ExecMode);
5672}
5673
5674void SPIRVProducerPass::PrintSourceLanguage(SPIRVOperand *Op) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005675 spv::SourceLanguage SourceLang =
5676 static_cast<spv::SourceLanguage>(Op->getNumID());
David Neto22f144c2017-06-12 14:26:21 -04005677 out << spv::getSourceLanguageName(SourceLang);
5678}
5679
5680void SPIRVProducerPass::PrintFuncCtrl(SPIRVOperand *Op) {
5681 spv::FunctionControlMask FuncCtrl =
5682 static_cast<spv::FunctionControlMask>(Op->getNumID());
5683 out << spv::getFunctionControlName(FuncCtrl);
5684}
5685
5686void SPIRVProducerPass::PrintStorageClass(SPIRVOperand *Op) {
5687 spv::StorageClass StClass = static_cast<spv::StorageClass>(Op->getNumID());
5688 out << getStorageClassName(StClass);
5689}
5690
5691void SPIRVProducerPass::PrintDecoration(SPIRVOperand *Op) {
5692 spv::Decoration Deco = static_cast<spv::Decoration>(Op->getNumID());
5693 out << getDecorationName(Deco);
5694}
5695
5696void SPIRVProducerPass::PrintBuiltIn(SPIRVOperand *Op) {
5697 spv::BuiltIn BIn = static_cast<spv::BuiltIn>(Op->getNumID());
5698 out << getBuiltInName(BIn);
5699}
5700
5701void SPIRVProducerPass::PrintSelectionControl(SPIRVOperand *Op) {
5702 spv::SelectionControlMask BIn =
5703 static_cast<spv::SelectionControlMask>(Op->getNumID());
5704 out << getSelectionControlName(BIn);
5705}
5706
5707void SPIRVProducerPass::PrintLoopControl(SPIRVOperand *Op) {
5708 spv::LoopControlMask BIn = static_cast<spv::LoopControlMask>(Op->getNumID());
5709 out << getLoopControlName(BIn);
5710}
5711
5712void SPIRVProducerPass::PrintDimensionality(SPIRVOperand *Op) {
5713 spv::Dim DIM = static_cast<spv::Dim>(Op->getNumID());
5714 out << getDimName(DIM);
5715}
5716
5717void SPIRVProducerPass::PrintImageFormat(SPIRVOperand *Op) {
5718 spv::ImageFormat Format = static_cast<spv::ImageFormat>(Op->getNumID());
5719 out << getImageFormatName(Format);
5720}
5721
5722void SPIRVProducerPass::PrintMemoryAccess(SPIRVOperand *Op) {
5723 out << spv::getMemoryAccessName(
5724 static_cast<spv::MemoryAccessMask>(Op->getNumID()));
5725}
5726
5727void SPIRVProducerPass::PrintImageOperandsType(SPIRVOperand *Op) {
5728 auto LiteralNum = Op->getLiteralNum();
5729 spv::ImageOperandsMask Type =
5730 static_cast<spv::ImageOperandsMask>(LiteralNum[0]);
5731 out << getImageOperandsName(Type);
5732}
5733
5734void SPIRVProducerPass::WriteSPIRVAssembly() {
5735 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5736
5737 for (auto Inst : SPIRVInstList) {
5738 SPIRVOperandList Ops = Inst->getOperands();
5739 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5740
5741 switch (Opcode) {
5742 default: {
5743 llvm_unreachable("Unsupported SPIRV instruction");
5744 break;
5745 }
5746 case spv::OpCapability: {
5747 // Ops[0] = Capability
5748 PrintOpcode(Inst);
5749 out << " ";
5750 PrintCapability(Ops[0]);
5751 out << "\n";
5752 break;
5753 }
5754 case spv::OpMemoryModel: {
5755 // Ops[0] = Addressing Model
5756 // Ops[1] = Memory Model
5757 PrintOpcode(Inst);
5758 out << " ";
5759 PrintAddrModel(Ops[0]);
5760 out << " ";
5761 PrintMemModel(Ops[1]);
5762 out << "\n";
5763 break;
5764 }
5765 case spv::OpEntryPoint: {
5766 // Ops[0] = Execution Model
5767 // Ops[1] = EntryPoint ID
5768 // Ops[2] = Name (Literal String)
5769 // Ops[3] ... Ops[n] = Interface ID
5770 PrintOpcode(Inst);
5771 out << " ";
5772 PrintExecModel(Ops[0]);
5773 for (uint32_t i = 1; i < Ops.size(); i++) {
5774 out << " ";
5775 PrintOperand(Ops[i]);
5776 }
5777 out << "\n";
5778 break;
5779 }
5780 case spv::OpExecutionMode: {
5781 // Ops[0] = Entry Point ID
5782 // Ops[1] = Execution Mode
5783 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
5784 PrintOpcode(Inst);
5785 out << " ";
5786 PrintOperand(Ops[0]);
5787 out << " ";
5788 PrintExecMode(Ops[1]);
5789 for (uint32_t i = 2; i < Ops.size(); i++) {
5790 out << " ";
5791 PrintOperand(Ops[i]);
5792 }
5793 out << "\n";
5794 break;
5795 }
5796 case spv::OpSource: {
5797 // Ops[0] = SourceLanguage ID
5798 // Ops[1] = Version (LiteralNum)
5799 PrintOpcode(Inst);
5800 out << " ";
5801 PrintSourceLanguage(Ops[0]);
5802 out << " ";
5803 PrintOperand(Ops[1]);
5804 out << "\n";
5805 break;
5806 }
5807 case spv::OpDecorate: {
5808 // Ops[0] = Target ID
5809 // Ops[1] = Decoration (Block or BufferBlock)
5810 // Ops[2] ... Ops[n] = Optional literals according to Decoration
5811 PrintOpcode(Inst);
5812 out << " ";
5813 PrintOperand(Ops[0]);
5814 out << " ";
5815 PrintDecoration(Ops[1]);
5816 // Handle BuiltIn OpDecorate specially.
5817 if (Ops[1]->getNumID() == spv::DecorationBuiltIn) {
5818 out << " ";
5819 PrintBuiltIn(Ops[2]);
5820 } else {
5821 for (uint32_t i = 2; i < Ops.size(); i++) {
5822 out << " ";
5823 PrintOperand(Ops[i]);
5824 }
5825 }
5826 out << "\n";
5827 break;
5828 }
5829 case spv::OpMemberDecorate: {
5830 // Ops[0] = Structure Type ID
5831 // Ops[1] = Member Index(Literal Number)
5832 // Ops[2] = Decoration
5833 // Ops[3] ... Ops[n] = Optional literals according to Decoration
5834 PrintOpcode(Inst);
5835 out << " ";
5836 PrintOperand(Ops[0]);
5837 out << " ";
5838 PrintOperand(Ops[1]);
5839 out << " ";
5840 PrintDecoration(Ops[2]);
5841 for (uint32_t i = 3; i < Ops.size(); i++) {
5842 out << " ";
5843 PrintOperand(Ops[i]);
5844 }
5845 out << "\n";
5846 break;
5847 }
5848 case spv::OpTypePointer: {
5849 // Ops[0] = Storage Class
5850 // Ops[1] = Element Type ID
5851 PrintResID(Inst);
5852 out << " = ";
5853 PrintOpcode(Inst);
5854 out << " ";
5855 PrintStorageClass(Ops[0]);
5856 out << " ";
5857 PrintOperand(Ops[1]);
5858 out << "\n";
5859 break;
5860 }
5861 case spv::OpTypeImage: {
5862 // Ops[0] = Sampled Type ID
5863 // Ops[1] = Dim ID
5864 // Ops[2] = Depth (Literal Number)
5865 // Ops[3] = Arrayed (Literal Number)
5866 // Ops[4] = MS (Literal Number)
5867 // Ops[5] = Sampled (Literal Number)
5868 // Ops[6] = Image Format ID
5869 PrintResID(Inst);
5870 out << " = ";
5871 PrintOpcode(Inst);
5872 out << " ";
5873 PrintOperand(Ops[0]);
5874 out << " ";
5875 PrintDimensionality(Ops[1]);
5876 out << " ";
5877 PrintOperand(Ops[2]);
5878 out << " ";
5879 PrintOperand(Ops[3]);
5880 out << " ";
5881 PrintOperand(Ops[4]);
5882 out << " ";
5883 PrintOperand(Ops[5]);
5884 out << " ";
5885 PrintImageFormat(Ops[6]);
5886 out << "\n";
5887 break;
5888 }
5889 case spv::OpFunction: {
5890 // Ops[0] : Result Type ID
5891 // Ops[1] : Function Control
5892 // Ops[2] : Function Type ID
5893 PrintResID(Inst);
5894 out << " = ";
5895 PrintOpcode(Inst);
5896 out << " ";
5897 PrintOperand(Ops[0]);
5898 out << " ";
5899 PrintFuncCtrl(Ops[1]);
5900 out << " ";
5901 PrintOperand(Ops[2]);
5902 out << "\n";
5903 break;
5904 }
5905 case spv::OpSelectionMerge: {
5906 // Ops[0] = Merge Block ID
5907 // Ops[1] = Selection Control
5908 PrintOpcode(Inst);
5909 out << " ";
5910 PrintOperand(Ops[0]);
5911 out << " ";
5912 PrintSelectionControl(Ops[1]);
5913 out << "\n";
5914 break;
5915 }
5916 case spv::OpLoopMerge: {
5917 // Ops[0] = Merge Block ID
5918 // Ops[1] = Continue Target ID
5919 // Ops[2] = Selection Control
5920 PrintOpcode(Inst);
5921 out << " ";
5922 PrintOperand(Ops[0]);
5923 out << " ";
5924 PrintOperand(Ops[1]);
5925 out << " ";
5926 PrintLoopControl(Ops[2]);
5927 out << "\n";
5928 break;
5929 }
5930 case spv::OpImageSampleExplicitLod: {
5931 // Ops[0] = Result Type ID
5932 // Ops[1] = Sampled Image ID
5933 // Ops[2] = Coordinate ID
5934 // Ops[3] = Image Operands Type ID
5935 // Ops[4] ... Ops[n] = Operands ID
5936 PrintResID(Inst);
5937 out << " = ";
5938 PrintOpcode(Inst);
5939 for (uint32_t i = 0; i < 3; i++) {
5940 out << " ";
5941 PrintOperand(Ops[i]);
5942 }
5943 out << " ";
5944 PrintImageOperandsType(Ops[3]);
5945 for (uint32_t i = 4; i < Ops.size(); i++) {
5946 out << " ";
5947 PrintOperand(Ops[i]);
5948 }
5949 out << "\n";
5950 break;
5951 }
5952 case spv::OpVariable: {
5953 // Ops[0] : Result Type ID
5954 // Ops[1] : Storage Class
5955 // Ops[2] ... Ops[n] = Initializer IDs
5956 PrintResID(Inst);
5957 out << " = ";
5958 PrintOpcode(Inst);
5959 out << " ";
5960 PrintOperand(Ops[0]);
5961 out << " ";
5962 PrintStorageClass(Ops[1]);
5963 for (uint32_t i = 2; i < Ops.size(); i++) {
5964 out << " ";
5965 PrintOperand(Ops[i]);
5966 }
5967 out << "\n";
5968 break;
5969 }
5970 case spv::OpExtInst: {
5971 // Ops[0] = Result Type ID
5972 // Ops[1] = Set ID (OpExtInstImport ID)
5973 // Ops[2] = Instruction Number (Literal Number)
5974 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5975 PrintResID(Inst);
5976 out << " = ";
5977 PrintOpcode(Inst);
5978 out << " ";
5979 PrintOperand(Ops[0]);
5980 out << " ";
5981 PrintOperand(Ops[1]);
5982 out << " ";
5983 PrintExtInst(Ops[2]);
5984 for (uint32_t i = 3; i < Ops.size(); i++) {
5985 out << " ";
5986 PrintOperand(Ops[i]);
5987 }
5988 out << "\n";
5989 break;
5990 }
5991 case spv::OpCopyMemory: {
5992 // Ops[0] = Addressing Model
5993 // Ops[1] = Memory Model
5994 PrintOpcode(Inst);
5995 out << " ";
5996 PrintOperand(Ops[0]);
5997 out << " ";
5998 PrintOperand(Ops[1]);
5999 out << " ";
6000 PrintMemoryAccess(Ops[2]);
6001 out << " ";
6002 PrintOperand(Ops[3]);
6003 out << "\n";
6004 break;
6005 }
6006 case spv::OpExtension:
6007 case spv::OpControlBarrier:
6008 case spv::OpMemoryBarrier:
6009 case spv::OpBranch:
6010 case spv::OpBranchConditional:
6011 case spv::OpStore:
6012 case spv::OpImageWrite:
6013 case spv::OpReturnValue:
6014 case spv::OpReturn:
6015 case spv::OpFunctionEnd: {
6016 PrintOpcode(Inst);
6017 for (uint32_t i = 0; i < Ops.size(); i++) {
6018 out << " ";
6019 PrintOperand(Ops[i]);
6020 }
6021 out << "\n";
6022 break;
6023 }
6024 case spv::OpExtInstImport:
6025 case spv::OpTypeRuntimeArray:
6026 case spv::OpTypeStruct:
6027 case spv::OpTypeSampler:
6028 case spv::OpTypeSampledImage:
6029 case spv::OpTypeInt:
6030 case spv::OpTypeFloat:
6031 case spv::OpTypeArray:
6032 case spv::OpTypeVector:
6033 case spv::OpTypeBool:
6034 case spv::OpTypeVoid:
6035 case spv::OpTypeFunction:
6036 case spv::OpFunctionParameter:
6037 case spv::OpLabel:
6038 case spv::OpPhi:
6039 case spv::OpLoad:
6040 case spv::OpSelect:
6041 case spv::OpAccessChain:
6042 case spv::OpPtrAccessChain:
6043 case spv::OpInBoundsAccessChain:
6044 case spv::OpUConvert:
6045 case spv::OpSConvert:
6046 case spv::OpConvertFToU:
6047 case spv::OpConvertFToS:
6048 case spv::OpConvertUToF:
6049 case spv::OpConvertSToF:
6050 case spv::OpFConvert:
6051 case spv::OpConvertPtrToU:
6052 case spv::OpConvertUToPtr:
6053 case spv::OpBitcast:
6054 case spv::OpIAdd:
6055 case spv::OpFAdd:
6056 case spv::OpISub:
6057 case spv::OpFSub:
6058 case spv::OpIMul:
6059 case spv::OpFMul:
6060 case spv::OpUDiv:
6061 case spv::OpSDiv:
6062 case spv::OpFDiv:
6063 case spv::OpUMod:
6064 case spv::OpSRem:
6065 case spv::OpFRem:
6066 case spv::OpBitwiseOr:
6067 case spv::OpBitwiseXor:
6068 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04006069 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04006070 case spv::OpShiftLeftLogical:
6071 case spv::OpShiftRightLogical:
6072 case spv::OpShiftRightArithmetic:
6073 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04006074 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04006075 case spv::OpCompositeExtract:
6076 case spv::OpVectorExtractDynamic:
6077 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04006078 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04006079 case spv::OpVectorInsertDynamic:
6080 case spv::OpVectorShuffle:
6081 case spv::OpIEqual:
6082 case spv::OpINotEqual:
6083 case spv::OpUGreaterThan:
6084 case spv::OpUGreaterThanEqual:
6085 case spv::OpULessThan:
6086 case spv::OpULessThanEqual:
6087 case spv::OpSGreaterThan:
6088 case spv::OpSGreaterThanEqual:
6089 case spv::OpSLessThan:
6090 case spv::OpSLessThanEqual:
6091 case spv::OpFOrdEqual:
6092 case spv::OpFOrdGreaterThan:
6093 case spv::OpFOrdGreaterThanEqual:
6094 case spv::OpFOrdLessThan:
6095 case spv::OpFOrdLessThanEqual:
6096 case spv::OpFOrdNotEqual:
6097 case spv::OpFUnordEqual:
6098 case spv::OpFUnordGreaterThan:
6099 case spv::OpFUnordGreaterThanEqual:
6100 case spv::OpFUnordLessThan:
6101 case spv::OpFUnordLessThanEqual:
6102 case spv::OpFUnordNotEqual:
6103 case spv::OpSampledImage:
6104 case spv::OpFunctionCall:
6105 case spv::OpConstantTrue:
6106 case spv::OpConstantFalse:
6107 case spv::OpConstant:
6108 case spv::OpSpecConstant:
6109 case spv::OpConstantComposite:
6110 case spv::OpSpecConstantComposite:
6111 case spv::OpConstantNull:
6112 case spv::OpLogicalOr:
6113 case spv::OpLogicalAnd:
6114 case spv::OpLogicalNot:
6115 case spv::OpLogicalNotEqual:
6116 case spv::OpUndef:
6117 case spv::OpIsInf:
6118 case spv::OpIsNan:
6119 case spv::OpAny:
6120 case spv::OpAll:
David Neto5c22a252018-03-15 16:07:41 -04006121 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04006122 case spv::OpAtomicIAdd:
6123 case spv::OpAtomicISub:
6124 case spv::OpAtomicExchange:
6125 case spv::OpAtomicIIncrement:
6126 case spv::OpAtomicIDecrement:
6127 case spv::OpAtomicCompareExchange:
6128 case spv::OpAtomicUMin:
6129 case spv::OpAtomicSMin:
6130 case spv::OpAtomicUMax:
6131 case spv::OpAtomicSMax:
6132 case spv::OpAtomicAnd:
6133 case spv::OpAtomicOr:
6134 case spv::OpAtomicXor:
6135 case spv::OpDot: {
6136 PrintResID(Inst);
6137 out << " = ";
6138 PrintOpcode(Inst);
6139 for (uint32_t i = 0; i < Ops.size(); i++) {
6140 out << " ";
6141 PrintOperand(Ops[i]);
6142 }
6143 out << "\n";
6144 break;
6145 }
6146 }
6147 }
6148}
6149
6150void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04006151 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04006152}
6153
6154void SPIRVProducerPass::WriteResultID(SPIRVInstruction *Inst) {
6155 WriteOneWord(Inst->getResultID());
6156}
6157
6158void SPIRVProducerPass::WriteWordCountAndOpcode(SPIRVInstruction *Inst) {
6159 // High 16 bit : Word Count
6160 // Low 16 bit : Opcode
6161 uint32_t Word = Inst->getOpcode();
David Netoee2660d2018-06-28 16:31:29 -04006162 const uint32_t count = Inst->getWordCount();
6163 if (count > 65535) {
6164 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
6165 llvm_unreachable("Word count too high");
6166 }
David Neto22f144c2017-06-12 14:26:21 -04006167 Word |= Inst->getWordCount() << 16;
6168 WriteOneWord(Word);
6169}
6170
6171void SPIRVProducerPass::WriteOperand(SPIRVOperand *Op) {
6172 SPIRVOperandType OpTy = Op->getType();
6173 switch (OpTy) {
6174 default: {
6175 llvm_unreachable("Unsupported SPIRV Operand Type???");
6176 break;
6177 }
6178 case SPIRVOperandType::NUMBERID: {
6179 WriteOneWord(Op->getNumID());
6180 break;
6181 }
6182 case SPIRVOperandType::LITERAL_STRING: {
6183 std::string Str = Op->getLiteralStr();
6184 const char *Data = Str.c_str();
6185 size_t WordSize = Str.size() / 4;
6186 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
6187 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
6188 }
6189
6190 uint32_t Remainder = Str.size() % 4;
6191 uint32_t LastWord = 0;
6192 if (Remainder) {
6193 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
6194 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
6195 }
6196 }
6197
6198 WriteOneWord(LastWord);
6199 break;
6200 }
6201 case SPIRVOperandType::LITERAL_INTEGER:
6202 case SPIRVOperandType::LITERAL_FLOAT: {
6203 auto LiteralNum = Op->getLiteralNum();
6204 // TODO: Handle LiteranNum carefully.
6205 for (auto Word : LiteralNum) {
6206 WriteOneWord(Word);
6207 }
6208 break;
6209 }
6210 }
6211}
6212
6213void SPIRVProducerPass::WriteSPIRVBinary() {
6214 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
6215
6216 for (auto Inst : SPIRVInstList) {
David Netoc6f3ab22018-04-06 18:02:31 -04006217 SPIRVOperandList Ops{Inst->getOperands()};
David Neto22f144c2017-06-12 14:26:21 -04006218 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
6219
6220 switch (Opcode) {
6221 default: {
David Neto5c22a252018-03-15 16:07:41 -04006222 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04006223 llvm_unreachable("Unsupported SPIRV instruction");
6224 break;
6225 }
6226 case spv::OpCapability:
6227 case spv::OpExtension:
6228 case spv::OpMemoryModel:
6229 case spv::OpEntryPoint:
6230 case spv::OpExecutionMode:
6231 case spv::OpSource:
6232 case spv::OpDecorate:
6233 case spv::OpMemberDecorate:
6234 case spv::OpBranch:
6235 case spv::OpBranchConditional:
6236 case spv::OpSelectionMerge:
6237 case spv::OpLoopMerge:
6238 case spv::OpStore:
6239 case spv::OpImageWrite:
6240 case spv::OpReturnValue:
6241 case spv::OpControlBarrier:
6242 case spv::OpMemoryBarrier:
6243 case spv::OpReturn:
6244 case spv::OpFunctionEnd:
6245 case spv::OpCopyMemory: {
6246 WriteWordCountAndOpcode(Inst);
6247 for (uint32_t i = 0; i < Ops.size(); i++) {
6248 WriteOperand(Ops[i]);
6249 }
6250 break;
6251 }
6252 case spv::OpTypeBool:
6253 case spv::OpTypeVoid:
6254 case spv::OpTypeSampler:
6255 case spv::OpLabel:
6256 case spv::OpExtInstImport:
6257 case spv::OpTypePointer:
6258 case spv::OpTypeRuntimeArray:
6259 case spv::OpTypeStruct:
6260 case spv::OpTypeImage:
6261 case spv::OpTypeSampledImage:
6262 case spv::OpTypeInt:
6263 case spv::OpTypeFloat:
6264 case spv::OpTypeArray:
6265 case spv::OpTypeVector:
6266 case spv::OpTypeFunction: {
6267 WriteWordCountAndOpcode(Inst);
6268 WriteResultID(Inst);
6269 for (uint32_t i = 0; i < Ops.size(); i++) {
6270 WriteOperand(Ops[i]);
6271 }
6272 break;
6273 }
6274 case spv::OpFunction:
6275 case spv::OpFunctionParameter:
6276 case spv::OpAccessChain:
6277 case spv::OpPtrAccessChain:
6278 case spv::OpInBoundsAccessChain:
6279 case spv::OpUConvert:
6280 case spv::OpSConvert:
6281 case spv::OpConvertFToU:
6282 case spv::OpConvertFToS:
6283 case spv::OpConvertUToF:
6284 case spv::OpConvertSToF:
6285 case spv::OpFConvert:
6286 case spv::OpConvertPtrToU:
6287 case spv::OpConvertUToPtr:
6288 case spv::OpBitcast:
6289 case spv::OpIAdd:
6290 case spv::OpFAdd:
6291 case spv::OpISub:
6292 case spv::OpFSub:
6293 case spv::OpIMul:
6294 case spv::OpFMul:
6295 case spv::OpUDiv:
6296 case spv::OpSDiv:
6297 case spv::OpFDiv:
6298 case spv::OpUMod:
6299 case spv::OpSRem:
6300 case spv::OpFRem:
6301 case spv::OpBitwiseOr:
6302 case spv::OpBitwiseXor:
6303 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04006304 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04006305 case spv::OpShiftLeftLogical:
6306 case spv::OpShiftRightLogical:
6307 case spv::OpShiftRightArithmetic:
6308 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04006309 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04006310 case spv::OpCompositeExtract:
6311 case spv::OpVectorExtractDynamic:
6312 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04006313 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04006314 case spv::OpVectorInsertDynamic:
6315 case spv::OpVectorShuffle:
6316 case spv::OpIEqual:
6317 case spv::OpINotEqual:
6318 case spv::OpUGreaterThan:
6319 case spv::OpUGreaterThanEqual:
6320 case spv::OpULessThan:
6321 case spv::OpULessThanEqual:
6322 case spv::OpSGreaterThan:
6323 case spv::OpSGreaterThanEqual:
6324 case spv::OpSLessThan:
6325 case spv::OpSLessThanEqual:
6326 case spv::OpFOrdEqual:
6327 case spv::OpFOrdGreaterThan:
6328 case spv::OpFOrdGreaterThanEqual:
6329 case spv::OpFOrdLessThan:
6330 case spv::OpFOrdLessThanEqual:
6331 case spv::OpFOrdNotEqual:
6332 case spv::OpFUnordEqual:
6333 case spv::OpFUnordGreaterThan:
6334 case spv::OpFUnordGreaterThanEqual:
6335 case spv::OpFUnordLessThan:
6336 case spv::OpFUnordLessThanEqual:
6337 case spv::OpFUnordNotEqual:
6338 case spv::OpExtInst:
6339 case spv::OpIsInf:
6340 case spv::OpIsNan:
6341 case spv::OpAny:
6342 case spv::OpAll:
6343 case spv::OpUndef:
6344 case spv::OpConstantNull:
6345 case spv::OpLogicalOr:
6346 case spv::OpLogicalAnd:
6347 case spv::OpLogicalNot:
6348 case spv::OpLogicalNotEqual:
6349 case spv::OpConstantComposite:
6350 case spv::OpSpecConstantComposite:
6351 case spv::OpConstantTrue:
6352 case spv::OpConstantFalse:
6353 case spv::OpConstant:
6354 case spv::OpSpecConstant:
6355 case spv::OpVariable:
6356 case spv::OpFunctionCall:
6357 case spv::OpSampledImage:
6358 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04006359 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04006360 case spv::OpSelect:
6361 case spv::OpPhi:
6362 case spv::OpLoad:
6363 case spv::OpAtomicIAdd:
6364 case spv::OpAtomicISub:
6365 case spv::OpAtomicExchange:
6366 case spv::OpAtomicIIncrement:
6367 case spv::OpAtomicIDecrement:
6368 case spv::OpAtomicCompareExchange:
6369 case spv::OpAtomicUMin:
6370 case spv::OpAtomicSMin:
6371 case spv::OpAtomicUMax:
6372 case spv::OpAtomicSMax:
6373 case spv::OpAtomicAnd:
6374 case spv::OpAtomicOr:
6375 case spv::OpAtomicXor:
6376 case spv::OpDot: {
6377 WriteWordCountAndOpcode(Inst);
6378 WriteOperand(Ops[0]);
6379 WriteResultID(Inst);
6380 for (uint32_t i = 1; i < Ops.size(); i++) {
6381 WriteOperand(Ops[i]);
6382 }
6383 break;
6384 }
6385 }
6386 }
6387}
Alan Baker9bf93fb2018-08-28 16:59:26 -04006388
alan-bakerb6b09dc2018-11-08 16:59:28 -05006389bool SPIRVProducerPass::IsTypeNullable(const Type *type) const {
Alan Baker9bf93fb2018-08-28 16:59:26 -04006390 switch (type->getTypeID()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05006391 case Type::HalfTyID:
6392 case Type::FloatTyID:
6393 case Type::DoubleTyID:
6394 case Type::IntegerTyID:
6395 case Type::VectorTyID:
6396 return true;
6397 case Type::PointerTyID: {
6398 const PointerType *pointer_type = cast<PointerType>(type);
6399 if (pointer_type->getPointerAddressSpace() !=
6400 AddressSpace::UniformConstant) {
6401 auto pointee_type = pointer_type->getPointerElementType();
6402 if (pointee_type->isStructTy() &&
6403 cast<StructType>(pointee_type)->isOpaque()) {
6404 // Images and samplers are not nullable.
6405 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04006406 }
Alan Baker9bf93fb2018-08-28 16:59:26 -04006407 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05006408 return true;
6409 }
6410 case Type::ArrayTyID:
6411 return IsTypeNullable(cast<CompositeType>(type)->getTypeAtIndex(0u));
6412 case Type::StructTyID: {
6413 const StructType *struct_type = cast<StructType>(type);
6414 // Images and samplers are not nullable.
6415 if (struct_type->isOpaque())
Alan Baker9bf93fb2018-08-28 16:59:26 -04006416 return false;
alan-bakerb6b09dc2018-11-08 16:59:28 -05006417 for (const auto element : struct_type->elements()) {
6418 if (!IsTypeNullable(element))
6419 return false;
6420 }
6421 return true;
6422 }
6423 default:
6424 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04006425 }
6426}
Alan Bakerfcda9482018-10-02 17:09:59 -04006427
6428void SPIRVProducerPass::PopulateUBOTypeMaps(Module &module) {
6429 if (auto *offsets_md =
6430 module.getNamedMetadata(clspv::RemappedTypeOffsetMetadataName())) {
6431 // Metdata is stored as key-value pair operands. The first element of each
6432 // operand is the type and the second is a vector of offsets.
6433 for (const auto *operand : offsets_md->operands()) {
6434 const auto *pair = cast<MDTuple>(operand);
6435 auto *type =
6436 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
6437 const auto *offset_vector = cast<MDTuple>(pair->getOperand(1));
6438 std::vector<uint32_t> offsets;
6439 for (const Metadata *offset_md : offset_vector->operands()) {
6440 const auto *constant_md = cast<ConstantAsMetadata>(offset_md);
alan-bakerb6b09dc2018-11-08 16:59:28 -05006441 offsets.push_back(static_cast<uint32_t>(
6442 cast<ConstantInt>(constant_md->getValue())->getZExtValue()));
Alan Bakerfcda9482018-10-02 17:09:59 -04006443 }
6444 RemappedUBOTypeOffsets.insert(std::make_pair(type, offsets));
6445 }
6446 }
6447
6448 if (auto *sizes_md =
6449 module.getNamedMetadata(clspv::RemappedTypeSizesMetadataName())) {
6450 // Metadata is stored as key-value pair operands. The first element of each
6451 // operand is the type and the second is a triple of sizes: type size in
6452 // bits, store size and alloc size.
6453 for (const auto *operand : sizes_md->operands()) {
6454 const auto *pair = cast<MDTuple>(operand);
6455 auto *type =
6456 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
6457 const auto *size_triple = cast<MDTuple>(pair->getOperand(1));
6458 uint64_t type_size_in_bits =
6459 cast<ConstantInt>(
6460 cast<ConstantAsMetadata>(size_triple->getOperand(0))->getValue())
6461 ->getZExtValue();
6462 uint64_t type_store_size =
6463 cast<ConstantInt>(
6464 cast<ConstantAsMetadata>(size_triple->getOperand(1))->getValue())
6465 ->getZExtValue();
6466 uint64_t type_alloc_size =
6467 cast<ConstantInt>(
6468 cast<ConstantAsMetadata>(size_triple->getOperand(2))->getValue())
6469 ->getZExtValue();
6470 RemappedUBOTypeSizes.insert(std::make_pair(
6471 type, std::make_tuple(type_size_in_bits, type_store_size,
6472 type_alloc_size)));
6473 }
6474 }
6475}
6476
6477uint64_t SPIRVProducerPass::GetTypeSizeInBits(Type *type,
6478 const DataLayout &DL) {
6479 auto iter = RemappedUBOTypeSizes.find(type);
6480 if (iter != RemappedUBOTypeSizes.end()) {
6481 return std::get<0>(iter->second);
6482 }
6483
6484 return DL.getTypeSizeInBits(type);
6485}
6486
6487uint64_t SPIRVProducerPass::GetTypeStoreSize(Type *type, const DataLayout &DL) {
6488 auto iter = RemappedUBOTypeSizes.find(type);
6489 if (iter != RemappedUBOTypeSizes.end()) {
6490 return std::get<1>(iter->second);
6491 }
6492
6493 return DL.getTypeStoreSize(type);
6494}
6495
6496uint64_t SPIRVProducerPass::GetTypeAllocSize(Type *type, const DataLayout &DL) {
6497 auto iter = RemappedUBOTypeSizes.find(type);
6498 if (iter != RemappedUBOTypeSizes.end()) {
6499 return std::get<2>(iter->second);
6500 }
6501
6502 return DL.getTypeAllocSize(type);
6503}
alan-baker5b86ed72019-02-15 08:26:50 -05006504
6505void SPIRVProducerPass::setVariablePointersCapabilities(unsigned address_space) {
6506 if (GetStorageClass(address_space) == spv::StorageClassStorageBuffer) {
6507 setVariablePointersStorageBuffer(true);
6508 } else {
6509 setVariablePointers(true);
6510 }
6511}
6512
6513Value *SPIRVProducerPass::GetBasePointer(Value* v) {
6514 if (auto *gep = dyn_cast<GetElementPtrInst>(v)) {
6515 return GetBasePointer(gep->getPointerOperand());
6516 }
6517
6518 // Conservatively return |v|.
6519 return v;
6520}
6521
6522bool SPIRVProducerPass::sameResource(Value *lhs, Value *rhs) const {
6523 if (auto *lhs_call = dyn_cast<CallInst>(lhs)) {
6524 if (auto *rhs_call = dyn_cast<CallInst>(rhs)) {
6525 if (lhs_call->getCalledFunction()->getName().startswith(
6526 clspv::ResourceAccessorFunction()) &&
6527 rhs_call->getCalledFunction()->getName().startswith(
6528 clspv::ResourceAccessorFunction())) {
6529 // For resource accessors, match descriptor set and binding.
6530 if (lhs_call->getOperand(0) == rhs_call->getOperand(0) &&
6531 lhs_call->getOperand(1) == rhs_call->getOperand(1))
6532 return true;
6533 } else if (lhs_call->getCalledFunction()->getName().startswith(
6534 clspv::WorkgroupAccessorFunction()) &&
6535 rhs_call->getCalledFunction()->getName().startswith(
6536 clspv::WorkgroupAccessorFunction())) {
6537 // For workgroup resources, match spec id.
6538 if (lhs_call->getOperand(0) == rhs_call->getOperand(0))
6539 return true;
6540 }
6541 }
6542 }
6543
6544 return false;
6545}
6546
6547bool SPIRVProducerPass::selectFromSameObject(Instruction *inst) {
6548 assert(inst->getType()->isPointerTy());
6549 assert(GetStorageClass(inst->getType()->getPointerAddressSpace()) ==
6550 spv::StorageClassStorageBuffer);
6551 const bool hack_undef = clspv::Option::HackUndef();
6552 if (auto *select = dyn_cast<SelectInst>(inst)) {
6553 auto *true_base = GetBasePointer(select->getTrueValue());
6554 auto *false_base = GetBasePointer(select->getFalseValue());
6555
6556 if (true_base == false_base)
6557 return true;
6558
6559 // If either the true or false operand is a null, then we satisfy the same
6560 // object constraint.
6561 if (auto *true_cst = dyn_cast<Constant>(true_base)) {
6562 if (true_cst->isNullValue() || (hack_undef && isa<UndefValue>(true_base)))
6563 return true;
6564 }
6565
6566 if (auto *false_cst = dyn_cast<Constant>(false_base)) {
6567 if (false_cst->isNullValue() ||
6568 (hack_undef && isa<UndefValue>(false_base)))
6569 return true;
6570 }
6571
6572 if (sameResource(true_base, false_base))
6573 return true;
6574 } else if (auto *phi = dyn_cast<PHINode>(inst)) {
6575 Value *value = nullptr;
6576 bool ok = true;
6577 for (unsigned i = 0; ok && i != phi->getNumIncomingValues(); ++i) {
6578 auto *base = GetBasePointer(phi->getIncomingValue(i));
6579 // Null values satisfy the constraint of selecting of selecting from the
6580 // same object.
6581 if (!value) {
6582 if (auto *cst = dyn_cast<Constant>(base)) {
6583 if (!cst->isNullValue() && !(hack_undef && isa<UndefValue>(base)))
6584 value = base;
6585 } else {
6586 value = base;
6587 }
6588 } else if (base != value) {
6589 if (auto *base_cst = dyn_cast<Constant>(base)) {
6590 if (base_cst->isNullValue() || (hack_undef && isa<UndefValue>(base)))
6591 continue;
6592 }
6593
6594 if (sameResource(value, base))
6595 continue;
6596
6597 // Values don't represent the same base.
6598 ok = false;
6599 }
6600 }
6601
6602 return ok;
6603 }
6604
6605 // Conservatively return false.
6606 return false;
6607}