blob: c4659c1b5b8883ef466a0207409e6944225037fd [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"
David Neto85082642018-03-24 06:55:20 -070049#include "clspv/spirv_c_strings.hpp"
50#include "clspv/spirv_glsl.hpp"
David Neto22f144c2017-06-12 14:26:21 -040051
David Neto4feb7a42017-10-06 17:29:42 -040052#include "ArgKind.h"
David Neto85082642018-03-24 06:55:20 -070053#include "ConstantEmitter.h"
Alan Baker202c8c72018-08-13 13:47:44 -040054#include "Constants.h"
David Neto78383442018-06-15 20:31:56 -040055#include "DescriptorCounter.h"
alan-baker56f7aff2019-05-22 08:06:42 -040056#include "NormalizeGlobalVariable.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040057#include "Passes.h"
David Neto48f56a42017-10-06 16:44:25 -040058
David Neto22f144c2017-06-12 14:26:21 -040059#if defined(_MSC_VER)
60#pragma warning(pop)
61#endif
62
63using namespace llvm;
64using namespace clspv;
David Neto156783e2017-07-05 15:39:41 -040065using namespace mdconst;
David Neto22f144c2017-06-12 14:26:21 -040066
67namespace {
David Netocd8ca5f2017-10-02 23:34:11 -040068
David Neto862b7d82018-06-14 18:48:37 -040069cl::opt<bool> ShowResourceVars("show-rv", cl::init(false), cl::Hidden,
70 cl::desc("Show resource variable creation"));
71
72// These hacks exist to help transition code generation algorithms
73// without making huge noise in detailed test output.
74const bool Hack_generate_runtime_array_stride_early = true;
75
David Neto3fbb4072017-10-16 11:28:14 -040076// The value of 1/pi. This value is from MSDN
77// https://msdn.microsoft.com/en-us/library/4hwaceh6.aspx
78const double kOneOverPi = 0.318309886183790671538;
79const glsl::ExtInst kGlslExtInstBad = static_cast<glsl::ExtInst>(0);
80
alan-bakerb6b09dc2018-11-08 16:59:28 -050081const char *kCompositeConstructFunctionPrefix = "clspv.composite_construct.";
David Netoab03f432017-11-03 17:00:44 -040082
David Neto22f144c2017-06-12 14:26:21 -040083enum SPIRVOperandType {
84 NUMBERID,
85 LITERAL_INTEGER,
86 LITERAL_STRING,
87 LITERAL_FLOAT
88};
89
90struct SPIRVOperand {
91 explicit SPIRVOperand(SPIRVOperandType Ty, uint32_t Num)
92 : Type(Ty), LiteralNum(1, Num) {}
93 explicit SPIRVOperand(SPIRVOperandType Ty, const char *Str)
94 : Type(Ty), LiteralStr(Str) {}
95 explicit SPIRVOperand(SPIRVOperandType Ty, StringRef Str)
96 : Type(Ty), LiteralStr(Str) {}
97 explicit SPIRVOperand(SPIRVOperandType Ty, ArrayRef<uint32_t> NumVec)
98 : Type(Ty), LiteralNum(NumVec.begin(), NumVec.end()) {}
99
100 SPIRVOperandType getType() { return Type; };
101 uint32_t getNumID() { return LiteralNum[0]; };
102 std::string getLiteralStr() { return LiteralStr; };
103 ArrayRef<uint32_t> getLiteralNum() { return LiteralNum; };
104
David Neto87846742018-04-11 17:36:22 -0400105 uint32_t GetNumWords() const {
106 switch (Type) {
107 case NUMBERID:
108 return 1;
109 case LITERAL_INTEGER:
110 case LITERAL_FLOAT:
David Netoee2660d2018-06-28 16:31:29 -0400111 return uint32_t(LiteralNum.size());
David Neto87846742018-04-11 17:36:22 -0400112 case LITERAL_STRING:
113 // Account for the terminating null character.
David Netoee2660d2018-06-28 16:31:29 -0400114 return uint32_t((LiteralStr.size() + 4) / 4);
David Neto87846742018-04-11 17:36:22 -0400115 }
116 llvm_unreachable("Unhandled case in SPIRVOperand::GetNumWords()");
117 }
118
David Neto22f144c2017-06-12 14:26:21 -0400119private:
120 SPIRVOperandType Type;
121 std::string LiteralStr;
122 SmallVector<uint32_t, 4> LiteralNum;
123};
124
David Netoc6f3ab22018-04-06 18:02:31 -0400125class SPIRVOperandList {
126public:
127 SPIRVOperandList() {}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500128 SPIRVOperandList(const SPIRVOperandList &other) = delete;
129 SPIRVOperandList(SPIRVOperandList &&other) {
David Netoc6f3ab22018-04-06 18:02:31 -0400130 contents_ = std::move(other.contents_);
131 other.contents_.clear();
132 }
133 SPIRVOperandList(ArrayRef<SPIRVOperand *> init)
134 : contents_(init.begin(), init.end()) {}
135 operator ArrayRef<SPIRVOperand *>() { return contents_; }
136 void push_back(SPIRVOperand *op) { contents_.push_back(op); }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500137 void clear() { contents_.clear(); }
David Netoc6f3ab22018-04-06 18:02:31 -0400138 size_t size() const { return contents_.size(); }
139 SPIRVOperand *&operator[](size_t i) { return contents_[i]; }
140
David Neto87846742018-04-11 17:36:22 -0400141 const SmallVector<SPIRVOperand *, 8> &getOperands() const {
142 return contents_;
143 }
144
David Netoc6f3ab22018-04-06 18:02:31 -0400145private:
alan-bakerb6b09dc2018-11-08 16:59:28 -0500146 SmallVector<SPIRVOperand *, 8> contents_;
David Netoc6f3ab22018-04-06 18:02:31 -0400147};
148
149SPIRVOperandList &operator<<(SPIRVOperandList &list, SPIRVOperand *elem) {
150 list.push_back(elem);
151 return list;
152}
153
alan-bakerb6b09dc2018-11-08 16:59:28 -0500154SPIRVOperand *MkNum(uint32_t num) {
David Netoc6f3ab22018-04-06 18:02:31 -0400155 return new SPIRVOperand(LITERAL_INTEGER, num);
156}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500157SPIRVOperand *MkInteger(ArrayRef<uint32_t> num_vec) {
David Neto257c3892018-04-11 13:19:45 -0400158 return new SPIRVOperand(LITERAL_INTEGER, num_vec);
159}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500160SPIRVOperand *MkFloat(ArrayRef<uint32_t> num_vec) {
David Neto257c3892018-04-11 13:19:45 -0400161 return new SPIRVOperand(LITERAL_FLOAT, num_vec);
162}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500163SPIRVOperand *MkId(uint32_t id) { return new SPIRVOperand(NUMBERID, id); }
164SPIRVOperand *MkString(StringRef str) {
David Neto257c3892018-04-11 13:19:45 -0400165 return new SPIRVOperand(LITERAL_STRING, str);
166}
David Netoc6f3ab22018-04-06 18:02:31 -0400167
David Neto22f144c2017-06-12 14:26:21 -0400168struct SPIRVInstruction {
David Neto87846742018-04-11 17:36:22 -0400169 // Create an instruction with an opcode and no result ID, and with the given
170 // operands. This computes its own word count.
171 explicit SPIRVInstruction(spv::Op Opc, ArrayRef<SPIRVOperand *> Ops)
172 : WordCount(1), Opcode(static_cast<uint16_t>(Opc)), ResultID(0),
173 Operands(Ops.begin(), Ops.end()) {
174 for (auto *operand : Ops) {
David Netoee2660d2018-06-28 16:31:29 -0400175 WordCount += uint16_t(operand->GetNumWords());
David Neto87846742018-04-11 17:36:22 -0400176 }
177 }
178 // Create an instruction with an opcode and a no-zero result ID, and
179 // with the given operands. This computes its own word count.
180 explicit SPIRVInstruction(spv::Op Opc, uint32_t ResID,
David Neto22f144c2017-06-12 14:26:21 -0400181 ArrayRef<SPIRVOperand *> Ops)
David Neto87846742018-04-11 17:36:22 -0400182 : WordCount(2), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID),
183 Operands(Ops.begin(), Ops.end()) {
184 if (ResID == 0) {
185 llvm_unreachable("Result ID of 0 was provided");
186 }
187 for (auto *operand : Ops) {
188 WordCount += operand->GetNumWords();
189 }
190 }
David Neto22f144c2017-06-12 14:26:21 -0400191
David Netoee2660d2018-06-28 16:31:29 -0400192 uint32_t getWordCount() const { return WordCount; }
David Neto22f144c2017-06-12 14:26:21 -0400193 uint16_t getOpcode() const { return Opcode; }
194 uint32_t getResultID() const { return ResultID; }
195 ArrayRef<SPIRVOperand *> getOperands() const { return Operands; }
196
197private:
David Netoee2660d2018-06-28 16:31:29 -0400198 uint32_t WordCount; // Check the 16-bit bound at code generation time.
David Neto22f144c2017-06-12 14:26:21 -0400199 uint16_t Opcode;
200 uint32_t ResultID;
201 SmallVector<SPIRVOperand *, 4> Operands;
202};
203
204struct SPIRVProducerPass final : public ModulePass {
David Neto22f144c2017-06-12 14:26:21 -0400205 typedef DenseMap<Type *, uint32_t> TypeMapType;
206 typedef UniqueVector<Type *> TypeList;
207 typedef DenseMap<Value *, uint32_t> ValueMapType;
David Netofb9a7972017-08-25 17:08:24 -0400208 typedef UniqueVector<Value *> ValueList;
David Neto22f144c2017-06-12 14:26:21 -0400209 typedef std::vector<std::pair<Value *, uint32_t>> EntryPointVecType;
210 typedef std::list<SPIRVInstruction *> SPIRVInstructionList;
David Neto87846742018-04-11 17:36:22 -0400211 // A vector of tuples, each of which is:
212 // - the LLVM instruction that we will later generate SPIR-V code for
213 // - where the SPIR-V instruction should be inserted
214 // - the result ID of the SPIR-V instruction
David Neto22f144c2017-06-12 14:26:21 -0400215 typedef std::vector<
216 std::tuple<Value *, SPIRVInstructionList::iterator, uint32_t>>
217 DeferredInstVecType;
218 typedef DenseMap<FunctionType *, std::pair<FunctionType *, uint32_t>>
219 GlobalConstFuncMapType;
220
David Neto44795152017-07-13 15:45:28 -0400221 explicit SPIRVProducerPass(
alan-bakerf5e5f692018-11-27 08:33:24 -0500222 raw_pwrite_stream &out,
223 std::vector<clspv::version0::DescriptorMapEntry> *descriptor_map_entries,
alan-baker00e7a582019-06-07 12:54:21 -0400224 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
David Neto44795152017-07-13 15:45:28 -0400225 bool outputCInitList)
David Netoc2c368d2017-06-30 16:50:17 -0400226 : ModulePass(ID), samplerMap(samplerMap), out(out),
David Neto0676e6f2017-07-11 18:47:44 -0400227 binaryTempOut(binaryTempUnderlyingVector), binaryOut(&out),
alan-baker00e7a582019-06-07 12:54:21 -0400228 descriptorMapEntries(descriptor_map_entries),
David Neto0676e6f2017-07-11 18:47:44 -0400229 outputCInitList(outputCInitList), patchBoundOffset(0), nextID(1),
alan-baker5b86ed72019-02-15 08:26:50 -0500230 OpExtInstImportID(0), HasVariablePointersStorageBuffer(false),
231 HasVariablePointers(false), SamplerTy(nullptr), WorkgroupSizeValueID(0),
Kévin Petit89a525c2019-06-15 08:13:07 +0100232 WorkgroupSizeVarID(0), max_local_spec_id_(0) {}
David Neto22f144c2017-06-12 14:26:21 -0400233
234 void getAnalysisUsage(AnalysisUsage &AU) const override {
235 AU.addRequired<DominatorTreeWrapperPass>();
236 AU.addRequired<LoopInfoWrapperPass>();
237 }
238
239 virtual bool runOnModule(Module &module) override;
240
241 // output the SPIR-V header block
242 void outputHeader();
243
244 // patch the SPIR-V header block
245 void patchHeader();
246
247 uint32_t lookupType(Type *Ty) {
248 if (Ty->isPointerTy() &&
249 (Ty->getPointerAddressSpace() != AddressSpace::UniformConstant)) {
250 auto PointeeTy = Ty->getPointerElementType();
251 if (PointeeTy->isStructTy() &&
252 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
253 Ty = PointeeTy;
254 }
255 }
256
David Neto862b7d82018-06-14 18:48:37 -0400257 auto where = TypeMap.find(Ty);
258 if (where == TypeMap.end()) {
259 if (Ty) {
260 errs() << "Unhandled type " << *Ty << "\n";
261 } else {
262 errs() << "Unhandled type (null)\n";
263 }
David Netoe439d702018-03-23 13:14:08 -0700264 llvm_unreachable("\nUnhandled type!");
David Neto22f144c2017-06-12 14:26:21 -0400265 }
266
David Neto862b7d82018-06-14 18:48:37 -0400267 return where->second;
David Neto22f144c2017-06-12 14:26:21 -0400268 }
269 TypeMapType &getImageTypeMap() { return ImageTypeMap; }
270 TypeList &getTypeList() { return Types; };
271 ValueList &getConstantList() { return Constants; };
272 ValueMapType &getValueMap() { return ValueMap; }
273 ValueMapType &getAllocatedValueMap() { return AllocatedValueMap; }
274 SPIRVInstructionList &getSPIRVInstList() { return SPIRVInsts; };
David Neto22f144c2017-06-12 14:26:21 -0400275 EntryPointVecType &getEntryPointVec() { return EntryPointVec; };
276 DeferredInstVecType &getDeferredInstVec() { return DeferredInstVec; };
277 ValueList &getEntryPointInterfacesVec() { return EntryPointInterfacesVec; };
278 uint32_t &getOpExtInstImportID() { return OpExtInstImportID; };
279 std::vector<uint32_t> &getBuiltinDimVec() { return BuiltinDimensionVec; };
alan-baker5b86ed72019-02-15 08:26:50 -0500280 bool hasVariablePointersStorageBuffer() {
281 return HasVariablePointersStorageBuffer;
282 }
283 void setVariablePointersStorageBuffer(bool Val) {
284 HasVariablePointersStorageBuffer = Val;
285 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400286 bool hasVariablePointers() { return HasVariablePointers; };
David Neto22f144c2017-06-12 14:26:21 -0400287 void setVariablePointers(bool Val) { HasVariablePointers = Val; };
alan-bakerb6b09dc2018-11-08 16:59:28 -0500288 ArrayRef<std::pair<unsigned, std::string>> &getSamplerMap() {
289 return samplerMap;
290 }
David Neto22f144c2017-06-12 14:26:21 -0400291 GlobalConstFuncMapType &getGlobalConstFuncTypeMap() {
292 return GlobalConstFuncTypeMap;
293 }
294 SmallPtrSet<Value *, 16> &getGlobalConstArgSet() {
295 return GlobalConstArgumentSet;
296 }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500297 TypeList &getTypesNeedingArrayStride() { return TypesNeedingArrayStride; }
David Neto22f144c2017-06-12 14:26:21 -0400298
David Netoc6f3ab22018-04-06 18:02:31 -0400299 void GenerateLLVMIRInfo(Module &M, const DataLayout &DL);
alan-bakerb6b09dc2018-11-08 16:59:28 -0500300 // Populate GlobalConstFuncTypeMap. Also, if module-scope __constant will
301 // *not* be converted to a storage buffer, replace each such global variable
302 // with one in the storage class expecgted by SPIR-V.
David Neto862b7d82018-06-14 18:48:37 -0400303 void FindGlobalConstVars(Module &M, const DataLayout &DL);
304 // Populate ResourceVarInfoList, FunctionToResourceVarsMap, and
305 // ModuleOrderedResourceVars.
306 void FindResourceVars(Module &M, const DataLayout &DL);
Alan Baker202c8c72018-08-13 13:47:44 -0400307 void FindWorkgroupVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400308 bool FindExtInst(Module &M);
309 void FindTypePerGlobalVar(GlobalVariable &GV);
310 void FindTypePerFunc(Function &F);
David Neto862b7d82018-06-14 18:48:37 -0400311 void FindTypesForSamplerMap(Module &M);
312 void FindTypesForResourceVars(Module &M);
alan-bakerb6b09dc2018-11-08 16:59:28 -0500313 // Inserts |Ty| and relevant sub-types into the |Types| member, indicating
314 // that |Ty| and its subtypes will need a corresponding SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400315 void FindType(Type *Ty);
316 void FindConstantPerGlobalVar(GlobalVariable &GV);
317 void FindConstantPerFunc(Function &F);
318 void FindConstant(Value *V);
319 void GenerateExtInstImport();
David Neto19a1bad2017-08-25 15:01:41 -0400320 // Generates instructions for SPIR-V types corresponding to the LLVM types
321 // saved in the |Types| member. A type follows its subtypes. IDs are
322 // allocated sequentially starting with the current value of nextID, and
323 // with a type following its subtypes. Also updates nextID to just beyond
324 // the last generated ID.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500325 void GenerateSPIRVTypes(LLVMContext &context, Module &module);
David Neto22f144c2017-06-12 14:26:21 -0400326 void GenerateSPIRVConstants();
David Neto5c22a252018-03-15 16:07:41 -0400327 void GenerateModuleInfo(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400328 void GenerateGlobalVar(GlobalVariable &GV);
David Netoc6f3ab22018-04-06 18:02:31 -0400329 void GenerateWorkgroupVars();
David Neto862b7d82018-06-14 18:48:37 -0400330 // Generate descriptor map entries for resource variables associated with
331 // arguments to F.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500332 void GenerateDescriptorMapInfo(const DataLayout &DL, Function &F);
David Neto22f144c2017-06-12 14:26:21 -0400333 void GenerateSamplers(Module &M);
David Neto862b7d82018-06-14 18:48:37 -0400334 // Generate OpVariables for %clspv.resource.var.* calls.
335 void GenerateResourceVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400336 void GenerateFuncPrologue(Function &F);
337 void GenerateFuncBody(Function &F);
David Netob6e2e062018-04-25 10:32:06 -0400338 void GenerateEntryPointInitialStores();
David Neto22f144c2017-06-12 14:26:21 -0400339 spv::Op GetSPIRVCmpOpcode(CmpInst *CmpI);
340 spv::Op GetSPIRVCastOpcode(Instruction &I);
341 spv::Op GetSPIRVBinaryOpcode(Instruction &I);
342 void GenerateInstruction(Instruction &I);
343 void GenerateFuncEpilogue();
344 void HandleDeferredInstruction();
alan-bakerb6b09dc2018-11-08 16:59:28 -0500345 void HandleDeferredDecorations(const DataLayout &DL);
David Neto22f144c2017-06-12 14:26:21 -0400346 bool is4xi8vec(Type *Ty) const;
347 spv::StorageClass GetStorageClass(unsigned AddrSpace) const;
David Neto862b7d82018-06-14 18:48:37 -0400348 spv::StorageClass GetStorageClassForArgKind(clspv::ArgKind arg_kind) const;
David Neto22f144c2017-06-12 14:26:21 -0400349 spv::BuiltIn GetBuiltin(StringRef globalVarName) const;
David Neto3fbb4072017-10-16 11:28:14 -0400350 // Returns the GLSL extended instruction enum that the given function
351 // call maps to. If none, then returns the 0 value, i.e. GLSLstd4580Bad.
David Neto22f144c2017-06-12 14:26:21 -0400352 glsl::ExtInst getExtInstEnum(StringRef Name);
David Neto3fbb4072017-10-16 11:28:14 -0400353 // Returns the GLSL extended instruction enum indirectly used by the given
354 // function. That is, to implement the given function, we use an extended
355 // instruction plus one more instruction. If none, then returns the 0 value,
356 // i.e. GLSLstd4580Bad.
357 glsl::ExtInst getIndirectExtInstEnum(StringRef Name);
358 // Returns the single GLSL extended instruction used directly or
359 // indirectly by the given function call.
360 glsl::ExtInst getDirectOrIndirectExtInstEnum(StringRef Name);
David Neto22f144c2017-06-12 14:26:21 -0400361 void WriteOneWord(uint32_t Word);
362 void WriteResultID(SPIRVInstruction *Inst);
363 void WriteWordCountAndOpcode(SPIRVInstruction *Inst);
364 void WriteOperand(SPIRVOperand *Op);
365 void WriteSPIRVBinary();
366
Alan Baker9bf93fb2018-08-28 16:59:26 -0400367 // Returns true if |type| is compatible with OpConstantNull.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500368 bool IsTypeNullable(const Type *type) const;
Alan Baker9bf93fb2018-08-28 16:59:26 -0400369
Alan Bakerfcda9482018-10-02 17:09:59 -0400370 // Populate UBO remapped type maps.
371 void PopulateUBOTypeMaps(Module &module);
372
373 // Wrapped methods of DataLayout accessors. If |type| was remapped for UBOs,
374 // uses the internal map, otherwise it falls back on the data layout.
375 uint64_t GetTypeSizeInBits(Type *type, const DataLayout &DL);
376 uint64_t GetTypeStoreSize(Type *type, const DataLayout &DL);
377 uint64_t GetTypeAllocSize(Type *type, const DataLayout &DL);
378
alan-baker5b86ed72019-02-15 08:26:50 -0500379 // Returns the base pointer of |v|.
380 Value *GetBasePointer(Value *v);
381
382 // Sets |HasVariablePointersStorageBuffer| or |HasVariablePointers| base on
383 // |address_space|.
384 void setVariablePointersCapabilities(unsigned address_space);
385
386 // Returns true if |lhs| and |rhs| represent the same resource or workgroup
387 // variable.
388 bool sameResource(Value *lhs, Value *rhs) const;
389
390 // Returns true if |inst| is phi or select that selects from the same
391 // structure (or null).
392 bool selectFromSameObject(Instruction *inst);
393
alan-bakere9308012019-03-15 10:25:13 -0400394 // Returns true if |Arg| is called with a coherent resource.
395 bool CalledWithCoherentResource(Argument &Arg);
396
David Neto22f144c2017-06-12 14:26:21 -0400397private:
398 static char ID;
David Neto44795152017-07-13 15:45:28 -0400399 ArrayRef<std::pair<unsigned, std::string>> samplerMap;
David Neto22f144c2017-06-12 14:26:21 -0400400 raw_pwrite_stream &out;
David Neto0676e6f2017-07-11 18:47:44 -0400401
402 // TODO(dneto): Wouldn't it be better to always just emit a binary, and then
403 // convert to other formats on demand?
404
405 // When emitting a C initialization list, the WriteSPIRVBinary method
406 // will actually write its words to this vector via binaryTempOut.
407 SmallVector<char, 100> binaryTempUnderlyingVector;
408 raw_svector_ostream binaryTempOut;
409
410 // Binary output writes to this stream, which might be |out| or
411 // |binaryTempOut|. It's the latter when we really want to write a C
412 // initializer list.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400413 raw_pwrite_stream *binaryOut;
alan-bakerf5e5f692018-11-27 08:33:24 -0500414 std::vector<version0::DescriptorMapEntry> *descriptorMapEntries;
David Neto0676e6f2017-07-11 18:47:44 -0400415 const bool outputCInitList; // If true, output look like {0x7023, ... , 5}
David Neto22f144c2017-06-12 14:26:21 -0400416 uint64_t patchBoundOffset;
417 uint32_t nextID;
418
David Neto19a1bad2017-08-25 15:01:41 -0400419 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400420 TypeMapType TypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400421 // Maps an LLVM image type to its SPIR-V ID.
David Neto22f144c2017-06-12 14:26:21 -0400422 TypeMapType ImageTypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400423 // A unique-vector of LLVM types that map to a SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400424 TypeList Types;
425 ValueList Constants;
David Neto19a1bad2017-08-25 15:01:41 -0400426 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400427 ValueMapType ValueMap;
428 ValueMapType AllocatedValueMap;
429 SPIRVInstructionList SPIRVInsts;
David Neto862b7d82018-06-14 18:48:37 -0400430
David Neto22f144c2017-06-12 14:26:21 -0400431 EntryPointVecType EntryPointVec;
432 DeferredInstVecType DeferredInstVec;
433 ValueList EntryPointInterfacesVec;
434 uint32_t OpExtInstImportID;
435 std::vector<uint32_t> BuiltinDimensionVec;
alan-baker5b86ed72019-02-15 08:26:50 -0500436 bool HasVariablePointersStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -0400437 bool HasVariablePointers;
438 Type *SamplerTy;
alan-bakerb6b09dc2018-11-08 16:59:28 -0500439 DenseMap<unsigned, uint32_t> SamplerMapIndexToIDMap;
David Netoc77d9e22018-03-24 06:30:28 -0700440
441 // If a function F has a pointer-to-__constant parameter, then this variable
David Neto9ed8e2f2018-03-24 06:47:24 -0700442 // will map F's type to (G, index of the parameter), where in a first phase
443 // G is F's type. During FindTypePerFunc, G will be changed to F's type
444 // but replacing the pointer-to-constant parameter with
445 // pointer-to-ModuleScopePrivate.
David Netoc77d9e22018-03-24 06:30:28 -0700446 // TODO(dneto): This doesn't seem general enough? A function might have
447 // more than one such parameter.
David Neto22f144c2017-06-12 14:26:21 -0400448 GlobalConstFuncMapType GlobalConstFuncTypeMap;
449 SmallPtrSet<Value *, 16> GlobalConstArgumentSet;
David Neto1a1a0582017-07-07 12:01:44 -0400450 // An ordered set of pointer types of Base arguments to OpPtrAccessChain,
David Neto85082642018-03-24 06:55:20 -0700451 // or array types, and which point into transparent memory (StorageBuffer
452 // storage class). These will require an ArrayStride decoration.
David Neto1a1a0582017-07-07 12:01:44 -0400453 // See SPV_KHR_variable_pointers rev 13.
David Neto85082642018-03-24 06:55:20 -0700454 TypeList TypesNeedingArrayStride;
David Netoa60b00b2017-09-15 16:34:09 -0400455
456 // This is truly ugly, but works around what look like driver bugs.
457 // For get_local_size, an earlier part of the flow has created a module-scope
458 // variable in Private address space to hold the value for the workgroup
459 // size. Its intializer is a uint3 value marked as builtin WorkgroupSize.
460 // When this is present, save the IDs of the initializer value and variable
461 // in these two variables. We only ever do a vector load from it, and
462 // when we see one of those, substitute just the value of the intializer.
463 // This mimics what Glslang does, and that's what drivers are used to.
David Neto66cfe642018-03-24 06:13:56 -0700464 // TODO(dneto): Remove this once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -0400465 uint32_t WorkgroupSizeValueID;
466 uint32_t WorkgroupSizeVarID;
David Neto26aaf622017-10-23 18:11:53 -0400467
David Neto862b7d82018-06-14 18:48:37 -0400468 // Bookkeeping for mapping kernel arguments to resource variables.
469 struct ResourceVarInfo {
470 ResourceVarInfo(int index_arg, unsigned set_arg, unsigned binding_arg,
alan-bakere9308012019-03-15 10:25:13 -0400471 Function *fn, clspv::ArgKind arg_kind_arg, int coherent_arg)
David Neto862b7d82018-06-14 18:48:37 -0400472 : index(index_arg), descriptor_set(set_arg), binding(binding_arg),
alan-bakere9308012019-03-15 10:25:13 -0400473 var_fn(fn), arg_kind(arg_kind_arg), coherent(coherent_arg),
David Neto862b7d82018-06-14 18:48:37 -0400474 addr_space(fn->getReturnType()->getPointerAddressSpace()) {}
475 const int index; // Index into ResourceVarInfoList
476 const unsigned descriptor_set;
477 const unsigned binding;
478 Function *const var_fn; // The @clspv.resource.var.* function.
479 const clspv::ArgKind arg_kind;
alan-bakere9308012019-03-15 10:25:13 -0400480 const int coherent;
David Neto862b7d82018-06-14 18:48:37 -0400481 const unsigned addr_space; // The LLVM address space
482 // The SPIR-V ID of the OpVariable. Not populated at construction time.
483 uint32_t var_id = 0;
484 };
485 // A list of resource var info. Each one correponds to a module-scope
486 // resource variable we will have to create. Resource var indices are
487 // indices into this vector.
488 SmallVector<std::unique_ptr<ResourceVarInfo>, 8> ResourceVarInfoList;
489 // This is a vector of pointers of all the resource vars, but ordered by
490 // kernel function, and then by argument.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500491 UniqueVector<ResourceVarInfo *> ModuleOrderedResourceVars;
David Neto862b7d82018-06-14 18:48:37 -0400492 // Map a function to the ordered list of resource variables it uses, one for
493 // each argument. If an argument does not use a resource variable, it
494 // will have a null pointer entry.
495 using FunctionToResourceVarsMapType =
496 DenseMap<Function *, SmallVector<ResourceVarInfo *, 8>>;
497 FunctionToResourceVarsMapType FunctionToResourceVarsMap;
498
499 // What LLVM types map to SPIR-V types needing layout? These are the
500 // arrays and structures supporting storage buffers and uniform buffers.
501 TypeList TypesNeedingLayout;
502 // What LLVM struct types map to a SPIR-V struct type with Block decoration?
503 UniqueVector<StructType *> StructTypesNeedingBlock;
504 // For a call that represents a load from an opaque type (samplers, images),
505 // map it to the variable id it should load from.
506 DenseMap<CallInst *, uint32_t> ResourceVarDeferredLoadCalls;
David Neto85082642018-03-24 06:55:20 -0700507
Alan Baker202c8c72018-08-13 13:47:44 -0400508 // One larger than the maximum used SpecId for pointer-to-local arguments.
509 int max_local_spec_id_;
David Netoc6f3ab22018-04-06 18:02:31 -0400510 // An ordered list of the kernel arguments of type pointer-to-local.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500511 using LocalArgList = SmallVector<Argument *, 8>;
David Netoc6f3ab22018-04-06 18:02:31 -0400512 LocalArgList LocalArgs;
513 // Information about a pointer-to-local argument.
514 struct LocalArgInfo {
515 // The SPIR-V ID of the array variable.
516 uint32_t variable_id;
517 // The element type of the
alan-bakerb6b09dc2018-11-08 16:59:28 -0500518 Type *elem_type;
David Netoc6f3ab22018-04-06 18:02:31 -0400519 // The ID of the array type.
520 uint32_t array_size_id;
521 // The ID of the array type.
522 uint32_t array_type_id;
523 // The ID of the pointer to the array type.
524 uint32_t ptr_array_type_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400525 // The specialization constant ID of the array size.
526 int spec_id;
527 };
Alan Baker202c8c72018-08-13 13:47:44 -0400528 // A mapping from Argument to its assigned SpecId.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500529 DenseMap<const Argument *, int> LocalArgSpecIds;
Alan Baker202c8c72018-08-13 13:47:44 -0400530 // A mapping from SpecId to its LocalArgInfo.
531 DenseMap<int, LocalArgInfo> LocalSpecIdInfoMap;
Alan Bakerfcda9482018-10-02 17:09:59 -0400532 // A mapping from a remapped type to its real offsets.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500533 DenseMap<Type *, std::vector<uint32_t>> RemappedUBOTypeOffsets;
Alan Bakerfcda9482018-10-02 17:09:59 -0400534 // A mapping from a remapped type to its real sizes.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500535 DenseMap<Type *, std::tuple<uint64_t, uint64_t, uint64_t>>
536 RemappedUBOTypeSizes;
David Neto22f144c2017-06-12 14:26:21 -0400537};
538
539char SPIRVProducerPass::ID;
David Netoc6f3ab22018-04-06 18:02:31 -0400540
alan-bakerb6b09dc2018-11-08 16:59:28 -0500541} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400542
543namespace clspv {
alan-bakerf5e5f692018-11-27 08:33:24 -0500544ModulePass *createSPIRVProducerPass(
545 raw_pwrite_stream &out,
546 std::vector<version0::DescriptorMapEntry> *descriptor_map_entries,
alan-baker00e7a582019-06-07 12:54:21 -0400547 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
alan-bakerf5e5f692018-11-27 08:33:24 -0500548 bool outputCInitList) {
549 return new SPIRVProducerPass(out, descriptor_map_entries, samplerMap,
alan-baker00e7a582019-06-07 12:54:21 -0400550 outputCInitList);
David Neto22f144c2017-06-12 14:26:21 -0400551}
David Netoc2c368d2017-06-30 16:50:17 -0400552} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400553
554bool SPIRVProducerPass::runOnModule(Module &module) {
David Neto0676e6f2017-07-11 18:47:44 -0400555 binaryOut = outputCInitList ? &binaryTempOut : &out;
556
Alan Bakerfcda9482018-10-02 17:09:59 -0400557 PopulateUBOTypeMaps(module);
558
David Neto22f144c2017-06-12 14:26:21 -0400559 // SPIR-V always begins with its header information
560 outputHeader();
561
David Netoc6f3ab22018-04-06 18:02:31 -0400562 const DataLayout &DL = module.getDataLayout();
563
David Neto22f144c2017-06-12 14:26:21 -0400564 // Gather information from the LLVM IR that we require.
David Netoc6f3ab22018-04-06 18:02:31 -0400565 GenerateLLVMIRInfo(module, DL);
David Neto22f144c2017-06-12 14:26:21 -0400566
David Neto22f144c2017-06-12 14:26:21 -0400567 // Collect information on global variables too.
568 for (GlobalVariable &GV : module.globals()) {
569 // If the GV is one of our special __spirv_* variables, remove the
570 // initializer as it was only placed there to force LLVM to not throw the
571 // value away.
572 if (GV.getName().startswith("__spirv_")) {
573 GV.setInitializer(nullptr);
574 }
575
576 // Collect types' information from global variable.
577 FindTypePerGlobalVar(GV);
578
579 // Collect constant information from global variable.
580 FindConstantPerGlobalVar(GV);
581
582 // If the variable is an input, entry points need to know about it.
583 if (AddressSpace::Input == GV.getType()->getPointerAddressSpace()) {
David Netofb9a7972017-08-25 17:08:24 -0400584 getEntryPointInterfacesVec().insert(&GV);
David Neto22f144c2017-06-12 14:26:21 -0400585 }
586 }
587
588 // If there are extended instructions, generate OpExtInstImport.
589 if (FindExtInst(module)) {
590 GenerateExtInstImport();
591 }
592
593 // Generate SPIRV instructions for types.
Alan Bakerfcda9482018-10-02 17:09:59 -0400594 GenerateSPIRVTypes(module.getContext(), module);
David Neto22f144c2017-06-12 14:26:21 -0400595
596 // Generate SPIRV constants.
597 GenerateSPIRVConstants();
598
599 // If we have a sampler map, we might have literal samplers to generate.
600 if (0 < getSamplerMap().size()) {
601 GenerateSamplers(module);
602 }
603
604 // Generate SPIRV variables.
605 for (GlobalVariable &GV : module.globals()) {
606 GenerateGlobalVar(GV);
607 }
David Neto862b7d82018-06-14 18:48:37 -0400608 GenerateResourceVars(module);
David Netoc6f3ab22018-04-06 18:02:31 -0400609 GenerateWorkgroupVars();
David Neto22f144c2017-06-12 14:26:21 -0400610
611 // Generate SPIRV instructions for each function.
612 for (Function &F : module) {
613 if (F.isDeclaration()) {
614 continue;
615 }
616
David Neto862b7d82018-06-14 18:48:37 -0400617 GenerateDescriptorMapInfo(DL, F);
618
David Neto22f144c2017-06-12 14:26:21 -0400619 // Generate Function Prologue.
620 GenerateFuncPrologue(F);
621
622 // Generate SPIRV instructions for function body.
623 GenerateFuncBody(F);
624
625 // Generate Function Epilogue.
626 GenerateFuncEpilogue();
627 }
628
629 HandleDeferredInstruction();
David Neto1a1a0582017-07-07 12:01:44 -0400630 HandleDeferredDecorations(DL);
David Neto22f144c2017-06-12 14:26:21 -0400631
632 // Generate SPIRV module information.
David Neto5c22a252018-03-15 16:07:41 -0400633 GenerateModuleInfo(module);
David Neto22f144c2017-06-12 14:26:21 -0400634
alan-baker00e7a582019-06-07 12:54:21 -0400635 WriteSPIRVBinary();
David Neto22f144c2017-06-12 14:26:21 -0400636
637 // We need to patch the SPIR-V header to set bound correctly.
638 patchHeader();
David Neto0676e6f2017-07-11 18:47:44 -0400639
640 if (outputCInitList) {
641 bool first = true;
David Neto0676e6f2017-07-11 18:47:44 -0400642 std::ostringstream os;
643
David Neto57fb0b92017-08-04 15:35:09 -0400644 auto emit_word = [&os, &first](uint32_t word) {
David Neto0676e6f2017-07-11 18:47:44 -0400645 if (!first)
David Neto57fb0b92017-08-04 15:35:09 -0400646 os << ",\n";
647 os << word;
David Neto0676e6f2017-07-11 18:47:44 -0400648 first = false;
649 };
650
651 os << "{";
David Neto57fb0b92017-08-04 15:35:09 -0400652 const std::string str(binaryTempOut.str());
653 for (unsigned i = 0; i < str.size(); i += 4) {
654 const uint32_t a = static_cast<unsigned char>(str[i]);
655 const uint32_t b = static_cast<unsigned char>(str[i + 1]);
656 const uint32_t c = static_cast<unsigned char>(str[i + 2]);
657 const uint32_t d = static_cast<unsigned char>(str[i + 3]);
658 emit_word(a | (b << 8) | (c << 16) | (d << 24));
David Neto0676e6f2017-07-11 18:47:44 -0400659 }
660 os << "}\n";
661 out << os.str();
662 }
663
David Neto22f144c2017-06-12 14:26:21 -0400664 return false;
665}
666
667void SPIRVProducerPass::outputHeader() {
alan-baker00e7a582019-06-07 12:54:21 -0400668 binaryOut->write(reinterpret_cast<const char *>(&spv::MagicNumber),
669 sizeof(spv::MagicNumber));
670 binaryOut->write(reinterpret_cast<const char *>(&spv::Version),
671 sizeof(spv::Version));
David Neto22f144c2017-06-12 14:26:21 -0400672
alan-baker0c18ab02019-06-12 10:23:21 -0400673 // use Google's vendor ID
674 const uint32_t vendor = 21 << 16;
alan-baker00e7a582019-06-07 12:54:21 -0400675 binaryOut->write(reinterpret_cast<const char *>(&vendor), sizeof(vendor));
David Neto22f144c2017-06-12 14:26:21 -0400676
alan-baker00e7a582019-06-07 12:54:21 -0400677 // we record where we need to come back to and patch in the bound value
678 patchBoundOffset = binaryOut->tell();
David Neto22f144c2017-06-12 14:26:21 -0400679
alan-baker00e7a582019-06-07 12:54:21 -0400680 // output a bad bound for now
681 binaryOut->write(reinterpret_cast<const char *>(&nextID), sizeof(nextID));
David Neto22f144c2017-06-12 14:26:21 -0400682
alan-baker00e7a582019-06-07 12:54:21 -0400683 // output the schema (reserved for use and must be 0)
684 const uint32_t schema = 0;
685 binaryOut->write(reinterpret_cast<const char *>(&schema), sizeof(schema));
David Neto22f144c2017-06-12 14:26:21 -0400686}
687
688void SPIRVProducerPass::patchHeader() {
alan-baker00e7a582019-06-07 12:54:21 -0400689 // for a binary we just write the value of nextID over bound
690 binaryOut->pwrite(reinterpret_cast<char *>(&nextID), sizeof(nextID),
691 patchBoundOffset);
David Neto22f144c2017-06-12 14:26:21 -0400692}
693
David Netoc6f3ab22018-04-06 18:02:31 -0400694void SPIRVProducerPass::GenerateLLVMIRInfo(Module &M, const DataLayout &DL) {
David Neto22f144c2017-06-12 14:26:21 -0400695 // This function generates LLVM IR for function such as global variable for
696 // argument, constant and pointer type for argument access. These information
697 // is artificial one because we need Vulkan SPIR-V output. This function is
698 // executed ahead of FindType and FindConstant.
David Neto22f144c2017-06-12 14:26:21 -0400699 LLVMContext &Context = M.getContext();
700
David Neto862b7d82018-06-14 18:48:37 -0400701 FindGlobalConstVars(M, DL);
David Neto5c22a252018-03-15 16:07:41 -0400702
David Neto862b7d82018-06-14 18:48:37 -0400703 FindResourceVars(M, DL);
David Neto22f144c2017-06-12 14:26:21 -0400704
705 bool HasWorkGroupBuiltin = false;
706 for (GlobalVariable &GV : M.globals()) {
707 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
708 if (spv::BuiltInWorkgroupSize == BuiltinType) {
709 HasWorkGroupBuiltin = true;
710 }
711 }
712
David Neto862b7d82018-06-14 18:48:37 -0400713 FindTypesForSamplerMap(M);
714 FindTypesForResourceVars(M);
Alan Baker202c8c72018-08-13 13:47:44 -0400715 FindWorkgroupVars(M);
David Neto22f144c2017-06-12 14:26:21 -0400716
David Neto862b7d82018-06-14 18:48:37 -0400717 // These function calls need a <2 x i32> as an intermediate result but not
718 // the final result.
719 std::unordered_set<std::string> NeedsIVec2{
720 "_Z15get_image_width14ocl_image2d_ro",
721 "_Z15get_image_width14ocl_image2d_wo",
722 "_Z16get_image_height14ocl_image2d_ro",
723 "_Z16get_image_height14ocl_image2d_wo",
724 };
725
David Neto22f144c2017-06-12 14:26:21 -0400726 for (Function &F : M) {
Kévin Petitabef4522019-03-27 13:08:01 +0000727 if (F.isDeclaration()) {
David Neto22f144c2017-06-12 14:26:21 -0400728 continue;
729 }
730
731 for (BasicBlock &BB : F) {
732 for (Instruction &I : BB) {
733 if (I.getOpcode() == Instruction::ZExt ||
734 I.getOpcode() == Instruction::SExt ||
735 I.getOpcode() == Instruction::UIToFP) {
736 // If there is zext with i1 type, it will be changed to OpSelect. The
737 // OpSelect needs constant 0 and 1 so the constants are added here.
738
739 auto OpTy = I.getOperand(0)->getType();
740
Kévin Petit24272b62018-10-18 19:16:12 +0000741 if (OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -0400742 if (I.getOpcode() == Instruction::ZExt) {
David Neto22f144c2017-06-12 14:26:21 -0400743 FindConstant(Constant::getNullValue(I.getType()));
Kévin Petit7bfb8992019-02-26 13:45:08 +0000744 FindConstant(ConstantInt::get(I.getType(), 1));
David Neto22f144c2017-06-12 14:26:21 -0400745 } else if (I.getOpcode() == Instruction::SExt) {
David Neto22f144c2017-06-12 14:26:21 -0400746 FindConstant(Constant::getNullValue(I.getType()));
Kévin Petit7bfb8992019-02-26 13:45:08 +0000747 FindConstant(ConstantInt::getSigned(I.getType(), -1));
David Neto22f144c2017-06-12 14:26:21 -0400748 } else {
749 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
750 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
751 }
752 }
753 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
David Neto862b7d82018-06-14 18:48:37 -0400754 StringRef callee_name = Call->getCalledFunction()->getName();
David Neto22f144c2017-06-12 14:26:21 -0400755
756 // Handle image type specially.
David Neto862b7d82018-06-14 18:48:37 -0400757 if (callee_name.equals(
David Neto22f144c2017-06-12 14:26:21 -0400758 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
David Neto862b7d82018-06-14 18:48:37 -0400759 callee_name.equals(
David Neto22f144c2017-06-12 14:26:21 -0400760 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
761 TypeMapType &OpImageTypeMap = getImageTypeMap();
762 Type *ImageTy =
763 Call->getArgOperand(0)->getType()->getPointerElementType();
764 OpImageTypeMap[ImageTy] = 0;
765
766 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
767 }
David Neto5c22a252018-03-15 16:07:41 -0400768
David Neto862b7d82018-06-14 18:48:37 -0400769 if (NeedsIVec2.find(callee_name) != NeedsIVec2.end()) {
David Neto5c22a252018-03-15 16:07:41 -0400770 FindType(VectorType::get(Type::getInt32Ty(Context), 2));
771 }
David Neto22f144c2017-06-12 14:26:21 -0400772 }
773 }
774 }
775
Kévin Petitabef4522019-03-27 13:08:01 +0000776 // More things to do on kernel functions
777 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
778 if (const MDNode *MD =
779 dyn_cast<Function>(&F)->getMetadata("reqd_work_group_size")) {
780 // We generate constants if the WorkgroupSize builtin is being used.
781 if (HasWorkGroupBuiltin) {
782 // Collect constant information for work group size.
783 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(0)));
784 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(1)));
785 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(2)));
David Neto22f144c2017-06-12 14:26:21 -0400786 }
787 }
788 }
789
790 if (M.getTypeByName("opencl.image2d_ro_t") ||
791 M.getTypeByName("opencl.image2d_wo_t") ||
792 M.getTypeByName("opencl.image3d_ro_t") ||
793 M.getTypeByName("opencl.image3d_wo_t")) {
794 // Assume Image type's sampled type is float type.
795 FindType(Type::getFloatTy(Context));
796 }
797
798 // Collect types' information from function.
799 FindTypePerFunc(F);
800
801 // Collect constant information from function.
802 FindConstantPerFunc(F);
803 }
804}
805
David Neto862b7d82018-06-14 18:48:37 -0400806void SPIRVProducerPass::FindGlobalConstVars(Module &M, const DataLayout &DL) {
alan-baker56f7aff2019-05-22 08:06:42 -0400807 clspv::NormalizeGlobalVariables(M);
808
David Neto862b7d82018-06-14 18:48:37 -0400809 SmallVector<GlobalVariable *, 8> GVList;
810 SmallVector<GlobalVariable *, 8> DeadGVList;
811 for (GlobalVariable &GV : M.globals()) {
812 if (GV.getType()->getAddressSpace() == AddressSpace::Constant) {
813 if (GV.use_empty()) {
814 DeadGVList.push_back(&GV);
815 } else {
816 GVList.push_back(&GV);
817 }
818 }
819 }
820
821 // Remove dead global __constant variables.
822 for (auto GV : DeadGVList) {
823 GV->eraseFromParent();
824 }
825 DeadGVList.clear();
826
827 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
828 // For now, we only support a single storage buffer.
829 if (GVList.size() > 0) {
830 assert(GVList.size() == 1);
831 const auto *GV = GVList[0];
832 const auto constants_byte_size =
Alan Bakerfcda9482018-10-02 17:09:59 -0400833 (GetTypeSizeInBits(GV->getInitializer()->getType(), DL)) / 8;
David Neto862b7d82018-06-14 18:48:37 -0400834 const size_t kConstantMaxSize = 65536;
835 if (constants_byte_size > kConstantMaxSize) {
836 outs() << "Max __constant capacity of " << kConstantMaxSize
837 << " bytes exceeded: " << constants_byte_size << " bytes used\n";
838 llvm_unreachable("Max __constant capacity exceeded");
839 }
840 }
841 } else {
842 // Change global constant variable's address space to ModuleScopePrivate.
843 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
844 for (auto GV : GVList) {
845 // Create new gv with ModuleScopePrivate address space.
846 Type *NewGVTy = GV->getType()->getPointerElementType();
847 GlobalVariable *NewGV = new GlobalVariable(
848 M, NewGVTy, false, GV->getLinkage(), GV->getInitializer(), "",
849 nullptr, GV->getThreadLocalMode(), AddressSpace::ModuleScopePrivate);
850 NewGV->takeName(GV);
851
852 const SmallVector<User *, 8> GVUsers(GV->user_begin(), GV->user_end());
853 SmallVector<User *, 8> CandidateUsers;
854
855 auto record_called_function_type_as_user =
856 [&GlobalConstFuncTyMap](Value *gv, CallInst *call) {
857 // Find argument index.
858 unsigned index = 0;
859 for (unsigned i = 0; i < call->getNumArgOperands(); i++) {
860 if (gv == call->getOperand(i)) {
861 // TODO(dneto): Should we break here?
862 index = i;
863 }
864 }
865
866 // Record function type with global constant.
867 GlobalConstFuncTyMap[call->getFunctionType()] =
868 std::make_pair(call->getFunctionType(), index);
869 };
870
871 for (User *GVU : GVUsers) {
872 if (CallInst *Call = dyn_cast<CallInst>(GVU)) {
873 record_called_function_type_as_user(GV, Call);
874 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(GVU)) {
875 // Check GEP users.
876 for (User *GEPU : GEP->users()) {
877 if (CallInst *GEPCall = dyn_cast<CallInst>(GEPU)) {
878 record_called_function_type_as_user(GEP, GEPCall);
879 }
880 }
881 }
882
883 CandidateUsers.push_back(GVU);
884 }
885
886 for (User *U : CandidateUsers) {
887 // Update users of gv with new gv.
alan-bakered80f572019-02-11 17:28:26 -0500888 if (!isa<Constant>(U)) {
889 // #254: Can't change operands of a constant, but this shouldn't be
890 // something that sticks around in the module.
891 U->replaceUsesOfWith(GV, NewGV);
892 }
David Neto862b7d82018-06-14 18:48:37 -0400893 }
894
895 // Delete original gv.
896 GV->eraseFromParent();
897 }
898 }
899}
900
Radek Szymanskibe4b0c42018-10-04 22:20:53 +0100901void SPIRVProducerPass::FindResourceVars(Module &M, const DataLayout &) {
David Neto862b7d82018-06-14 18:48:37 -0400902 ResourceVarInfoList.clear();
903 FunctionToResourceVarsMap.clear();
904 ModuleOrderedResourceVars.reset();
905 // Normally, there is one resource variable per clspv.resource.var.*
906 // function, since that is unique'd by arg type and index. By design,
907 // we can share these resource variables across kernels because all
908 // kernels use the same descriptor set.
909 //
910 // But if the user requested distinct descriptor sets per kernel, then
911 // the descriptor allocator has made different (set,binding) pairs for
912 // the same (type,arg_index) pair. Since we can decorate a resource
913 // variable with only exactly one DescriptorSet and Binding, we are
914 // forced in this case to make distinct resource variables whenever
915 // the same clspv.reource.var.X function is seen with disintct
916 // (set,binding) values.
917 const bool always_distinct_sets =
918 clspv::Option::DistinctKernelDescriptorSets();
919 for (Function &F : M) {
920 // Rely on the fact the resource var functions have a stable ordering
921 // in the module.
Alan Baker202c8c72018-08-13 13:47:44 -0400922 if (F.getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -0400923 // Find all calls to this function with distinct set and binding pairs.
924 // Save them in ResourceVarInfoList.
925
926 // Determine uniqueness of the (set,binding) pairs only withing this
927 // one resource-var builtin function.
928 using SetAndBinding = std::pair<unsigned, unsigned>;
929 // Maps set and binding to the resource var info.
930 DenseMap<SetAndBinding, ResourceVarInfo *> set_and_binding_map;
931 bool first_use = true;
932 for (auto &U : F.uses()) {
933 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
934 const auto set = unsigned(
935 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
936 const auto binding = unsigned(
937 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
938 const auto arg_kind = clspv::ArgKind(
939 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
940 const auto arg_index = unsigned(
941 dyn_cast<ConstantInt>(call->getArgOperand(3))->getZExtValue());
alan-bakere9308012019-03-15 10:25:13 -0400942 const auto coherent = unsigned(
943 dyn_cast<ConstantInt>(call->getArgOperand(5))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -0400944
945 // Find or make the resource var info for this combination.
946 ResourceVarInfo *rv = nullptr;
947 if (always_distinct_sets) {
948 // Make a new resource var any time we see a different
949 // (set,binding) pair.
950 SetAndBinding key{set, binding};
951 auto where = set_and_binding_map.find(key);
952 if (where == set_and_binding_map.end()) {
953 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
alan-bakere9308012019-03-15 10:25:13 -0400954 binding, &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -0400955 ResourceVarInfoList.emplace_back(rv);
956 set_and_binding_map[key] = rv;
957 } else {
958 rv = where->second;
959 }
960 } else {
961 // The default is to make exactly one resource for each
962 // clspv.resource.var.* function.
963 if (first_use) {
964 first_use = false;
965 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
alan-bakere9308012019-03-15 10:25:13 -0400966 binding, &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -0400967 ResourceVarInfoList.emplace_back(rv);
968 } else {
969 rv = ResourceVarInfoList.back().get();
970 }
971 }
972
973 // Now populate FunctionToResourceVarsMap.
974 auto &mapping =
975 FunctionToResourceVarsMap[call->getParent()->getParent()];
976 while (mapping.size() <= arg_index) {
977 mapping.push_back(nullptr);
978 }
979 mapping[arg_index] = rv;
980 }
981 }
982 }
983 }
984
985 // Populate ModuleOrderedResourceVars.
986 for (Function &F : M) {
987 auto where = FunctionToResourceVarsMap.find(&F);
988 if (where != FunctionToResourceVarsMap.end()) {
989 for (auto &rv : where->second) {
990 if (rv != nullptr) {
991 ModuleOrderedResourceVars.insert(rv);
992 }
993 }
994 }
995 }
996 if (ShowResourceVars) {
997 for (auto *info : ModuleOrderedResourceVars) {
998 outs() << "MORV index " << info->index << " (" << info->descriptor_set
999 << "," << info->binding << ") " << *(info->var_fn->getReturnType())
1000 << "\n";
1001 }
1002 }
1003}
1004
David Neto22f144c2017-06-12 14:26:21 -04001005bool SPIRVProducerPass::FindExtInst(Module &M) {
1006 LLVMContext &Context = M.getContext();
1007 bool HasExtInst = false;
1008
1009 for (Function &F : M) {
1010 for (BasicBlock &BB : F) {
1011 for (Instruction &I : BB) {
1012 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1013 Function *Callee = Call->getCalledFunction();
1014 // Check whether this call is for extend instructions.
David Neto3fbb4072017-10-16 11:28:14 -04001015 auto callee_name = Callee->getName();
1016 const glsl::ExtInst EInst = getExtInstEnum(callee_name);
1017 const glsl::ExtInst IndirectEInst =
1018 getIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04001019
David Neto3fbb4072017-10-16 11:28:14 -04001020 HasExtInst |=
1021 (EInst != kGlslExtInstBad) || (IndirectEInst != kGlslExtInstBad);
1022
1023 if (IndirectEInst) {
1024 // Register extra constants if needed.
1025
1026 // Registers a type and constant for computing the result of the
1027 // given instruction. If the result of the instruction is a vector,
1028 // then make a splat vector constant with the same number of
1029 // elements.
1030 auto register_constant = [this, &I](Constant *constant) {
1031 FindType(constant->getType());
1032 FindConstant(constant);
1033 if (auto *vectorTy = dyn_cast<VectorType>(I.getType())) {
1034 // Register the splat vector of the value with the same
1035 // width as the result of the instruction.
1036 auto *vec_constant = ConstantVector::getSplat(
1037 static_cast<unsigned>(vectorTy->getNumElements()),
1038 constant);
1039 FindConstant(vec_constant);
1040 FindType(vec_constant->getType());
1041 }
1042 };
1043 switch (IndirectEInst) {
1044 case glsl::ExtInstFindUMsb:
1045 // clz needs OpExtInst and OpISub with constant 31, or splat
1046 // vector of 31. Add it to the constant list here.
1047 register_constant(
1048 ConstantInt::get(Type::getInt32Ty(Context), 31));
1049 break;
1050 case glsl::ExtInstAcos:
1051 case glsl::ExtInstAsin:
Kévin Petiteb9f90a2018-09-29 12:29:34 +01001052 case glsl::ExtInstAtan:
David Neto3fbb4072017-10-16 11:28:14 -04001053 case glsl::ExtInstAtan2:
1054 // We need 1/pi for acospi, asinpi, atan2pi.
1055 register_constant(
1056 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
1057 break;
1058 default:
1059 assert(false && "internally inconsistent");
1060 }
David Neto22f144c2017-06-12 14:26:21 -04001061 }
1062 }
1063 }
1064 }
1065 }
1066
1067 return HasExtInst;
1068}
1069
1070void SPIRVProducerPass::FindTypePerGlobalVar(GlobalVariable &GV) {
1071 // Investigate global variable's type.
1072 FindType(GV.getType());
1073}
1074
1075void SPIRVProducerPass::FindTypePerFunc(Function &F) {
1076 // Investigate function's type.
1077 FunctionType *FTy = F.getFunctionType();
1078
1079 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
1080 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
David Neto9ed8e2f2018-03-24 06:47:24 -07001081 // Handle a regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04001082 if (GlobalConstFuncTyMap.count(FTy)) {
1083 uint32_t GVCstArgIdx = GlobalConstFuncTypeMap[FTy].second;
1084 SmallVector<Type *, 4> NewFuncParamTys;
1085 for (unsigned i = 0; i < FTy->getNumParams(); i++) {
1086 Type *ParamTy = FTy->getParamType(i);
1087 if (i == GVCstArgIdx) {
1088 Type *EleTy = ParamTy->getPointerElementType();
1089 ParamTy = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1090 }
1091
1092 NewFuncParamTys.push_back(ParamTy);
1093 }
1094
1095 FunctionType *NewFTy =
1096 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1097 GlobalConstFuncTyMap[FTy] = std::make_pair(NewFTy, GVCstArgIdx);
1098 FTy = NewFTy;
1099 }
1100
1101 FindType(FTy);
1102 } else {
1103 // As kernel functions do not have parameters, create new function type and
1104 // add it to type map.
1105 SmallVector<Type *, 4> NewFuncParamTys;
1106 FunctionType *NewFTy =
1107 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1108 FindType(NewFTy);
1109 }
1110
1111 // Investigate instructions' type in function body.
1112 for (BasicBlock &BB : F) {
1113 for (Instruction &I : BB) {
1114 if (isa<ShuffleVectorInst>(I)) {
1115 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1116 // Ignore type for mask of shuffle vector instruction.
1117 if (i == 2) {
1118 continue;
1119 }
1120
1121 Value *Op = I.getOperand(i);
1122 if (!isa<MetadataAsValue>(Op)) {
1123 FindType(Op->getType());
1124 }
1125 }
1126
1127 FindType(I.getType());
1128 continue;
1129 }
1130
David Neto862b7d82018-06-14 18:48:37 -04001131 CallInst *Call = dyn_cast<CallInst>(&I);
1132
1133 if (Call && Call->getCalledFunction()->getName().startswith(
Alan Baker202c8c72018-08-13 13:47:44 -04001134 clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001135 // This is a fake call representing access to a resource variable.
1136 // We handle that elsewhere.
1137 continue;
1138 }
1139
Alan Baker202c8c72018-08-13 13:47:44 -04001140 if (Call && Call->getCalledFunction()->getName().startswith(
1141 clspv::WorkgroupAccessorFunction())) {
1142 // This is a fake call representing access to a workgroup variable.
1143 // We handle that elsewhere.
1144 continue;
1145 }
1146
David Neto22f144c2017-06-12 14:26:21 -04001147 // Work through the operands of the instruction.
1148 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1149 Value *const Op = I.getOperand(i);
1150 // If any of the operands is a constant, find the type!
1151 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1152 FindType(Op->getType());
1153 }
1154 }
1155
1156 for (Use &Op : I.operands()) {
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001157 if (isa<CallInst>(&I)) {
David Neto22f144c2017-06-12 14:26:21 -04001158 // Avoid to check call instruction's type.
1159 break;
1160 }
Alan Baker202c8c72018-08-13 13:47:44 -04001161 if (CallInst *OpCall = dyn_cast<CallInst>(Op)) {
1162 if (OpCall && OpCall->getCalledFunction()->getName().startswith(
1163 clspv::WorkgroupAccessorFunction())) {
1164 // This is a fake call representing access to a workgroup variable.
1165 // We handle that elsewhere.
1166 continue;
1167 }
1168 }
David Neto22f144c2017-06-12 14:26:21 -04001169 if (!isa<MetadataAsValue>(&Op)) {
1170 FindType(Op->getType());
1171 continue;
1172 }
1173 }
1174
David Neto22f144c2017-06-12 14:26:21 -04001175 // We don't want to track the type of this call as we are going to replace
1176 // it.
Kévin Petitdf71de32019-04-09 14:09:50 +01001177 if (Call && (clspv::LiteralSamplerFunction() ==
David Neto22f144c2017-06-12 14:26:21 -04001178 Call->getCalledFunction()->getName())) {
1179 continue;
1180 }
1181
1182 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1183 // If gep's base operand has ModuleScopePrivate address space, make gep
1184 // return ModuleScopePrivate address space.
1185 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate) {
1186 // Add pointer type with private address space for global constant to
1187 // type list.
1188 Type *EleTy = I.getType()->getPointerElementType();
1189 Type *NewPTy =
1190 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1191
1192 FindType(NewPTy);
1193 continue;
1194 }
1195 }
1196
1197 FindType(I.getType());
1198 }
1199 }
1200}
1201
David Neto862b7d82018-06-14 18:48:37 -04001202void SPIRVProducerPass::FindTypesForSamplerMap(Module &M) {
1203 // If we are using a sampler map, find the type of the sampler.
Kévin Petitdf71de32019-04-09 14:09:50 +01001204 if (M.getFunction(clspv::LiteralSamplerFunction()) ||
David Neto862b7d82018-06-14 18:48:37 -04001205 0 < getSamplerMap().size()) {
1206 auto SamplerStructTy = M.getTypeByName("opencl.sampler_t");
1207 if (!SamplerStructTy) {
1208 SamplerStructTy = StructType::create(M.getContext(), "opencl.sampler_t");
1209 }
1210
1211 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
1212
1213 FindType(SamplerTy);
1214 }
1215}
1216
1217void SPIRVProducerPass::FindTypesForResourceVars(Module &M) {
1218 // Record types so they are generated.
1219 TypesNeedingLayout.reset();
1220 StructTypesNeedingBlock.reset();
1221
1222 // To match older clspv codegen, generate the float type first if required
1223 // for images.
1224 for (const auto *info : ModuleOrderedResourceVars) {
1225 if (info->arg_kind == clspv::ArgKind::ReadOnlyImage ||
1226 info->arg_kind == clspv::ArgKind::WriteOnlyImage) {
1227 // We need "float" for the sampled component type.
1228 FindType(Type::getFloatTy(M.getContext()));
1229 // We only need to find it once.
1230 break;
1231 }
1232 }
1233
1234 for (const auto *info : ModuleOrderedResourceVars) {
1235 Type *type = info->var_fn->getReturnType();
1236
1237 switch (info->arg_kind) {
1238 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04001239 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04001240 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1241 StructTypesNeedingBlock.insert(sty);
1242 } else {
1243 errs() << *type << "\n";
1244 llvm_unreachable("Buffer arguments must map to structures!");
1245 }
1246 break;
1247 case clspv::ArgKind::Pod:
1248 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1249 StructTypesNeedingBlock.insert(sty);
1250 } else {
1251 errs() << *type << "\n";
1252 llvm_unreachable("POD arguments must map to structures!");
1253 }
1254 break;
1255 case clspv::ArgKind::ReadOnlyImage:
1256 case clspv::ArgKind::WriteOnlyImage:
1257 case clspv::ArgKind::Sampler:
1258 // Sampler and image types map to the pointee type but
1259 // in the uniform constant address space.
1260 type = PointerType::get(type->getPointerElementType(),
1261 clspv::AddressSpace::UniformConstant);
1262 break;
1263 default:
1264 break;
1265 }
1266
1267 // The converted type is the type of the OpVariable we will generate.
1268 // If the pointee type is an array of size zero, FindType will convert it
1269 // to a runtime array.
1270 FindType(type);
1271 }
1272
1273 // Traverse the arrays and structures underneath each Block, and
1274 // mark them as needing layout.
1275 std::vector<Type *> work_list(StructTypesNeedingBlock.begin(),
1276 StructTypesNeedingBlock.end());
1277 while (!work_list.empty()) {
1278 Type *type = work_list.back();
1279 work_list.pop_back();
1280 TypesNeedingLayout.insert(type);
1281 switch (type->getTypeID()) {
1282 case Type::ArrayTyID:
1283 work_list.push_back(type->getArrayElementType());
1284 if (!Hack_generate_runtime_array_stride_early) {
1285 // Remember this array type for deferred decoration.
1286 TypesNeedingArrayStride.insert(type);
1287 }
1288 break;
1289 case Type::StructTyID:
1290 for (auto *elem_ty : cast<StructType>(type)->elements()) {
1291 work_list.push_back(elem_ty);
1292 }
1293 default:
1294 // This type and its contained types don't get layout.
1295 break;
1296 }
1297 }
1298}
1299
Alan Baker202c8c72018-08-13 13:47:44 -04001300void SPIRVProducerPass::FindWorkgroupVars(Module &M) {
1301 // The SpecId assignment for pointer-to-local arguments is recorded in
1302 // module-level metadata. Translate that information into local argument
1303 // information.
1304 NamedMDNode *nmd = M.getNamedMetadata(clspv::LocalSpecIdMetadataName());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001305 if (!nmd)
1306 return;
Alan Baker202c8c72018-08-13 13:47:44 -04001307 for (auto operand : nmd->operands()) {
1308 MDTuple *tuple = cast<MDTuple>(operand);
1309 ValueAsMetadata *fn_md = cast<ValueAsMetadata>(tuple->getOperand(0));
1310 Function *func = cast<Function>(fn_md->getValue());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001311 ConstantAsMetadata *arg_index_md =
1312 cast<ConstantAsMetadata>(tuple->getOperand(1));
1313 int arg_index = static_cast<int>(
1314 cast<ConstantInt>(arg_index_md->getValue())->getSExtValue());
1315 Argument *arg = &*(func->arg_begin() + arg_index);
Alan Baker202c8c72018-08-13 13:47:44 -04001316
1317 ConstantAsMetadata *spec_id_md =
1318 cast<ConstantAsMetadata>(tuple->getOperand(2));
alan-bakerb6b09dc2018-11-08 16:59:28 -05001319 int spec_id = static_cast<int>(
1320 cast<ConstantInt>(spec_id_md->getValue())->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04001321
1322 max_local_spec_id_ = std::max(max_local_spec_id_, spec_id + 1);
1323 LocalArgSpecIds[arg] = spec_id;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001324 if (LocalSpecIdInfoMap.count(spec_id))
1325 continue;
Alan Baker202c8c72018-08-13 13:47:44 -04001326
1327 // We haven't seen this SpecId yet, so generate the LocalArgInfo for it.
1328 LocalArgInfo info{nextID, arg->getType()->getPointerElementType(),
1329 nextID + 1, nextID + 2,
1330 nextID + 3, spec_id};
1331 LocalSpecIdInfoMap[spec_id] = info;
1332 nextID += 4;
1333
1334 // Ensure the types necessary for this argument get generated.
1335 Type *IdxTy = Type::getInt32Ty(M.getContext());
1336 FindConstant(ConstantInt::get(IdxTy, 0));
1337 FindType(IdxTy);
1338 FindType(arg->getType());
1339 }
1340}
1341
David Neto22f144c2017-06-12 14:26:21 -04001342void SPIRVProducerPass::FindType(Type *Ty) {
1343 TypeList &TyList = getTypeList();
1344
1345 if (0 != TyList.idFor(Ty)) {
1346 return;
1347 }
1348
1349 if (Ty->isPointerTy()) {
1350 auto AddrSpace = Ty->getPointerAddressSpace();
1351 if ((AddressSpace::Constant == AddrSpace) ||
1352 (AddressSpace::Global == AddrSpace)) {
1353 auto PointeeTy = Ty->getPointerElementType();
1354
1355 if (PointeeTy->isStructTy() &&
1356 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1357 FindType(PointeeTy);
1358 auto ActualPointerTy =
1359 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1360 FindType(ActualPointerTy);
1361 return;
1362 }
1363 }
1364 }
1365
David Neto862b7d82018-06-14 18:48:37 -04001366 // By convention, LLVM array type with 0 elements will map to
1367 // OpTypeRuntimeArray. Otherwise, it will map to OpTypeArray, which
1368 // has a constant number of elements. We need to support type of the
1369 // constant.
1370 if (auto *arrayTy = dyn_cast<ArrayType>(Ty)) {
1371 if (arrayTy->getNumElements() > 0) {
1372 LLVMContext &Context = Ty->getContext();
1373 FindType(Type::getInt32Ty(Context));
1374 }
David Neto22f144c2017-06-12 14:26:21 -04001375 }
1376
1377 for (Type *SubTy : Ty->subtypes()) {
1378 FindType(SubTy);
1379 }
1380
1381 TyList.insert(Ty);
1382}
1383
1384void SPIRVProducerPass::FindConstantPerGlobalVar(GlobalVariable &GV) {
1385 // If the global variable has a (non undef) initializer.
1386 if (GV.hasInitializer() && !isa<UndefValue>(GV.getInitializer())) {
David Neto862b7d82018-06-14 18:48:37 -04001387 // Generate the constant if it's not the initializer to a module scope
1388 // constant that we will expect in a storage buffer.
1389 const bool module_scope_constant_external_init =
1390 (GV.getType()->getPointerAddressSpace() == AddressSpace::Constant) &&
1391 clspv::Option::ModuleConstantsInStorageBuffer();
1392 if (!module_scope_constant_external_init) {
1393 FindConstant(GV.getInitializer());
1394 }
David Neto22f144c2017-06-12 14:26:21 -04001395 }
1396}
1397
1398void SPIRVProducerPass::FindConstantPerFunc(Function &F) {
1399 // Investigate constants in function body.
1400 for (BasicBlock &BB : F) {
1401 for (Instruction &I : BB) {
David Neto862b7d82018-06-14 18:48:37 -04001402 if (auto *call = dyn_cast<CallInst>(&I)) {
1403 auto name = call->getCalledFunction()->getName();
Kévin Petitdf71de32019-04-09 14:09:50 +01001404 if (name == clspv::LiteralSamplerFunction()) {
David Neto862b7d82018-06-14 18:48:37 -04001405 // We've handled these constants elsewhere, so skip it.
1406 continue;
1407 }
Alan Baker202c8c72018-08-13 13:47:44 -04001408 if (name.startswith(clspv::ResourceAccessorFunction())) {
1409 continue;
1410 }
1411 if (name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001412 continue;
1413 }
Kévin Petit617a76d2019-04-04 13:54:16 +01001414 if (name.startswith(clspv::SPIRVOpIntrinsicFunction())) {
1415 // Skip the first operand that has the SPIR-V Opcode
1416 for (unsigned i = 1; i < I.getNumOperands(); i++) {
1417 if (isa<Constant>(I.getOperand(i)) &&
1418 !isa<GlobalValue>(I.getOperand(i))) {
1419 FindConstant(I.getOperand(i));
1420 }
1421 }
1422 continue;
1423 }
David Neto22f144c2017-06-12 14:26:21 -04001424 }
1425
1426 if (isa<AllocaInst>(I)) {
1427 // Alloca instruction has constant for the number of element. Ignore it.
1428 continue;
1429 } else if (isa<ShuffleVectorInst>(I)) {
1430 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1431 // Ignore constant for mask of shuffle vector instruction.
1432 if (i == 2) {
1433 continue;
1434 }
1435
1436 if (isa<Constant>(I.getOperand(i)) &&
1437 !isa<GlobalValue>(I.getOperand(i))) {
1438 FindConstant(I.getOperand(i));
1439 }
1440 }
1441
1442 continue;
1443 } else if (isa<InsertElementInst>(I)) {
1444 // Handle InsertElement with <4 x i8> specially.
1445 Type *CompositeTy = I.getOperand(0)->getType();
1446 if (is4xi8vec(CompositeTy)) {
1447 LLVMContext &Context = CompositeTy->getContext();
1448 if (isa<Constant>(I.getOperand(0))) {
1449 FindConstant(I.getOperand(0));
1450 }
1451
1452 if (isa<Constant>(I.getOperand(1))) {
1453 FindConstant(I.getOperand(1));
1454 }
1455
1456 // Add mask constant 0xFF.
1457 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1458 FindConstant(CstFF);
1459
1460 // Add shift amount constant.
1461 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
1462 uint64_t Idx = CI->getZExtValue();
1463 Constant *CstShiftAmount =
1464 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1465 FindConstant(CstShiftAmount);
1466 }
1467
1468 continue;
1469 }
1470
1471 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1472 // Ignore constant for index of InsertElement instruction.
1473 if (i == 2) {
1474 continue;
1475 }
1476
1477 if (isa<Constant>(I.getOperand(i)) &&
1478 !isa<GlobalValue>(I.getOperand(i))) {
1479 FindConstant(I.getOperand(i));
1480 }
1481 }
1482
1483 continue;
1484 } else if (isa<ExtractElementInst>(I)) {
1485 // Handle ExtractElement with <4 x i8> specially.
1486 Type *CompositeTy = I.getOperand(0)->getType();
1487 if (is4xi8vec(CompositeTy)) {
1488 LLVMContext &Context = CompositeTy->getContext();
1489 if (isa<Constant>(I.getOperand(0))) {
1490 FindConstant(I.getOperand(0));
1491 }
1492
1493 // Add mask constant 0xFF.
1494 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1495 FindConstant(CstFF);
1496
1497 // Add shift amount constant.
1498 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1499 uint64_t Idx = CI->getZExtValue();
1500 Constant *CstShiftAmount =
1501 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1502 FindConstant(CstShiftAmount);
1503 } else {
1504 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
1505 FindConstant(Cst8);
1506 }
1507
1508 continue;
1509 }
1510
1511 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1512 // Ignore constant for index of ExtractElement instruction.
1513 if (i == 1) {
1514 continue;
1515 }
1516
1517 if (isa<Constant>(I.getOperand(i)) &&
1518 !isa<GlobalValue>(I.getOperand(i))) {
1519 FindConstant(I.getOperand(i));
1520 }
1521 }
1522
1523 continue;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001524 } else if ((Instruction::Xor == I.getOpcode()) &&
1525 I.getType()->isIntegerTy(1)) {
1526 // We special case for Xor where the type is i1 and one of the arguments
1527 // is a constant 1 (true), this is an OpLogicalNot in SPIR-V, and we
1528 // don't need the constant
David Neto22f144c2017-06-12 14:26:21 -04001529 bool foundConstantTrue = false;
1530 for (Use &Op : I.operands()) {
1531 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1532 auto CI = cast<ConstantInt>(Op);
1533
1534 if (CI->isZero() || foundConstantTrue) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05001535 // If we already found the true constant, we might (probably only
1536 // on -O0) have an OpLogicalNot which is taking a constant
1537 // argument, so discover it anyway.
David Neto22f144c2017-06-12 14:26:21 -04001538 FindConstant(Op);
1539 } else {
1540 foundConstantTrue = true;
1541 }
1542 }
1543 }
1544
1545 continue;
David Netod2de94a2017-08-28 17:27:47 -04001546 } else if (isa<TruncInst>(I)) {
alan-bakerb39c8262019-03-08 14:03:37 -05001547 // Special case if i8 is not generally handled.
1548 if (!clspv::Option::Int8Support()) {
1549 // For truncation to i8 we mask against 255.
1550 Type *ToTy = I.getType();
1551 if (8u == ToTy->getPrimitiveSizeInBits()) {
1552 LLVMContext &Context = ToTy->getContext();
1553 Constant *Cst255 =
1554 ConstantInt::get(Type::getInt32Ty(Context), 0xff);
1555 FindConstant(Cst255);
1556 }
David Netod2de94a2017-08-28 17:27:47 -04001557 }
Neil Henning39672102017-09-29 14:33:13 +01001558 } else if (isa<AtomicRMWInst>(I)) {
1559 LLVMContext &Context = I.getContext();
1560
1561 FindConstant(
1562 ConstantInt::get(Type::getInt32Ty(Context), spv::ScopeDevice));
1563 FindConstant(ConstantInt::get(
1564 Type::getInt32Ty(Context),
1565 spv::MemorySemanticsUniformMemoryMask |
1566 spv::MemorySemanticsSequentiallyConsistentMask));
David Neto22f144c2017-06-12 14:26:21 -04001567 }
1568
1569 for (Use &Op : I.operands()) {
1570 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1571 FindConstant(Op);
1572 }
1573 }
1574 }
1575 }
1576}
1577
1578void SPIRVProducerPass::FindConstant(Value *V) {
David Neto22f144c2017-06-12 14:26:21 -04001579 ValueList &CstList = getConstantList();
1580
David Netofb9a7972017-08-25 17:08:24 -04001581 // If V is already tracked, ignore it.
1582 if (0 != CstList.idFor(V)) {
David Neto22f144c2017-06-12 14:26:21 -04001583 return;
1584 }
1585
David Neto862b7d82018-06-14 18:48:37 -04001586 if (isa<GlobalValue>(V) && clspv::Option::ModuleConstantsInStorageBuffer()) {
1587 return;
1588 }
1589
David Neto22f144c2017-06-12 14:26:21 -04001590 Constant *Cst = cast<Constant>(V);
David Neto862b7d82018-06-14 18:48:37 -04001591 Type *CstTy = Cst->getType();
David Neto22f144c2017-06-12 14:26:21 -04001592
1593 // Handle constant with <4 x i8> type specially.
David Neto22f144c2017-06-12 14:26:21 -04001594 if (is4xi8vec(CstTy)) {
1595 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001596 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001597 }
1598 }
1599
1600 if (Cst->getNumOperands()) {
1601 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end(); I != E;
1602 ++I) {
1603 FindConstant(*I);
1604 }
1605
David Netofb9a7972017-08-25 17:08:24 -04001606 CstList.insert(Cst);
David Neto22f144c2017-06-12 14:26:21 -04001607 return;
1608 } else if (const ConstantDataSequential *CDS =
1609 dyn_cast<ConstantDataSequential>(Cst)) {
1610 // Add constants for each element to constant list.
1611 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
1612 Constant *EleCst = CDS->getElementAsConstant(i);
1613 FindConstant(EleCst);
1614 }
1615 }
1616
1617 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001618 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001619 }
1620}
1621
1622spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1623 switch (AddrSpace) {
1624 default:
1625 llvm_unreachable("Unsupported OpenCL address space");
1626 case AddressSpace::Private:
1627 return spv::StorageClassFunction;
1628 case AddressSpace::Global:
David Neto22f144c2017-06-12 14:26:21 -04001629 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001630 case AddressSpace::Constant:
1631 return clspv::Option::ConstantArgsInUniformBuffer()
1632 ? spv::StorageClassUniform
1633 : spv::StorageClassStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -04001634 case AddressSpace::Input:
1635 return spv::StorageClassInput;
1636 case AddressSpace::Local:
1637 return spv::StorageClassWorkgroup;
1638 case AddressSpace::UniformConstant:
1639 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001640 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001641 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001642 case AddressSpace::ModuleScopePrivate:
1643 return spv::StorageClassPrivate;
1644 }
1645}
1646
David Neto862b7d82018-06-14 18:48:37 -04001647spv::StorageClass
1648SPIRVProducerPass::GetStorageClassForArgKind(clspv::ArgKind arg_kind) const {
1649 switch (arg_kind) {
1650 case clspv::ArgKind::Buffer:
1651 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001652 case clspv::ArgKind::BufferUBO:
1653 return spv::StorageClassUniform;
David Neto862b7d82018-06-14 18:48:37 -04001654 case clspv::ArgKind::Pod:
1655 return clspv::Option::PodArgsInUniformBuffer()
1656 ? spv::StorageClassUniform
1657 : spv::StorageClassStorageBuffer;
1658 case clspv::ArgKind::Local:
1659 return spv::StorageClassWorkgroup;
1660 case clspv::ArgKind::ReadOnlyImage:
1661 case clspv::ArgKind::WriteOnlyImage:
1662 case clspv::ArgKind::Sampler:
1663 return spv::StorageClassUniformConstant;
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001664 default:
1665 llvm_unreachable("Unsupported storage class for argument kind");
David Neto862b7d82018-06-14 18:48:37 -04001666 }
1667}
1668
David Neto22f144c2017-06-12 14:26:21 -04001669spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1670 return StringSwitch<spv::BuiltIn>(Name)
1671 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1672 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1673 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1674 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1675 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
1676 .Default(spv::BuiltInMax);
1677}
1678
1679void SPIRVProducerPass::GenerateExtInstImport() {
1680 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1681 uint32_t &ExtInstImportID = getOpExtInstImportID();
1682
1683 //
1684 // Generate OpExtInstImport.
1685 //
1686 // Ops[0] ... Ops[n] = Name (Literal String)
David Neto22f144c2017-06-12 14:26:21 -04001687 ExtInstImportID = nextID;
David Neto87846742018-04-11 17:36:22 -04001688 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpExtInstImport, nextID++,
1689 MkString("GLSL.std.450")));
David Neto22f144c2017-06-12 14:26:21 -04001690}
1691
alan-bakerb6b09dc2018-11-08 16:59:28 -05001692void SPIRVProducerPass::GenerateSPIRVTypes(LLVMContext &Context,
1693 Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04001694 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1695 ValueMapType &VMap = getValueMap();
1696 ValueMapType &AllocatedVMap = getAllocatedValueMap();
Alan Bakerfcda9482018-10-02 17:09:59 -04001697 const auto &DL = module.getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04001698
1699 // Map for OpTypeRuntimeArray. If argument has pointer type, 2 spirv type
1700 // instructions are generated. They are OpTypePointer and OpTypeRuntimeArray.
1701 DenseMap<Type *, uint32_t> OpRuntimeTyMap;
1702
1703 for (Type *Ty : getTypeList()) {
1704 // Update TypeMap with nextID for reference later.
1705 TypeMap[Ty] = nextID;
1706
1707 switch (Ty->getTypeID()) {
1708 default: {
1709 Ty->print(errs());
1710 llvm_unreachable("Unsupported type???");
1711 break;
1712 }
1713 case Type::MetadataTyID:
1714 case Type::LabelTyID: {
1715 // Ignore these types.
1716 break;
1717 }
1718 case Type::PointerTyID: {
1719 PointerType *PTy = cast<PointerType>(Ty);
1720 unsigned AddrSpace = PTy->getAddressSpace();
1721
1722 // For the purposes of our Vulkan SPIR-V type system, constant and global
1723 // are conflated.
1724 bool UseExistingOpTypePointer = false;
1725 if (AddressSpace::Constant == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001726 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1727 AddrSpace = AddressSpace::Global;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001728 // Check to see if we already created this type (for instance, if we
1729 // had a constant <type>* and a global <type>*, the type would be
1730 // created by one of these types, and shared by both).
Alan Bakerfcda9482018-10-02 17:09:59 -04001731 auto GlobalTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1732 if (0 < TypeMap.count(GlobalTy)) {
1733 TypeMap[PTy] = TypeMap[GlobalTy];
1734 UseExistingOpTypePointer = true;
1735 break;
1736 }
David Neto22f144c2017-06-12 14:26:21 -04001737 }
1738 } else if (AddressSpace::Global == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001739 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1740 AddrSpace = AddressSpace::Constant;
David Neto22f144c2017-06-12 14:26:21 -04001741
alan-bakerb6b09dc2018-11-08 16:59:28 -05001742 // Check to see if we already created this type (for instance, if we
1743 // had a constant <type>* and a global <type>*, the type would be
1744 // created by one of these types, and shared by both).
1745 auto ConstantTy =
1746 PTy->getPointerElementType()->getPointerTo(AddrSpace);
Alan Bakerfcda9482018-10-02 17:09:59 -04001747 if (0 < TypeMap.count(ConstantTy)) {
1748 TypeMap[PTy] = TypeMap[ConstantTy];
1749 UseExistingOpTypePointer = true;
1750 }
David Neto22f144c2017-06-12 14:26:21 -04001751 }
1752 }
1753
David Neto862b7d82018-06-14 18:48:37 -04001754 const bool HasArgUser = true;
David Neto22f144c2017-06-12 14:26:21 -04001755
David Neto862b7d82018-06-14 18:48:37 -04001756 if (HasArgUser && !UseExistingOpTypePointer) {
David Neto22f144c2017-06-12 14:26:21 -04001757 //
1758 // Generate OpTypePointer.
1759 //
1760
1761 // OpTypePointer
1762 // Ops[0] = Storage Class
1763 // Ops[1] = Element Type ID
1764 SPIRVOperandList Ops;
1765
David Neto257c3892018-04-11 13:19:45 -04001766 Ops << MkNum(GetStorageClass(AddrSpace))
1767 << MkId(lookupType(PTy->getElementType()));
David Neto22f144c2017-06-12 14:26:21 -04001768
David Neto87846742018-04-11 17:36:22 -04001769 auto *Inst = new SPIRVInstruction(spv::OpTypePointer, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001770 SPIRVInstList.push_back(Inst);
1771 }
David Neto22f144c2017-06-12 14:26:21 -04001772 break;
1773 }
1774 case Type::StructTyID: {
David Neto22f144c2017-06-12 14:26:21 -04001775 StructType *STy = cast<StructType>(Ty);
1776
1777 // Handle sampler type.
1778 if (STy->isOpaque()) {
1779 if (STy->getName().equals("opencl.sampler_t")) {
1780 //
1781 // Generate OpTypeSampler
1782 //
1783 // Empty Ops.
1784 SPIRVOperandList Ops;
1785
David Neto87846742018-04-11 17:36:22 -04001786 auto *Inst = new SPIRVInstruction(spv::OpTypeSampler, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001787 SPIRVInstList.push_back(Inst);
1788 break;
1789 } else if (STy->getName().equals("opencl.image2d_ro_t") ||
1790 STy->getName().equals("opencl.image2d_wo_t") ||
1791 STy->getName().equals("opencl.image3d_ro_t") ||
1792 STy->getName().equals("opencl.image3d_wo_t")) {
1793 //
1794 // Generate OpTypeImage
1795 //
1796 // Ops[0] = Sampled Type ID
1797 // Ops[1] = Dim ID
1798 // Ops[2] = Depth (Literal Number)
1799 // Ops[3] = Arrayed (Literal Number)
1800 // Ops[4] = MS (Literal Number)
1801 // Ops[5] = Sampled (Literal Number)
1802 // Ops[6] = Image Format ID
1803 //
1804 SPIRVOperandList Ops;
1805
1806 // TODO: Changed Sampled Type according to situations.
1807 uint32_t SampledTyID = lookupType(Type::getFloatTy(Context));
David Neto257c3892018-04-11 13:19:45 -04001808 Ops << MkId(SampledTyID);
David Neto22f144c2017-06-12 14:26:21 -04001809
1810 spv::Dim DimID = spv::Dim2D;
1811 if (STy->getName().equals("opencl.image3d_ro_t") ||
1812 STy->getName().equals("opencl.image3d_wo_t")) {
1813 DimID = spv::Dim3D;
1814 }
David Neto257c3892018-04-11 13:19:45 -04001815 Ops << MkNum(DimID);
David Neto22f144c2017-06-12 14:26:21 -04001816
1817 // TODO: Set up Depth.
David Neto257c3892018-04-11 13:19:45 -04001818 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001819
1820 // TODO: Set up Arrayed.
David Neto257c3892018-04-11 13:19:45 -04001821 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001822
1823 // TODO: Set up MS.
David Neto257c3892018-04-11 13:19:45 -04001824 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001825
1826 // TODO: Set up Sampled.
1827 //
1828 // From Spec
1829 //
1830 // 0 indicates this is only known at run time, not at compile time
1831 // 1 indicates will be used with sampler
1832 // 2 indicates will be used without a sampler (a storage image)
1833 uint32_t Sampled = 1;
1834 if (STy->getName().equals("opencl.image2d_wo_t") ||
1835 STy->getName().equals("opencl.image3d_wo_t")) {
1836 Sampled = 2;
1837 }
David Neto257c3892018-04-11 13:19:45 -04001838 Ops << MkNum(Sampled);
David Neto22f144c2017-06-12 14:26:21 -04001839
1840 // TODO: Set up Image Format.
David Neto257c3892018-04-11 13:19:45 -04001841 Ops << MkNum(spv::ImageFormatUnknown);
David Neto22f144c2017-06-12 14:26:21 -04001842
David Neto87846742018-04-11 17:36:22 -04001843 auto *Inst = new SPIRVInstruction(spv::OpTypeImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001844 SPIRVInstList.push_back(Inst);
1845 break;
1846 }
1847 }
1848
1849 //
1850 // Generate OpTypeStruct
1851 //
1852 // Ops[0] ... Ops[n] = Member IDs
1853 SPIRVOperandList Ops;
1854
1855 for (auto *EleTy : STy->elements()) {
David Neto862b7d82018-06-14 18:48:37 -04001856 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04001857 }
1858
David Neto22f144c2017-06-12 14:26:21 -04001859 uint32_t STyID = nextID;
1860
alan-bakerb6b09dc2018-11-08 16:59:28 -05001861 auto *Inst = new SPIRVInstruction(spv::OpTypeStruct, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001862 SPIRVInstList.push_back(Inst);
1863
1864 // Generate OpMemberDecorate.
1865 auto DecoInsertPoint =
1866 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
1867 [](SPIRVInstruction *Inst) -> bool {
1868 return Inst->getOpcode() != spv::OpDecorate &&
1869 Inst->getOpcode() != spv::OpMemberDecorate &&
1870 Inst->getOpcode() != spv::OpExtInstImport;
1871 });
1872
David Netoc463b372017-08-10 15:32:21 -04001873 const auto StructLayout = DL.getStructLayout(STy);
Alan Bakerfcda9482018-10-02 17:09:59 -04001874 // Search for the correct offsets if this type was remapped.
1875 std::vector<uint32_t> *offsets = nullptr;
1876 auto iter = RemappedUBOTypeOffsets.find(STy);
1877 if (iter != RemappedUBOTypeOffsets.end()) {
1878 offsets = &iter->second;
1879 }
David Netoc463b372017-08-10 15:32:21 -04001880
David Neto862b7d82018-06-14 18:48:37 -04001881 // #error TODO(dneto): Only do this if in TypesNeedingLayout.
David Neto22f144c2017-06-12 14:26:21 -04001882 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
1883 MemberIdx++) {
1884 // Ops[0] = Structure Type ID
1885 // Ops[1] = Member Index(Literal Number)
1886 // Ops[2] = Decoration (Offset)
1887 // Ops[3] = Byte Offset (Literal Number)
1888 Ops.clear();
1889
David Neto257c3892018-04-11 13:19:45 -04001890 Ops << MkId(STyID) << MkNum(MemberIdx) << MkNum(spv::DecorationOffset);
David Neto22f144c2017-06-12 14:26:21 -04001891
alan-bakerb6b09dc2018-11-08 16:59:28 -05001892 auto ByteOffset =
1893 static_cast<uint32_t>(StructLayout->getElementOffset(MemberIdx));
Alan Bakerfcda9482018-10-02 17:09:59 -04001894 if (offsets) {
1895 ByteOffset = (*offsets)[MemberIdx];
1896 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05001897 // const auto ByteOffset =
Alan Bakerfcda9482018-10-02 17:09:59 -04001898 // uint32_t(StructLayout->getElementOffset(MemberIdx));
David Neto257c3892018-04-11 13:19:45 -04001899 Ops << MkNum(ByteOffset);
David Neto22f144c2017-06-12 14:26:21 -04001900
David Neto87846742018-04-11 17:36:22 -04001901 auto *DecoInst = new SPIRVInstruction(spv::OpMemberDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001902 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04001903 }
1904
1905 // Generate OpDecorate.
David Neto862b7d82018-06-14 18:48:37 -04001906 if (StructTypesNeedingBlock.idFor(STy)) {
1907 Ops.clear();
1908 // Use Block decorations with StorageBuffer storage class.
1909 Ops << MkId(STyID) << MkNum(spv::DecorationBlock);
David Neto22f144c2017-06-12 14:26:21 -04001910
David Neto862b7d82018-06-14 18:48:37 -04001911 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
1912 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04001913 }
1914 break;
1915 }
1916 case Type::IntegerTyID: {
1917 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
1918
1919 if (BitWidth == 1) {
David Neto87846742018-04-11 17:36:22 -04001920 auto *Inst = new SPIRVInstruction(spv::OpTypeBool, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04001921 SPIRVInstList.push_back(Inst);
1922 } else {
alan-bakerb39c8262019-03-08 14:03:37 -05001923 if (!clspv::Option::Int8Support()) {
1924 // i8 is added to TypeMap as i32.
1925 // No matter what LLVM type is requested first, always alias the
1926 // second one's SPIR-V type to be the same as the one we generated
1927 // first.
1928 unsigned aliasToWidth = 0;
1929 if (BitWidth == 8) {
1930 aliasToWidth = 32;
1931 BitWidth = 32;
1932 } else if (BitWidth == 32) {
1933 aliasToWidth = 8;
1934 }
1935 if (aliasToWidth) {
1936 Type *otherType = Type::getIntNTy(Ty->getContext(), aliasToWidth);
1937 auto where = TypeMap.find(otherType);
1938 if (where == TypeMap.end()) {
1939 // Go ahead and make it, but also map the other type to it.
1940 TypeMap[otherType] = nextID;
1941 } else {
1942 // Alias this SPIR-V type the existing type.
1943 TypeMap[Ty] = where->second;
1944 break;
1945 }
David Neto391aeb12017-08-26 15:51:58 -04001946 }
David Neto22f144c2017-06-12 14:26:21 -04001947 }
1948
David Neto257c3892018-04-11 13:19:45 -04001949 SPIRVOperandList Ops;
1950 Ops << MkNum(BitWidth) << MkNum(0 /* not signed */);
David Neto22f144c2017-06-12 14:26:21 -04001951
1952 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04001953 new SPIRVInstruction(spv::OpTypeInt, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04001954 }
1955 break;
1956 }
1957 case Type::HalfTyID:
1958 case Type::FloatTyID:
1959 case Type::DoubleTyID: {
1960 SPIRVOperand *WidthOp = new SPIRVOperand(
1961 SPIRVOperandType::LITERAL_INTEGER, Ty->getPrimitiveSizeInBits());
1962
1963 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04001964 new SPIRVInstruction(spv::OpTypeFloat, nextID++, WidthOp));
David Neto22f144c2017-06-12 14:26:21 -04001965 break;
1966 }
1967 case Type::ArrayTyID: {
David Neto22f144c2017-06-12 14:26:21 -04001968 ArrayType *ArrTy = cast<ArrayType>(Ty);
David Neto862b7d82018-06-14 18:48:37 -04001969 const uint64_t Length = ArrTy->getArrayNumElements();
1970 if (Length == 0) {
1971 // By convention, map it to a RuntimeArray.
David Neto22f144c2017-06-12 14:26:21 -04001972
David Neto862b7d82018-06-14 18:48:37 -04001973 // Only generate the type once.
1974 // TODO(dneto): Can it ever be generated more than once?
1975 // Doesn't LLVM type uniqueness guarantee we'll only see this
1976 // once?
1977 Type *EleTy = ArrTy->getArrayElementType();
1978 if (OpRuntimeTyMap.count(EleTy) == 0) {
1979 uint32_t OpTypeRuntimeArrayID = nextID;
1980 OpRuntimeTyMap[Ty] = nextID;
David Neto22f144c2017-06-12 14:26:21 -04001981
David Neto862b7d82018-06-14 18:48:37 -04001982 //
1983 // Generate OpTypeRuntimeArray.
1984 //
David Neto22f144c2017-06-12 14:26:21 -04001985
David Neto862b7d82018-06-14 18:48:37 -04001986 // OpTypeRuntimeArray
1987 // Ops[0] = Element Type ID
1988 SPIRVOperandList Ops;
1989 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04001990
David Neto862b7d82018-06-14 18:48:37 -04001991 SPIRVInstList.push_back(
1992 new SPIRVInstruction(spv::OpTypeRuntimeArray, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04001993
David Neto862b7d82018-06-14 18:48:37 -04001994 if (Hack_generate_runtime_array_stride_early) {
1995 // Generate OpDecorate.
1996 auto DecoInsertPoint = std::find_if(
1997 SPIRVInstList.begin(), SPIRVInstList.end(),
1998 [](SPIRVInstruction *Inst) -> bool {
1999 return Inst->getOpcode() != spv::OpDecorate &&
2000 Inst->getOpcode() != spv::OpMemberDecorate &&
2001 Inst->getOpcode() != spv::OpExtInstImport;
2002 });
David Neto22f144c2017-06-12 14:26:21 -04002003
David Neto862b7d82018-06-14 18:48:37 -04002004 // Ops[0] = Target ID
2005 // Ops[1] = Decoration (ArrayStride)
2006 // Ops[2] = Stride Number(Literal Number)
2007 Ops.clear();
David Neto85082642018-03-24 06:55:20 -07002008
David Neto862b7d82018-06-14 18:48:37 -04002009 Ops << MkId(OpTypeRuntimeArrayID)
2010 << MkNum(spv::DecorationArrayStride)
Alan Bakerfcda9482018-10-02 17:09:59 -04002011 << MkNum(static_cast<uint32_t>(GetTypeAllocSize(EleTy, DL)));
David Neto22f144c2017-06-12 14:26:21 -04002012
David Neto862b7d82018-06-14 18:48:37 -04002013 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
2014 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
2015 }
2016 }
David Neto22f144c2017-06-12 14:26:21 -04002017
David Neto862b7d82018-06-14 18:48:37 -04002018 } else {
David Neto22f144c2017-06-12 14:26:21 -04002019
David Neto862b7d82018-06-14 18:48:37 -04002020 //
2021 // Generate OpConstant and OpTypeArray.
2022 //
2023
2024 //
2025 // Generate OpConstant for array length.
2026 //
2027 // Ops[0] = Result Type ID
2028 // Ops[1] .. Ops[n] = Values LiteralNumber
2029 SPIRVOperandList Ops;
2030
2031 Type *LengthTy = Type::getInt32Ty(Context);
2032 uint32_t ResTyID = lookupType(LengthTy);
2033 Ops << MkId(ResTyID);
2034
2035 assert(Length < UINT32_MAX);
2036 Ops << MkNum(static_cast<uint32_t>(Length));
2037
2038 // Add constant for length to constant list.
2039 Constant *CstLength = ConstantInt::get(LengthTy, Length);
2040 AllocatedVMap[CstLength] = nextID;
2041 VMap[CstLength] = nextID;
2042 uint32_t LengthID = nextID;
2043
2044 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
2045 SPIRVInstList.push_back(CstInst);
2046
2047 // Remember to generate ArrayStride later
2048 getTypesNeedingArrayStride().insert(Ty);
2049
2050 //
2051 // Generate OpTypeArray.
2052 //
2053 // Ops[0] = Element Type ID
2054 // Ops[1] = Array Length Constant ID
2055 Ops.clear();
2056
2057 uint32_t EleTyID = lookupType(ArrTy->getElementType());
2058 Ops << MkId(EleTyID) << MkId(LengthID);
2059
2060 // Update TypeMap with nextID.
2061 TypeMap[Ty] = nextID;
2062
2063 auto *ArrayInst = new SPIRVInstruction(spv::OpTypeArray, nextID++, Ops);
2064 SPIRVInstList.push_back(ArrayInst);
2065 }
David Neto22f144c2017-06-12 14:26:21 -04002066 break;
2067 }
2068 case Type::VectorTyID: {
alan-bakerb39c8262019-03-08 14:03:37 -05002069 // <4 x i8> is changed to i32 if i8 is not generally supported.
2070 if (!clspv::Option::Int8Support() &&
2071 Ty->getVectorElementType() == Type::getInt8Ty(Context)) {
David Neto22f144c2017-06-12 14:26:21 -04002072 if (Ty->getVectorNumElements() == 4) {
2073 TypeMap[Ty] = lookupType(Ty->getVectorElementType());
2074 break;
2075 } else {
2076 Ty->print(errs());
2077 llvm_unreachable("Support above i8 vector type");
2078 }
2079 }
2080
2081 // Ops[0] = Component Type ID
2082 // Ops[1] = Component Count (Literal Number)
David Neto257c3892018-04-11 13:19:45 -04002083 SPIRVOperandList Ops;
2084 Ops << MkId(lookupType(Ty->getVectorElementType()))
2085 << MkNum(Ty->getVectorNumElements());
David Neto22f144c2017-06-12 14:26:21 -04002086
alan-bakerb6b09dc2018-11-08 16:59:28 -05002087 SPIRVInstruction *inst =
2088 new SPIRVInstruction(spv::OpTypeVector, nextID++, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002089 SPIRVInstList.push_back(inst);
David Neto22f144c2017-06-12 14:26:21 -04002090 break;
2091 }
2092 case Type::VoidTyID: {
David Neto87846742018-04-11 17:36:22 -04002093 auto *Inst = new SPIRVInstruction(spv::OpTypeVoid, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04002094 SPIRVInstList.push_back(Inst);
2095 break;
2096 }
2097 case Type::FunctionTyID: {
2098 // Generate SPIRV instruction for function type.
2099 FunctionType *FTy = cast<FunctionType>(Ty);
2100
2101 // Ops[0] = Return Type ID
2102 // Ops[1] ... Ops[n] = Parameter Type IDs
2103 SPIRVOperandList Ops;
2104
2105 // Find SPIRV instruction for return type
David Netoc6f3ab22018-04-06 18:02:31 -04002106 Ops << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04002107
2108 // Find SPIRV instructions for parameter types
2109 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
2110 // Find SPIRV instruction for parameter type.
2111 auto ParamTy = FTy->getParamType(k);
2112 if (ParamTy->isPointerTy()) {
2113 auto PointeeTy = ParamTy->getPointerElementType();
2114 if (PointeeTy->isStructTy() &&
2115 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
2116 ParamTy = PointeeTy;
2117 }
2118 }
2119
David Netoc6f3ab22018-04-06 18:02:31 -04002120 Ops << MkId(lookupType(ParamTy));
David Neto22f144c2017-06-12 14:26:21 -04002121 }
2122
David Neto87846742018-04-11 17:36:22 -04002123 auto *Inst = new SPIRVInstruction(spv::OpTypeFunction, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002124 SPIRVInstList.push_back(Inst);
2125 break;
2126 }
2127 }
2128 }
2129
2130 // Generate OpTypeSampledImage.
2131 TypeMapType &OpImageTypeMap = getImageTypeMap();
2132 for (auto &ImageType : OpImageTypeMap) {
2133 //
2134 // Generate OpTypeSampledImage.
2135 //
2136 // Ops[0] = Image Type ID
2137 //
2138 SPIRVOperandList Ops;
2139
2140 Type *ImgTy = ImageType.first;
David Netoc6f3ab22018-04-06 18:02:31 -04002141 Ops << MkId(TypeMap[ImgTy]);
David Neto22f144c2017-06-12 14:26:21 -04002142
2143 // Update OpImageTypeMap.
2144 ImageType.second = nextID;
2145
David Neto87846742018-04-11 17:36:22 -04002146 auto *Inst = new SPIRVInstruction(spv::OpTypeSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002147 SPIRVInstList.push_back(Inst);
2148 }
David Netoc6f3ab22018-04-06 18:02:31 -04002149
2150 // Generate types for pointer-to-local arguments.
Alan Baker202c8c72018-08-13 13:47:44 -04002151 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2152 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002153 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002154
2155 // Generate the spec constant.
2156 SPIRVOperandList Ops;
2157 Ops << MkId(lookupType(Type::getInt32Ty(Context))) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04002158 SPIRVInstList.push_back(
2159 new SPIRVInstruction(spv::OpSpecConstant, arg_info.array_size_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002160
2161 // Generate the array type.
2162 Ops.clear();
2163 // The element type must have been created.
2164 uint32_t elem_ty_id = lookupType(arg_info.elem_type);
2165 assert(elem_ty_id);
2166 Ops << MkId(elem_ty_id) << MkId(arg_info.array_size_id);
2167
2168 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002169 new SPIRVInstruction(spv::OpTypeArray, arg_info.array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002170
2171 Ops.clear();
2172 Ops << MkNum(spv::StorageClassWorkgroup) << MkId(arg_info.array_type_id);
David Neto87846742018-04-11 17:36:22 -04002173 SPIRVInstList.push_back(new SPIRVInstruction(
2174 spv::OpTypePointer, arg_info.ptr_array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002175 }
David Neto22f144c2017-06-12 14:26:21 -04002176}
2177
2178void SPIRVProducerPass::GenerateSPIRVConstants() {
2179 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2180 ValueMapType &VMap = getValueMap();
2181 ValueMapType &AllocatedVMap = getAllocatedValueMap();
2182 ValueList &CstList = getConstantList();
David Neto482550a2018-03-24 05:21:07 -07002183 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04002184
2185 for (uint32_t i = 0; i < CstList.size(); i++) {
David Netofb9a7972017-08-25 17:08:24 -04002186 // UniqueVector ids are 1-based.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002187 Constant *Cst = cast<Constant>(CstList[i + 1]);
David Neto22f144c2017-06-12 14:26:21 -04002188
2189 // OpTypeArray's constant was already generated.
David Netofb9a7972017-08-25 17:08:24 -04002190 if (AllocatedVMap.find_as(Cst) != AllocatedVMap.end()) {
David Neto22f144c2017-06-12 14:26:21 -04002191 continue;
2192 }
2193
David Netofb9a7972017-08-25 17:08:24 -04002194 // Set ValueMap with nextID for reference later.
David Neto22f144c2017-06-12 14:26:21 -04002195 VMap[Cst] = nextID;
2196
2197 //
2198 // Generate OpConstant.
2199 //
2200
2201 // Ops[0] = Result Type ID
2202 // Ops[1] .. Ops[n] = Values LiteralNumber
2203 SPIRVOperandList Ops;
2204
David Neto257c3892018-04-11 13:19:45 -04002205 Ops << MkId(lookupType(Cst->getType()));
David Neto22f144c2017-06-12 14:26:21 -04002206
2207 std::vector<uint32_t> LiteralNum;
David Neto22f144c2017-06-12 14:26:21 -04002208 spv::Op Opcode = spv::OpNop;
2209
2210 if (isa<UndefValue>(Cst)) {
2211 // Ops[0] = Result Type ID
David Netoc66b3352017-10-20 14:28:46 -04002212 Opcode = spv::OpUndef;
Alan Baker9bf93fb2018-08-28 16:59:26 -04002213 if (hack_undef && IsTypeNullable(Cst->getType())) {
2214 Opcode = spv::OpConstantNull;
David Netoc66b3352017-10-20 14:28:46 -04002215 }
David Neto22f144c2017-06-12 14:26:21 -04002216 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
2217 unsigned BitWidth = CI->getBitWidth();
2218 if (BitWidth == 1) {
2219 // If the bitwidth of constant is 1, generate OpConstantTrue or
2220 // OpConstantFalse.
2221 if (CI->getZExtValue()) {
2222 // Ops[0] = Result Type ID
2223 Opcode = spv::OpConstantTrue;
2224 } else {
2225 // Ops[0] = Result Type ID
2226 Opcode = spv::OpConstantFalse;
2227 }
David Neto22f144c2017-06-12 14:26:21 -04002228 } else {
2229 auto V = CI->getZExtValue();
2230 LiteralNum.push_back(V & 0xFFFFFFFF);
2231
2232 if (BitWidth > 32) {
2233 LiteralNum.push_back(V >> 32);
2234 }
2235
2236 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002237
David Neto257c3892018-04-11 13:19:45 -04002238 Ops << MkInteger(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002239 }
2240 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2241 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2242 Type *CFPTy = CFP->getType();
2243 if (CFPTy->isFloatTy()) {
2244 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
Kévin Petit02ee34e2019-04-04 19:03:22 +01002245 } else if (CFPTy->isDoubleTy()) {
2246 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2247 LiteralNum.push_back(FPVal >> 32);
David Neto22f144c2017-06-12 14:26:21 -04002248 } else {
2249 CFPTy->print(errs());
2250 llvm_unreachable("Implement this ConstantFP Type");
2251 }
2252
2253 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002254
David Neto257c3892018-04-11 13:19:45 -04002255 Ops << MkFloat(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002256 } else if (isa<ConstantDataSequential>(Cst) &&
2257 cast<ConstantDataSequential>(Cst)->isString()) {
2258 Cst->print(errs());
2259 llvm_unreachable("Implement this Constant");
2260
2261 } else if (const ConstantDataSequential *CDS =
2262 dyn_cast<ConstantDataSequential>(Cst)) {
David Neto49351ac2017-08-26 17:32:20 -04002263 // Let's convert <4 x i8> constant to int constant specially.
2264 // This case occurs when all the values are specified as constant
2265 // ints.
2266 Type *CstTy = Cst->getType();
2267 if (is4xi8vec(CstTy)) {
2268 LLVMContext &Context = CstTy->getContext();
2269
2270 //
2271 // Generate OpConstant with OpTypeInt 32 0.
2272 //
Neil Henning39672102017-09-29 14:33:13 +01002273 uint32_t IntValue = 0;
2274 for (unsigned k = 0; k < 4; k++) {
2275 const uint64_t Val = CDS->getElementAsInteger(k);
David Neto49351ac2017-08-26 17:32:20 -04002276 IntValue = (IntValue << 8) | (Val & 0xffu);
2277 }
2278
2279 Type *i32 = Type::getInt32Ty(Context);
2280 Constant *CstInt = ConstantInt::get(i32, IntValue);
2281 // If this constant is already registered on VMap, use it.
2282 if (VMap.count(CstInt)) {
2283 uint32_t CstID = VMap[CstInt];
2284 VMap[Cst] = CstID;
2285 continue;
2286 }
2287
David Neto257c3892018-04-11 13:19:45 -04002288 Ops << MkNum(IntValue);
David Neto49351ac2017-08-26 17:32:20 -04002289
David Neto87846742018-04-11 17:36:22 -04002290 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto49351ac2017-08-26 17:32:20 -04002291 SPIRVInstList.push_back(CstInst);
2292
2293 continue;
2294 }
2295
2296 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002297 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
2298 Constant *EleCst = CDS->getElementAsConstant(k);
2299 uint32_t EleCstID = VMap[EleCst];
David Neto257c3892018-04-11 13:19:45 -04002300 Ops << MkId(EleCstID);
David Neto22f144c2017-06-12 14:26:21 -04002301 }
2302
2303 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002304 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2305 // Let's convert <4 x i8> constant to int constant specially.
David Neto49351ac2017-08-26 17:32:20 -04002306 // This case occurs when at least one of the values is an undef.
David Neto22f144c2017-06-12 14:26:21 -04002307 Type *CstTy = Cst->getType();
2308 if (is4xi8vec(CstTy)) {
2309 LLVMContext &Context = CstTy->getContext();
2310
2311 //
2312 // Generate OpConstant with OpTypeInt 32 0.
2313 //
Neil Henning39672102017-09-29 14:33:13 +01002314 uint32_t IntValue = 0;
David Neto22f144c2017-06-12 14:26:21 -04002315 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2316 I != E; ++I) {
2317 uint64_t Val = 0;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002318 const Value *CV = *I;
Neil Henning39672102017-09-29 14:33:13 +01002319 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2320 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002321 }
David Neto49351ac2017-08-26 17:32:20 -04002322 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002323 }
2324
David Neto49351ac2017-08-26 17:32:20 -04002325 Type *i32 = Type::getInt32Ty(Context);
2326 Constant *CstInt = ConstantInt::get(i32, IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002327 // If this constant is already registered on VMap, use it.
2328 if (VMap.count(CstInt)) {
2329 uint32_t CstID = VMap[CstInt];
2330 VMap[Cst] = CstID;
David Neto19a1bad2017-08-25 15:01:41 -04002331 continue;
David Neto22f144c2017-06-12 14:26:21 -04002332 }
2333
David Neto257c3892018-04-11 13:19:45 -04002334 Ops << MkNum(IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002335
David Neto87846742018-04-11 17:36:22 -04002336 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002337 SPIRVInstList.push_back(CstInst);
2338
David Neto19a1bad2017-08-25 15:01:41 -04002339 continue;
David Neto22f144c2017-06-12 14:26:21 -04002340 }
2341
2342 // We use a constant composite in SPIR-V for our constant aggregate in
2343 // LLVM.
2344 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002345
2346 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
2347 // Look up the ID of the element of this aggregate (which we will
2348 // previously have created a constant for).
2349 uint32_t ElementConstantID = VMap[CA->getAggregateElement(k)];
2350
2351 // And add an operand to the composite we are constructing
David Neto257c3892018-04-11 13:19:45 -04002352 Ops << MkId(ElementConstantID);
David Neto22f144c2017-06-12 14:26:21 -04002353 }
2354 } else if (Cst->isNullValue()) {
2355 Opcode = spv::OpConstantNull;
David Neto22f144c2017-06-12 14:26:21 -04002356 } else {
2357 Cst->print(errs());
2358 llvm_unreachable("Unsupported Constant???");
2359 }
2360
alan-baker5b86ed72019-02-15 08:26:50 -05002361 if (Opcode == spv::OpConstantNull && Cst->getType()->isPointerTy()) {
2362 // Null pointer requires variable pointers.
2363 setVariablePointersCapabilities(Cst->getType()->getPointerAddressSpace());
2364 }
2365
David Neto87846742018-04-11 17:36:22 -04002366 auto *CstInst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002367 SPIRVInstList.push_back(CstInst);
2368 }
2369}
2370
2371void SPIRVProducerPass::GenerateSamplers(Module &M) {
2372 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto22f144c2017-06-12 14:26:21 -04002373
alan-bakerb6b09dc2018-11-08 16:59:28 -05002374 auto &sampler_map = getSamplerMap();
David Neto862b7d82018-06-14 18:48:37 -04002375 SamplerMapIndexToIDMap.clear();
David Neto22f144c2017-06-12 14:26:21 -04002376 DenseMap<unsigned, unsigned> SamplerLiteralToIDMap;
David Neto862b7d82018-06-14 18:48:37 -04002377 DenseMap<unsigned, unsigned> SamplerLiteralToDescriptorSetMap;
2378 DenseMap<unsigned, unsigned> SamplerLiteralToBindingMap;
David Neto22f144c2017-06-12 14:26:21 -04002379
David Neto862b7d82018-06-14 18:48:37 -04002380 // We might have samplers in the sampler map that are not used
2381 // in the translation unit. We need to allocate variables
2382 // for them and bindings too.
2383 DenseSet<unsigned> used_bindings;
David Neto22f144c2017-06-12 14:26:21 -04002384
Kévin Petitdf71de32019-04-09 14:09:50 +01002385 auto *var_fn = M.getFunction(clspv::LiteralSamplerFunction());
alan-bakerb6b09dc2018-11-08 16:59:28 -05002386 if (!var_fn)
2387 return;
David Neto862b7d82018-06-14 18:48:37 -04002388 for (auto user : var_fn->users()) {
2389 // Populate SamplerLiteralToDescriptorSetMap and
2390 // SamplerLiteralToBindingMap.
2391 //
2392 // Look for calls like
2393 // call %opencl.sampler_t addrspace(2)*
2394 // @clspv.sampler.var.literal(
2395 // i32 descriptor,
2396 // i32 binding,
2397 // i32 index-into-sampler-map)
alan-bakerb6b09dc2018-11-08 16:59:28 -05002398 if (auto *call = dyn_cast<CallInst>(user)) {
2399 const size_t index_into_sampler_map = static_cast<size_t>(
2400 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04002401 if (index_into_sampler_map >= sampler_map.size()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002402 errs() << "Out of bounds index to sampler map: "
2403 << index_into_sampler_map;
David Neto862b7d82018-06-14 18:48:37 -04002404 llvm_unreachable("bad sampler init: out of bounds");
2405 }
2406
2407 auto sampler_value = sampler_map[index_into_sampler_map].first;
2408 const auto descriptor_set = static_cast<unsigned>(
2409 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
2410 const auto binding = static_cast<unsigned>(
2411 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
2412
2413 SamplerLiteralToDescriptorSetMap[sampler_value] = descriptor_set;
2414 SamplerLiteralToBindingMap[sampler_value] = binding;
2415 used_bindings.insert(binding);
2416 }
2417 }
2418
2419 unsigned index = 0;
2420 for (auto SamplerLiteral : sampler_map) {
David Neto22f144c2017-06-12 14:26:21 -04002421 // Generate OpVariable.
2422 //
2423 // GIDOps[0] : Result Type ID
2424 // GIDOps[1] : Storage Class
2425 SPIRVOperandList Ops;
2426
David Neto257c3892018-04-11 13:19:45 -04002427 Ops << MkId(lookupType(SamplerTy))
2428 << MkNum(spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002429
David Neto862b7d82018-06-14 18:48:37 -04002430 auto sampler_var_id = nextID++;
2431 auto *Inst = new SPIRVInstruction(spv::OpVariable, sampler_var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002432 SPIRVInstList.push_back(Inst);
2433
David Neto862b7d82018-06-14 18:48:37 -04002434 SamplerMapIndexToIDMap[index] = sampler_var_id;
2435 SamplerLiteralToIDMap[SamplerLiteral.first] = sampler_var_id;
David Neto22f144c2017-06-12 14:26:21 -04002436
2437 // Find Insert Point for OpDecorate.
2438 auto DecoInsertPoint =
2439 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2440 [](SPIRVInstruction *Inst) -> bool {
2441 return Inst->getOpcode() != spv::OpDecorate &&
2442 Inst->getOpcode() != spv::OpMemberDecorate &&
2443 Inst->getOpcode() != spv::OpExtInstImport;
2444 });
2445
2446 // Ops[0] = Target ID
2447 // Ops[1] = Decoration (DescriptorSet)
2448 // Ops[2] = LiteralNumber according to Decoration
2449 Ops.clear();
2450
David Neto862b7d82018-06-14 18:48:37 -04002451 unsigned descriptor_set;
2452 unsigned binding;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002453 if (SamplerLiteralToBindingMap.find(SamplerLiteral.first) ==
2454 SamplerLiteralToBindingMap.end()) {
David Neto862b7d82018-06-14 18:48:37 -04002455 // This sampler is not actually used. Find the next one.
2456 for (binding = 0; used_bindings.count(binding); binding++)
2457 ;
2458 descriptor_set = 0; // Literal samplers always use descriptor set 0.
2459 used_bindings.insert(binding);
2460 } else {
2461 descriptor_set = SamplerLiteralToDescriptorSetMap[SamplerLiteral.first];
2462 binding = SamplerLiteralToBindingMap[SamplerLiteral.first];
alan-bakercff80152019-06-15 00:38:00 -04002463
2464 version0::DescriptorMapEntry::SamplerData sampler_data = {
2465 SamplerLiteral.first};
2466 descriptorMapEntries->emplace_back(std::move(sampler_data),
2467 descriptor_set, binding);
David Neto862b7d82018-06-14 18:48:37 -04002468 }
2469
2470 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationDescriptorSet)
2471 << MkNum(descriptor_set);
David Neto22f144c2017-06-12 14:26:21 -04002472
David Neto87846742018-04-11 17:36:22 -04002473 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002474 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2475
2476 // Ops[0] = Target ID
2477 // Ops[1] = Decoration (Binding)
2478 // Ops[2] = LiteralNumber according to Decoration
2479 Ops.clear();
David Neto862b7d82018-06-14 18:48:37 -04002480 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationBinding)
2481 << MkNum(binding);
David Neto22f144c2017-06-12 14:26:21 -04002482
David Neto87846742018-04-11 17:36:22 -04002483 auto *BindDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002484 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
David Neto862b7d82018-06-14 18:48:37 -04002485
2486 index++;
David Neto22f144c2017-06-12 14:26:21 -04002487 }
David Neto862b7d82018-06-14 18:48:37 -04002488}
David Neto22f144c2017-06-12 14:26:21 -04002489
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01002490void SPIRVProducerPass::GenerateResourceVars(Module &) {
David Neto862b7d82018-06-14 18:48:37 -04002491 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2492 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04002493
David Neto862b7d82018-06-14 18:48:37 -04002494 // Generate variables. Make one for each of resource var info object.
2495 for (auto *info : ModuleOrderedResourceVars) {
2496 Type *type = info->var_fn->getReturnType();
2497 // Remap the address space for opaque types.
2498 switch (info->arg_kind) {
2499 case clspv::ArgKind::Sampler:
2500 case clspv::ArgKind::ReadOnlyImage:
2501 case clspv::ArgKind::WriteOnlyImage:
2502 type = PointerType::get(type->getPointerElementType(),
2503 clspv::AddressSpace::UniformConstant);
2504 break;
2505 default:
2506 break;
2507 }
David Neto22f144c2017-06-12 14:26:21 -04002508
David Neto862b7d82018-06-14 18:48:37 -04002509 info->var_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04002510
David Neto862b7d82018-06-14 18:48:37 -04002511 const auto type_id = lookupType(type);
2512 const auto sc = GetStorageClassForArgKind(info->arg_kind);
2513 SPIRVOperandList Ops;
2514 Ops << MkId(type_id) << MkNum(sc);
David Neto22f144c2017-06-12 14:26:21 -04002515
David Neto862b7d82018-06-14 18:48:37 -04002516 auto *Inst = new SPIRVInstruction(spv::OpVariable, info->var_id, Ops);
2517 SPIRVInstList.push_back(Inst);
2518
2519 // Map calls to the variable-builtin-function.
2520 for (auto &U : info->var_fn->uses()) {
2521 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
2522 const auto set = unsigned(
2523 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
2524 const auto binding = unsigned(
2525 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
2526 if (set == info->descriptor_set && binding == info->binding) {
2527 switch (info->arg_kind) {
2528 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002529 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002530 case clspv::ArgKind::Pod:
2531 // The call maps to the variable directly.
2532 VMap[call] = info->var_id;
2533 break;
2534 case clspv::ArgKind::Sampler:
2535 case clspv::ArgKind::ReadOnlyImage:
2536 case clspv::ArgKind::WriteOnlyImage:
2537 // The call maps to a load we generate later.
2538 ResourceVarDeferredLoadCalls[call] = info->var_id;
2539 break;
2540 default:
2541 llvm_unreachable("Unhandled arg kind");
2542 }
2543 }
David Neto22f144c2017-06-12 14:26:21 -04002544 }
David Neto862b7d82018-06-14 18:48:37 -04002545 }
2546 }
David Neto22f144c2017-06-12 14:26:21 -04002547
David Neto862b7d82018-06-14 18:48:37 -04002548 // Generate associated decorations.
David Neto22f144c2017-06-12 14:26:21 -04002549
David Neto862b7d82018-06-14 18:48:37 -04002550 // Find Insert Point for OpDecorate.
2551 auto DecoInsertPoint =
2552 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2553 [](SPIRVInstruction *Inst) -> bool {
2554 return Inst->getOpcode() != spv::OpDecorate &&
2555 Inst->getOpcode() != spv::OpMemberDecorate &&
2556 Inst->getOpcode() != spv::OpExtInstImport;
2557 });
2558
2559 SPIRVOperandList Ops;
2560 for (auto *info : ModuleOrderedResourceVars) {
2561 // Decorate with DescriptorSet and Binding.
2562 Ops.clear();
2563 Ops << MkId(info->var_id) << MkNum(spv::DecorationDescriptorSet)
2564 << MkNum(info->descriptor_set);
2565 SPIRVInstList.insert(DecoInsertPoint,
2566 new SPIRVInstruction(spv::OpDecorate, Ops));
2567
2568 Ops.clear();
2569 Ops << MkId(info->var_id) << MkNum(spv::DecorationBinding)
2570 << MkNum(info->binding);
2571 SPIRVInstList.insert(DecoInsertPoint,
2572 new SPIRVInstruction(spv::OpDecorate, Ops));
2573
alan-bakere9308012019-03-15 10:25:13 -04002574 if (info->coherent) {
2575 // Decorate with Coherent if required for the variable.
2576 Ops.clear();
2577 Ops << MkId(info->var_id) << MkNum(spv::DecorationCoherent);
2578 SPIRVInstList.insert(DecoInsertPoint,
2579 new SPIRVInstruction(spv::OpDecorate, Ops));
2580 }
2581
David Neto862b7d82018-06-14 18:48:37 -04002582 // Generate NonWritable and NonReadable
2583 switch (info->arg_kind) {
2584 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002585 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002586 if (info->var_fn->getReturnType()->getPointerAddressSpace() ==
2587 clspv::AddressSpace::Constant) {
2588 Ops.clear();
2589 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
2590 SPIRVInstList.insert(DecoInsertPoint,
2591 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002592 }
David Neto862b7d82018-06-14 18:48:37 -04002593 break;
David Neto862b7d82018-06-14 18:48:37 -04002594 case clspv::ArgKind::WriteOnlyImage:
2595 Ops.clear();
2596 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonReadable);
2597 SPIRVInstList.insert(DecoInsertPoint,
2598 new SPIRVInstruction(spv::OpDecorate, Ops));
2599 break;
2600 default:
2601 break;
David Neto22f144c2017-06-12 14:26:21 -04002602 }
2603 }
2604}
2605
2606void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002607 Module &M = *GV.getParent();
David Neto22f144c2017-06-12 14:26:21 -04002608 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2609 ValueMapType &VMap = getValueMap();
2610 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07002611 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002612
2613 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2614 Type *Ty = GV.getType();
2615 PointerType *PTy = cast<PointerType>(Ty);
2616
2617 uint32_t InitializerID = 0;
2618
2619 // Workgroup size is handled differently (it goes into a constant)
2620 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2621 std::vector<bool> HasMDVec;
2622 uint32_t PrevXDimCst = 0xFFFFFFFF;
2623 uint32_t PrevYDimCst = 0xFFFFFFFF;
2624 uint32_t PrevZDimCst = 0xFFFFFFFF;
2625 for (Function &Func : *GV.getParent()) {
2626 if (Func.isDeclaration()) {
2627 continue;
2628 }
2629
2630 // We only need to check kernels.
2631 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2632 continue;
2633 }
2634
2635 if (const MDNode *MD =
2636 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2637 uint32_t CurXDimCst = static_cast<uint32_t>(
2638 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2639 uint32_t CurYDimCst = static_cast<uint32_t>(
2640 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2641 uint32_t CurZDimCst = static_cast<uint32_t>(
2642 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2643
2644 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2645 PrevZDimCst == 0xFFFFFFFF) {
2646 PrevXDimCst = CurXDimCst;
2647 PrevYDimCst = CurYDimCst;
2648 PrevZDimCst = CurZDimCst;
2649 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2650 CurZDimCst != PrevZDimCst) {
2651 llvm_unreachable(
2652 "reqd_work_group_size must be the same across all kernels");
2653 } else {
2654 continue;
2655 }
2656
2657 //
2658 // Generate OpConstantComposite.
2659 //
2660 // Ops[0] : Result Type ID
2661 // Ops[1] : Constant size for x dimension.
2662 // Ops[2] : Constant size for y dimension.
2663 // Ops[3] : Constant size for z dimension.
2664 SPIRVOperandList Ops;
2665
2666 uint32_t XDimCstID =
2667 VMap[mdconst::extract<ConstantInt>(MD->getOperand(0))];
2668 uint32_t YDimCstID =
2669 VMap[mdconst::extract<ConstantInt>(MD->getOperand(1))];
2670 uint32_t ZDimCstID =
2671 VMap[mdconst::extract<ConstantInt>(MD->getOperand(2))];
2672
2673 InitializerID = nextID;
2674
David Neto257c3892018-04-11 13:19:45 -04002675 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2676 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002677
David Neto87846742018-04-11 17:36:22 -04002678 auto *Inst =
2679 new SPIRVInstruction(spv::OpConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002680 SPIRVInstList.push_back(Inst);
2681
2682 HasMDVec.push_back(true);
2683 } else {
2684 HasMDVec.push_back(false);
2685 }
2686 }
2687
2688 // Check all kernels have same definitions for work_group_size.
2689 bool HasMD = false;
2690 if (!HasMDVec.empty()) {
2691 HasMD = HasMDVec[0];
2692 for (uint32_t i = 1; i < HasMDVec.size(); i++) {
2693 if (HasMD != HasMDVec[i]) {
2694 llvm_unreachable(
2695 "Kernels should have consistent work group size definition");
2696 }
2697 }
2698 }
2699
2700 // If all kernels do not have metadata for reqd_work_group_size, generate
2701 // OpSpecConstants for x/y/z dimension.
2702 if (!HasMD) {
2703 //
2704 // Generate OpSpecConstants for x/y/z dimension.
2705 //
2706 // Ops[0] : Result Type ID
2707 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
2708 uint32_t XDimCstID = 0;
2709 uint32_t YDimCstID = 0;
2710 uint32_t ZDimCstID = 0;
2711
David Neto22f144c2017-06-12 14:26:21 -04002712 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04002713 uint32_t result_type_id =
2714 lookupType(Ty->getPointerElementType()->getSequentialElementType());
David Neto22f144c2017-06-12 14:26:21 -04002715
David Neto257c3892018-04-11 13:19:45 -04002716 // X Dimension
2717 Ops << MkId(result_type_id) << MkNum(1);
2718 XDimCstID = nextID++;
2719 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002720 new SPIRVInstruction(spv::OpSpecConstant, XDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002721
2722 // Y Dimension
2723 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002724 Ops << MkId(result_type_id) << MkNum(1);
2725 YDimCstID = nextID++;
2726 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002727 new SPIRVInstruction(spv::OpSpecConstant, YDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002728
2729 // Z Dimension
2730 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002731 Ops << MkId(result_type_id) << MkNum(1);
2732 ZDimCstID = nextID++;
2733 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002734 new SPIRVInstruction(spv::OpSpecConstant, ZDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002735
David Neto257c3892018-04-11 13:19:45 -04002736 BuiltinDimVec.push_back(XDimCstID);
2737 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002738 BuiltinDimVec.push_back(ZDimCstID);
2739
David Neto22f144c2017-06-12 14:26:21 -04002740 //
2741 // Generate OpSpecConstantComposite.
2742 //
2743 // Ops[0] : Result Type ID
2744 // Ops[1] : Constant size for x dimension.
2745 // Ops[2] : Constant size for y dimension.
2746 // Ops[3] : Constant size for z dimension.
2747 InitializerID = nextID;
2748
2749 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002750 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2751 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002752
David Neto87846742018-04-11 17:36:22 -04002753 auto *Inst =
2754 new SPIRVInstruction(spv::OpSpecConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002755 SPIRVInstList.push_back(Inst);
2756 }
2757 }
2758
David Neto22f144c2017-06-12 14:26:21 -04002759 VMap[&GV] = nextID;
2760
2761 //
2762 // Generate OpVariable.
2763 //
2764 // GIDOps[0] : Result Type ID
2765 // GIDOps[1] : Storage Class
2766 SPIRVOperandList Ops;
2767
David Neto85082642018-03-24 06:55:20 -07002768 const auto AS = PTy->getAddressSpace();
David Netoc6f3ab22018-04-06 18:02:31 -04002769 Ops << MkId(lookupType(Ty)) << MkNum(GetStorageClass(AS));
David Neto22f144c2017-06-12 14:26:21 -04002770
David Neto85082642018-03-24 06:55:20 -07002771 if (GV.hasInitializer()) {
2772 InitializerID = VMap[GV.getInitializer()];
David Neto22f144c2017-06-12 14:26:21 -04002773 }
2774
David Neto85082642018-03-24 06:55:20 -07002775 const bool module_scope_constant_external_init =
David Neto862b7d82018-06-14 18:48:37 -04002776 (AS == AddressSpace::Constant) && GV.hasInitializer() &&
David Neto85082642018-03-24 06:55:20 -07002777 clspv::Option::ModuleConstantsInStorageBuffer();
2778
2779 if (0 != InitializerID) {
2780 if (!module_scope_constant_external_init) {
2781 // Emit the ID of the intiializer as part of the variable definition.
David Netoc6f3ab22018-04-06 18:02:31 -04002782 Ops << MkId(InitializerID);
David Neto85082642018-03-24 06:55:20 -07002783 }
2784 }
2785 const uint32_t var_id = nextID++;
2786
David Neto87846742018-04-11 17:36:22 -04002787 auto *Inst = new SPIRVInstruction(spv::OpVariable, var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002788 SPIRVInstList.push_back(Inst);
2789
2790 // If we have a builtin.
2791 if (spv::BuiltInMax != BuiltinType) {
2792 // Find Insert Point for OpDecorate.
2793 auto DecoInsertPoint =
2794 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2795 [](SPIRVInstruction *Inst) -> bool {
2796 return Inst->getOpcode() != spv::OpDecorate &&
2797 Inst->getOpcode() != spv::OpMemberDecorate &&
2798 Inst->getOpcode() != spv::OpExtInstImport;
2799 });
2800 //
2801 // Generate OpDecorate.
2802 //
2803 // DOps[0] = Target ID
2804 // DOps[1] = Decoration (Builtin)
2805 // DOps[2] = BuiltIn ID
2806 uint32_t ResultID;
2807
2808 // WorkgroupSize is different, we decorate the constant composite that has
2809 // its value, rather than the variable that we use to access the value.
2810 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2811 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04002812 // Save both the value and variable IDs for later.
2813 WorkgroupSizeValueID = InitializerID;
2814 WorkgroupSizeVarID = VMap[&GV];
David Neto22f144c2017-06-12 14:26:21 -04002815 } else {
2816 ResultID = VMap[&GV];
2817 }
2818
2819 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002820 DOps << MkId(ResultID) << MkNum(spv::DecorationBuiltIn)
2821 << MkNum(BuiltinType);
David Neto22f144c2017-06-12 14:26:21 -04002822
David Neto87846742018-04-11 17:36:22 -04002823 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, DOps);
David Neto22f144c2017-06-12 14:26:21 -04002824 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
David Neto85082642018-03-24 06:55:20 -07002825 } else if (module_scope_constant_external_init) {
2826 // This module scope constant is initialized from a storage buffer with data
2827 // provided by the host at binding 0 of the next descriptor set.
David Neto78383442018-06-15 20:31:56 -04002828 const uint32_t descriptor_set = TakeDescriptorIndex(&M);
David Neto85082642018-03-24 06:55:20 -07002829
David Neto862b7d82018-06-14 18:48:37 -04002830 // Emit the intializer to the descriptor map file.
David Neto85082642018-03-24 06:55:20 -07002831 // Use "kind,buffer" to indicate storage buffer. We might want to expand
2832 // that later to other types, like uniform buffer.
alan-bakerf5e5f692018-11-27 08:33:24 -05002833 std::string hexbytes;
2834 llvm::raw_string_ostream str(hexbytes);
2835 clspv::ConstantEmitter(DL, str).Emit(GV.getInitializer());
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002836 version0::DescriptorMapEntry::ConstantData constant_data = {ArgKind::Buffer,
2837 str.str()};
2838 descriptorMapEntries->emplace_back(std::move(constant_data), descriptor_set,
2839 0);
David Neto85082642018-03-24 06:55:20 -07002840
2841 // Find Insert Point for OpDecorate.
2842 auto DecoInsertPoint =
2843 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2844 [](SPIRVInstruction *Inst) -> bool {
2845 return Inst->getOpcode() != spv::OpDecorate &&
2846 Inst->getOpcode() != spv::OpMemberDecorate &&
2847 Inst->getOpcode() != spv::OpExtInstImport;
2848 });
2849
David Neto257c3892018-04-11 13:19:45 -04002850 // OpDecorate %var Binding <binding>
David Neto85082642018-03-24 06:55:20 -07002851 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002852 DOps << MkId(var_id) << MkNum(spv::DecorationBinding) << MkNum(0);
2853 DecoInsertPoint = SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04002854 DecoInsertPoint, new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto85082642018-03-24 06:55:20 -07002855
2856 // OpDecorate %var DescriptorSet <descriptor_set>
2857 DOps.clear();
David Neto257c3892018-04-11 13:19:45 -04002858 DOps << MkId(var_id) << MkNum(spv::DecorationDescriptorSet)
2859 << MkNum(descriptor_set);
David Netoc6f3ab22018-04-06 18:02:31 -04002860 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04002861 new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto22f144c2017-06-12 14:26:21 -04002862 }
2863}
2864
David Netoc6f3ab22018-04-06 18:02:31 -04002865void SPIRVProducerPass::GenerateWorkgroupVars() {
2866 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
Alan Baker202c8c72018-08-13 13:47:44 -04002867 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2868 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002869 LocalArgInfo &info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002870
2871 // Generate OpVariable.
2872 //
2873 // GIDOps[0] : Result Type ID
2874 // GIDOps[1] : Storage Class
2875 SPIRVOperandList Ops;
2876 Ops << MkId(info.ptr_array_type_id) << MkNum(spv::StorageClassWorkgroup);
2877
2878 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002879 new SPIRVInstruction(spv::OpVariable, info.variable_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002880 }
2881}
2882
David Neto862b7d82018-06-14 18:48:37 -04002883void SPIRVProducerPass::GenerateDescriptorMapInfo(const DataLayout &DL,
2884 Function &F) {
David Netoc5fb5242018-07-30 13:28:31 -04002885 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2886 return;
2887 }
David Neto862b7d82018-06-14 18:48:37 -04002888 // Gather the list of resources that are used by this function's arguments.
2889 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
2890
alan-bakerf5e5f692018-11-27 08:33:24 -05002891 // TODO(alan-baker): This should become unnecessary by fixing the rest of the
2892 // flow to generate pod_ubo arguments earlier.
David Neto862b7d82018-06-14 18:48:37 -04002893 auto remap_arg_kind = [](StringRef argKind) {
alan-bakerf5e5f692018-11-27 08:33:24 -05002894 std::string kind =
2895 clspv::Option::PodArgsInUniformBuffer() && argKind.equals("pod")
2896 ? "pod_ubo"
2897 : argKind;
2898 return GetArgKindFromName(kind);
David Neto862b7d82018-06-14 18:48:37 -04002899 };
2900
2901 auto *fty = F.getType()->getPointerElementType();
2902 auto *func_ty = dyn_cast<FunctionType>(fty);
2903
alan-baker038e9242019-04-19 22:14:41 -04002904 // If we've clustered POD arguments, then argument details are in metadata.
David Neto862b7d82018-06-14 18:48:37 -04002905 // If an argument maps to a resource variable, then get descriptor set and
2906 // binding from the resoure variable. Other info comes from the metadata.
2907 const auto *arg_map = F.getMetadata("kernel_arg_map");
2908 if (arg_map) {
2909 for (const auto &arg : arg_map->operands()) {
2910 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
Kévin PETITa353c832018-03-20 23:21:21 +00002911 assert(arg_node->getNumOperands() == 7);
David Neto862b7d82018-06-14 18:48:37 -04002912 const auto name =
2913 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
2914 const auto old_index =
2915 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
2916 // Remapped argument index
alan-bakerb6b09dc2018-11-08 16:59:28 -05002917 const size_t new_index = static_cast<size_t>(
2918 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04002919 const auto offset =
2920 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
Kévin PETITa353c832018-03-20 23:21:21 +00002921 const auto arg_size =
2922 dyn_extract<ConstantInt>(arg_node->getOperand(4))->getZExtValue();
David Neto862b7d82018-06-14 18:48:37 -04002923 const auto argKind = remap_arg_kind(
Kévin PETITa353c832018-03-20 23:21:21 +00002924 dyn_cast<MDString>(arg_node->getOperand(5))->getString());
David Neto862b7d82018-06-14 18:48:37 -04002925 const auto spec_id =
Kévin PETITa353c832018-03-20 23:21:21 +00002926 dyn_extract<ConstantInt>(arg_node->getOperand(6))->getSExtValue();
alan-bakerf5e5f692018-11-27 08:33:24 -05002927
2928 uint32_t descriptor_set = 0;
2929 uint32_t binding = 0;
2930 version0::DescriptorMapEntry::KernelArgData kernel_data = {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002931 F.getName(), name, static_cast<uint32_t>(old_index), argKind,
alan-bakerf5e5f692018-11-27 08:33:24 -05002932 static_cast<uint32_t>(spec_id),
2933 // This will be set below for pointer-to-local args.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002934 0, static_cast<uint32_t>(offset), static_cast<uint32_t>(arg_size)};
David Neto862b7d82018-06-14 18:48:37 -04002935 if (spec_id > 0) {
alan-bakerf5e5f692018-11-27 08:33:24 -05002936 kernel_data.local_element_size = static_cast<uint32_t>(GetTypeAllocSize(
2937 func_ty->getParamType(unsigned(new_index))->getPointerElementType(),
2938 DL));
David Neto862b7d82018-06-14 18:48:37 -04002939 } else {
2940 auto *info = resource_var_at_index[new_index];
2941 assert(info);
alan-bakerf5e5f692018-11-27 08:33:24 -05002942 descriptor_set = info->descriptor_set;
2943 binding = info->binding;
David Neto862b7d82018-06-14 18:48:37 -04002944 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002945 descriptorMapEntries->emplace_back(std::move(kernel_data), descriptor_set,
2946 binding);
David Neto862b7d82018-06-14 18:48:37 -04002947 }
2948 } else {
2949 // There is no argument map.
2950 // Take descriptor info from the resource variable calls.
Kévin PETITa353c832018-03-20 23:21:21 +00002951 // Take argument name and size from the arguments list.
David Neto862b7d82018-06-14 18:48:37 -04002952
2953 SmallVector<Argument *, 4> arguments;
2954 for (auto &arg : F.args()) {
2955 arguments.push_back(&arg);
2956 }
2957
2958 unsigned arg_index = 0;
2959 for (auto *info : resource_var_at_index) {
2960 if (info) {
Kévin PETITa353c832018-03-20 23:21:21 +00002961 auto arg = arguments[arg_index];
alan-bakerb6b09dc2018-11-08 16:59:28 -05002962 unsigned arg_size = 0;
Kévin PETITa353c832018-03-20 23:21:21 +00002963 if (info->arg_kind == clspv::ArgKind::Pod) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002964 arg_size = static_cast<uint32_t>(DL.getTypeStoreSize(arg->getType()));
Kévin PETITa353c832018-03-20 23:21:21 +00002965 }
2966
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002967 // Local pointer arguments are unused in this case. Offset is always
2968 // zero.
alan-bakerf5e5f692018-11-27 08:33:24 -05002969 version0::DescriptorMapEntry::KernelArgData kernel_data = {
2970 F.getName(), arg->getName(),
2971 arg_index, remap_arg_kind(clspv::GetArgKindName(info->arg_kind)),
2972 0, 0,
2973 0, arg_size};
2974 descriptorMapEntries->emplace_back(std::move(kernel_data),
2975 info->descriptor_set, info->binding);
David Neto862b7d82018-06-14 18:48:37 -04002976 }
2977 arg_index++;
2978 }
2979 // Generate mappings for pointer-to-local arguments.
2980 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
2981 Argument *arg = arguments[arg_index];
Alan Baker202c8c72018-08-13 13:47:44 -04002982 auto where = LocalArgSpecIds.find(arg);
2983 if (where != LocalArgSpecIds.end()) {
2984 auto &local_arg_info = LocalSpecIdInfoMap[where->second];
alan-bakerf5e5f692018-11-27 08:33:24 -05002985 // Pod arguments members are unused in this case.
2986 version0::DescriptorMapEntry::KernelArgData kernel_data = {
2987 F.getName(),
2988 arg->getName(),
2989 arg_index,
2990 ArgKind::Local,
2991 static_cast<uint32_t>(local_arg_info.spec_id),
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002992 static_cast<uint32_t>(
2993 GetTypeAllocSize(local_arg_info.elem_type, DL)),
alan-bakerf5e5f692018-11-27 08:33:24 -05002994 0,
2995 0};
2996 // Pointer-to-local arguments do not utilize descriptor set and binding.
2997 descriptorMapEntries->emplace_back(std::move(kernel_data), 0, 0);
David Neto862b7d82018-06-14 18:48:37 -04002998 }
2999 }
3000 }
3001}
3002
David Neto22f144c2017-06-12 14:26:21 -04003003void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
3004 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3005 ValueMapType &VMap = getValueMap();
3006 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04003007 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
3008 auto &GlobalConstArgSet = getGlobalConstArgSet();
3009
3010 FunctionType *FTy = F.getFunctionType();
3011
3012 //
David Neto22f144c2017-06-12 14:26:21 -04003013 // Generate OPFunction.
3014 //
3015
3016 // FOps[0] : Result Type ID
3017 // FOps[1] : Function Control
3018 // FOps[2] : Function Type ID
3019 SPIRVOperandList FOps;
3020
3021 // Find SPIRV instruction for return type.
David Neto257c3892018-04-11 13:19:45 -04003022 FOps << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04003023
3024 // Check function attributes for SPIRV Function Control.
3025 uint32_t FuncControl = spv::FunctionControlMaskNone;
3026 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
3027 FuncControl |= spv::FunctionControlInlineMask;
3028 }
3029 if (F.hasFnAttribute(Attribute::NoInline)) {
3030 FuncControl |= spv::FunctionControlDontInlineMask;
3031 }
3032 // TODO: Check llvm attribute for Function Control Pure.
3033 if (F.hasFnAttribute(Attribute::ReadOnly)) {
3034 FuncControl |= spv::FunctionControlPureMask;
3035 }
3036 // TODO: Check llvm attribute for Function Control Const.
3037 if (F.hasFnAttribute(Attribute::ReadNone)) {
3038 FuncControl |= spv::FunctionControlConstMask;
3039 }
3040
David Neto257c3892018-04-11 13:19:45 -04003041 FOps << MkNum(FuncControl);
David Neto22f144c2017-06-12 14:26:21 -04003042
3043 uint32_t FTyID;
3044 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3045 SmallVector<Type *, 4> NewFuncParamTys;
3046 FunctionType *NewFTy =
3047 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
3048 FTyID = lookupType(NewFTy);
3049 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07003050 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04003051 if (GlobalConstFuncTyMap.count(FTy)) {
3052 FTyID = lookupType(GlobalConstFuncTyMap[FTy].first);
3053 } else {
3054 FTyID = lookupType(FTy);
3055 }
3056 }
3057
David Neto257c3892018-04-11 13:19:45 -04003058 FOps << MkId(FTyID);
David Neto22f144c2017-06-12 14:26:21 -04003059
3060 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3061 EntryPoints.push_back(std::make_pair(&F, nextID));
3062 }
3063
3064 VMap[&F] = nextID;
3065
David Neto482550a2018-03-24 05:21:07 -07003066 if (clspv::Option::ShowIDs()) {
David Netob05675d2018-02-16 12:37:49 -05003067 errs() << "Function " << F.getName() << " is " << nextID << "\n";
3068 }
David Neto22f144c2017-06-12 14:26:21 -04003069 // Generate SPIRV instruction for function.
David Neto87846742018-04-11 17:36:22 -04003070 auto *FuncInst = new SPIRVInstruction(spv::OpFunction, nextID++, FOps);
David Neto22f144c2017-06-12 14:26:21 -04003071 SPIRVInstList.push_back(FuncInst);
3072
3073 //
3074 // Generate OpFunctionParameter for Normal function.
3075 //
3076
3077 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
alan-bakere9308012019-03-15 10:25:13 -04003078
3079 // Find Insert Point for OpDecorate.
3080 auto DecoInsertPoint =
3081 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
3082 [](SPIRVInstruction *Inst) -> bool {
3083 return Inst->getOpcode() != spv::OpDecorate &&
3084 Inst->getOpcode() != spv::OpMemberDecorate &&
3085 Inst->getOpcode() != spv::OpExtInstImport;
3086 });
3087
David Neto22f144c2017-06-12 14:26:21 -04003088 // Iterate Argument for name instead of param type from function type.
3089 unsigned ArgIdx = 0;
3090 for (Argument &Arg : F.args()) {
alan-bakere9308012019-03-15 10:25:13 -04003091 uint32_t param_id = nextID++;
3092 VMap[&Arg] = param_id;
3093
3094 if (CalledWithCoherentResource(Arg)) {
3095 // If the arg is passed a coherent resource ever, then decorate this
3096 // parameter with Coherent too.
3097 SPIRVOperandList decoration_ops;
3098 decoration_ops << MkId(param_id) << MkNum(spv::DecorationCoherent);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003099 SPIRVInstList.insert(
3100 DecoInsertPoint,
3101 new SPIRVInstruction(spv::OpDecorate, decoration_ops));
alan-bakere9308012019-03-15 10:25:13 -04003102 }
David Neto22f144c2017-06-12 14:26:21 -04003103
3104 // ParamOps[0] : Result Type ID
3105 SPIRVOperandList ParamOps;
3106
3107 // Find SPIRV instruction for parameter type.
3108 uint32_t ParamTyID = lookupType(Arg.getType());
3109 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
3110 if (GlobalConstFuncTyMap.count(FTy)) {
3111 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
3112 Type *EleTy = PTy->getPointerElementType();
3113 Type *ArgTy =
3114 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
3115 ParamTyID = lookupType(ArgTy);
3116 GlobalConstArgSet.insert(&Arg);
3117 }
3118 }
3119 }
David Neto257c3892018-04-11 13:19:45 -04003120 ParamOps << MkId(ParamTyID);
David Neto22f144c2017-06-12 14:26:21 -04003121
3122 // Generate SPIRV instruction for parameter.
David Neto87846742018-04-11 17:36:22 -04003123 auto *ParamInst =
alan-bakere9308012019-03-15 10:25:13 -04003124 new SPIRVInstruction(spv::OpFunctionParameter, param_id, ParamOps);
David Neto22f144c2017-06-12 14:26:21 -04003125 SPIRVInstList.push_back(ParamInst);
3126
3127 ArgIdx++;
3128 }
3129 }
3130}
3131
alan-bakerb6b09dc2018-11-08 16:59:28 -05003132void SPIRVProducerPass::GenerateModuleInfo(Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04003133 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3134 EntryPointVecType &EntryPoints = getEntryPointVec();
3135 ValueMapType &VMap = getValueMap();
3136 ValueList &EntryPointInterfaces = getEntryPointInterfacesVec();
3137 uint32_t &ExtInstImportID = getOpExtInstImportID();
3138 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
3139
3140 // Set up insert point.
3141 auto InsertPoint = SPIRVInstList.begin();
3142
3143 //
3144 // Generate OpCapability
3145 //
3146 // TODO: Which llvm information is mapped to SPIRV Capapbility?
3147
3148 // Ops[0] = Capability
3149 SPIRVOperandList Ops;
3150
David Neto87846742018-04-11 17:36:22 -04003151 auto *CapInst =
3152 new SPIRVInstruction(spv::OpCapability, {MkNum(spv::CapabilityShader)});
David Neto22f144c2017-06-12 14:26:21 -04003153 SPIRVInstList.insert(InsertPoint, CapInst);
3154
3155 for (Type *Ty : getTypeList()) {
alan-bakerb39c8262019-03-08 14:03:37 -05003156 if (clspv::Option::Int8Support() && Ty->isIntegerTy(8)) {
3157 // Generate OpCapability for i8 type.
3158 SPIRVInstList.insert(InsertPoint,
3159 new SPIRVInstruction(spv::OpCapability,
3160 {MkNum(spv::CapabilityInt8)}));
3161 } else if (Ty->isIntegerTy(16)) {
David Neto22f144c2017-06-12 14:26:21 -04003162 // Generate OpCapability for i16 type.
David Neto87846742018-04-11 17:36:22 -04003163 SPIRVInstList.insert(InsertPoint,
3164 new SPIRVInstruction(spv::OpCapability,
3165 {MkNum(spv::CapabilityInt16)}));
David Neto22f144c2017-06-12 14:26:21 -04003166 } else if (Ty->isIntegerTy(64)) {
3167 // Generate OpCapability for i64 type.
David Neto87846742018-04-11 17:36:22 -04003168 SPIRVInstList.insert(InsertPoint,
3169 new SPIRVInstruction(spv::OpCapability,
3170 {MkNum(spv::CapabilityInt64)}));
David Neto22f144c2017-06-12 14:26:21 -04003171 } else if (Ty->isHalfTy()) {
3172 // Generate OpCapability for half type.
3173 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003174 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3175 {MkNum(spv::CapabilityFloat16)}));
David Neto22f144c2017-06-12 14:26:21 -04003176 } else if (Ty->isDoubleTy()) {
3177 // Generate OpCapability for double type.
3178 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003179 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3180 {MkNum(spv::CapabilityFloat64)}));
David Neto22f144c2017-06-12 14:26:21 -04003181 } else if (auto *STy = dyn_cast<StructType>(Ty)) {
3182 if (STy->isOpaque()) {
David Neto565571c2017-08-21 12:00:05 -04003183 if (STy->getName().equals("opencl.image2d_wo_t") ||
3184 STy->getName().equals("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04003185 // Generate OpCapability for write only image type.
3186 SPIRVInstList.insert(
3187 InsertPoint,
3188 new SPIRVInstruction(
David Neto87846742018-04-11 17:36:22 -04003189 spv::OpCapability,
3190 {MkNum(spv::CapabilityStorageImageWriteWithoutFormat)}));
David Neto22f144c2017-06-12 14:26:21 -04003191 }
3192 }
3193 }
3194 }
3195
David Neto5c22a252018-03-15 16:07:41 -04003196 { // OpCapability ImageQuery
3197 bool hasImageQuery = false;
3198 for (const char *imageQuery : {
3199 "_Z15get_image_width14ocl_image2d_ro",
3200 "_Z15get_image_width14ocl_image2d_wo",
3201 "_Z16get_image_height14ocl_image2d_ro",
3202 "_Z16get_image_height14ocl_image2d_wo",
3203 }) {
3204 if (module.getFunction(imageQuery)) {
3205 hasImageQuery = true;
3206 break;
3207 }
3208 }
3209 if (hasImageQuery) {
David Neto87846742018-04-11 17:36:22 -04003210 auto *ImageQueryCapInst = new SPIRVInstruction(
3211 spv::OpCapability, {MkNum(spv::CapabilityImageQuery)});
David Neto5c22a252018-03-15 16:07:41 -04003212 SPIRVInstList.insert(InsertPoint, ImageQueryCapInst);
3213 }
3214 }
3215
David Neto22f144c2017-06-12 14:26:21 -04003216 if (hasVariablePointers()) {
3217 //
David Neto22f144c2017-06-12 14:26:21 -04003218 // Generate OpCapability.
3219 //
3220 // Ops[0] = Capability
3221 //
3222 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003223 Ops << MkNum(spv::CapabilityVariablePointers);
David Neto22f144c2017-06-12 14:26:21 -04003224
David Neto87846742018-04-11 17:36:22 -04003225 SPIRVInstList.insert(InsertPoint,
3226 new SPIRVInstruction(spv::OpCapability, Ops));
alan-baker5b86ed72019-02-15 08:26:50 -05003227 } else if (hasVariablePointersStorageBuffer()) {
3228 //
3229 // Generate OpCapability.
3230 //
3231 // Ops[0] = Capability
3232 //
3233 Ops.clear();
3234 Ops << MkNum(spv::CapabilityVariablePointersStorageBuffer);
David Neto22f144c2017-06-12 14:26:21 -04003235
alan-baker5b86ed72019-02-15 08:26:50 -05003236 SPIRVInstList.insert(InsertPoint,
3237 new SPIRVInstruction(spv::OpCapability, Ops));
3238 }
3239
3240 // Always add the storage buffer extension
3241 {
David Neto22f144c2017-06-12 14:26:21 -04003242 //
3243 // Generate OpExtension.
3244 //
3245 // Ops[0] = Name (Literal String)
3246 //
alan-baker5b86ed72019-02-15 08:26:50 -05003247 auto *ExtensionInst = new SPIRVInstruction(
3248 spv::OpExtension, {MkString("SPV_KHR_storage_buffer_storage_class")});
3249 SPIRVInstList.insert(InsertPoint, ExtensionInst);
3250 }
David Neto22f144c2017-06-12 14:26:21 -04003251
alan-baker5b86ed72019-02-15 08:26:50 -05003252 if (hasVariablePointers() || hasVariablePointersStorageBuffer()) {
3253 //
3254 // Generate OpExtension.
3255 //
3256 // Ops[0] = Name (Literal String)
3257 //
3258 auto *ExtensionInst = new SPIRVInstruction(
3259 spv::OpExtension, {MkString("SPV_KHR_variable_pointers")});
3260 SPIRVInstList.insert(InsertPoint, ExtensionInst);
David Neto22f144c2017-06-12 14:26:21 -04003261 }
3262
3263 if (ExtInstImportID) {
3264 ++InsertPoint;
3265 }
3266
3267 //
3268 // Generate OpMemoryModel
3269 //
3270 // Memory model for Vulkan will always be GLSL450.
3271
3272 // Ops[0] = Addressing Model
3273 // Ops[1] = Memory Model
3274 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003275 Ops << MkNum(spv::AddressingModelLogical) << MkNum(spv::MemoryModelGLSL450);
David Neto22f144c2017-06-12 14:26:21 -04003276
David Neto87846742018-04-11 17:36:22 -04003277 auto *MemModelInst = new SPIRVInstruction(spv::OpMemoryModel, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003278 SPIRVInstList.insert(InsertPoint, MemModelInst);
3279
3280 //
3281 // Generate OpEntryPoint
3282 //
3283 for (auto EntryPoint : EntryPoints) {
3284 // Ops[0] = Execution Model
3285 // Ops[1] = EntryPoint ID
3286 // Ops[2] = Name (Literal String)
3287 // ...
3288 //
3289 // TODO: Do we need to consider Interface ID for forward references???
3290 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003291 const StringRef &name = EntryPoint.first->getName();
David Neto257c3892018-04-11 13:19:45 -04003292 Ops << MkNum(spv::ExecutionModelGLCompute) << MkId(EntryPoint.second)
3293 << MkString(name);
David Neto22f144c2017-06-12 14:26:21 -04003294
David Neto22f144c2017-06-12 14:26:21 -04003295 for (Value *Interface : EntryPointInterfaces) {
David Neto257c3892018-04-11 13:19:45 -04003296 Ops << MkId(VMap[Interface]);
David Neto22f144c2017-06-12 14:26:21 -04003297 }
3298
David Neto87846742018-04-11 17:36:22 -04003299 auto *EntryPointInst = new SPIRVInstruction(spv::OpEntryPoint, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003300 SPIRVInstList.insert(InsertPoint, EntryPointInst);
3301 }
3302
3303 for (auto EntryPoint : EntryPoints) {
3304 if (const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
3305 ->getMetadata("reqd_work_group_size")) {
3306
3307 if (!BuiltinDimVec.empty()) {
3308 llvm_unreachable(
3309 "Kernels should have consistent work group size definition");
3310 }
3311
3312 //
3313 // Generate OpExecutionMode
3314 //
3315
3316 // Ops[0] = Entry Point ID
3317 // Ops[1] = Execution Mode
3318 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
3319 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003320 Ops << MkId(EntryPoint.second) << MkNum(spv::ExecutionModeLocalSize);
David Neto22f144c2017-06-12 14:26:21 -04003321
3322 uint32_t XDim = static_cast<uint32_t>(
3323 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3324 uint32_t YDim = static_cast<uint32_t>(
3325 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3326 uint32_t ZDim = static_cast<uint32_t>(
3327 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3328
David Neto257c3892018-04-11 13:19:45 -04003329 Ops << MkNum(XDim) << MkNum(YDim) << MkNum(ZDim);
David Neto22f144c2017-06-12 14:26:21 -04003330
David Neto87846742018-04-11 17:36:22 -04003331 auto *ExecModeInst = new SPIRVInstruction(spv::OpExecutionMode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003332 SPIRVInstList.insert(InsertPoint, ExecModeInst);
3333 }
3334 }
3335
3336 //
3337 // Generate OpSource.
3338 //
3339 // Ops[0] = SourceLanguage ID
3340 // Ops[1] = Version (LiteralNum)
3341 //
3342 Ops.clear();
Kévin Petit0fc88042019-04-09 23:25:02 +01003343 if (clspv::Option::CPlusPlus()) {
3344 Ops << MkNum(spv::SourceLanguageOpenCL_CPP) << MkNum(100);
3345 } else {
3346 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(120);
3347 }
David Neto22f144c2017-06-12 14:26:21 -04003348
David Neto87846742018-04-11 17:36:22 -04003349 auto *OpenSourceInst = new SPIRVInstruction(spv::OpSource, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003350 SPIRVInstList.insert(InsertPoint, OpenSourceInst);
3351
3352 if (!BuiltinDimVec.empty()) {
3353 //
3354 // Generate OpDecorates for x/y/z dimension.
3355 //
3356 // Ops[0] = Target ID
3357 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04003358 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04003359
3360 // X Dimension
3361 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003362 Ops << MkId(BuiltinDimVec[0]) << MkNum(spv::DecorationSpecId) << MkNum(0);
David Neto87846742018-04-11 17:36:22 -04003363 SPIRVInstList.insert(InsertPoint,
3364 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003365
3366 // Y Dimension
3367 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003368 Ops << MkId(BuiltinDimVec[1]) << MkNum(spv::DecorationSpecId) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04003369 SPIRVInstList.insert(InsertPoint,
3370 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003371
3372 // Z Dimension
3373 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003374 Ops << MkId(BuiltinDimVec[2]) << MkNum(spv::DecorationSpecId) << MkNum(2);
David Neto87846742018-04-11 17:36:22 -04003375 SPIRVInstList.insert(InsertPoint,
3376 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003377 }
3378}
3379
David Netob6e2e062018-04-25 10:32:06 -04003380void SPIRVProducerPass::GenerateEntryPointInitialStores() {
3381 // Work around a driver bug. Initializers on Private variables might not
3382 // work. So the start of the kernel should store the initializer value to the
3383 // variables. Yes, *every* entry point pays this cost if *any* entry point
3384 // uses this builtin. At this point I judge this to be an acceptable tradeoff
3385 // of complexity vs. runtime, for a broken driver.
alan-bakerb6b09dc2018-11-08 16:59:28 -05003386 // TODO(dneto): Remove this at some point once fixed drivers are widely
3387 // available.
David Netob6e2e062018-04-25 10:32:06 -04003388 if (WorkgroupSizeVarID) {
3389 assert(WorkgroupSizeValueID);
3390
3391 SPIRVOperandList Ops;
3392 Ops << MkId(WorkgroupSizeVarID) << MkId(WorkgroupSizeValueID);
3393
3394 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
3395 getSPIRVInstList().push_back(Inst);
3396 }
3397}
3398
David Neto22f144c2017-06-12 14:26:21 -04003399void SPIRVProducerPass::GenerateFuncBody(Function &F) {
3400 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3401 ValueMapType &VMap = getValueMap();
3402
David Netob6e2e062018-04-25 10:32:06 -04003403 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04003404
3405 for (BasicBlock &BB : F) {
3406 // Register BasicBlock to ValueMap.
3407 VMap[&BB] = nextID;
3408
3409 //
3410 // Generate OpLabel for Basic Block.
3411 //
3412 SPIRVOperandList Ops;
David Neto87846742018-04-11 17:36:22 -04003413 auto *Inst = new SPIRVInstruction(spv::OpLabel, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003414 SPIRVInstList.push_back(Inst);
3415
David Neto6dcd4712017-06-23 11:06:47 -04003416 // OpVariable instructions must come first.
3417 for (Instruction &I : BB) {
alan-baker5b86ed72019-02-15 08:26:50 -05003418 if (auto *alloca = dyn_cast<AllocaInst>(&I)) {
3419 // Allocating a pointer requires variable pointers.
3420 if (alloca->getAllocatedType()->isPointerTy()) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003421 setVariablePointersCapabilities(
3422 alloca->getAllocatedType()->getPointerAddressSpace());
alan-baker5b86ed72019-02-15 08:26:50 -05003423 }
David Neto6dcd4712017-06-23 11:06:47 -04003424 GenerateInstruction(I);
3425 }
3426 }
3427
David Neto22f144c2017-06-12 14:26:21 -04003428 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04003429 if (clspv::Option::HackInitializers()) {
3430 GenerateEntryPointInitialStores();
3431 }
David Neto22f144c2017-06-12 14:26:21 -04003432 }
3433
3434 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003435 if (!isa<AllocaInst>(I)) {
3436 GenerateInstruction(I);
3437 }
David Neto22f144c2017-06-12 14:26:21 -04003438 }
3439 }
3440}
3441
3442spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3443 const std::map<CmpInst::Predicate, spv::Op> Map = {
3444 {CmpInst::ICMP_EQ, spv::OpIEqual},
3445 {CmpInst::ICMP_NE, spv::OpINotEqual},
3446 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3447 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3448 {CmpInst::ICMP_ULT, spv::OpULessThan},
3449 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3450 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3451 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3452 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3453 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3454 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3455 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3456 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3457 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3458 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3459 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3460 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3461 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3462 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3463 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3464 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3465 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3466
3467 assert(0 != Map.count(I->getPredicate()));
3468
3469 return Map.at(I->getPredicate());
3470}
3471
3472spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3473 const std::map<unsigned, spv::Op> Map{
3474 {Instruction::Trunc, spv::OpUConvert},
3475 {Instruction::ZExt, spv::OpUConvert},
3476 {Instruction::SExt, spv::OpSConvert},
3477 {Instruction::FPToUI, spv::OpConvertFToU},
3478 {Instruction::FPToSI, spv::OpConvertFToS},
3479 {Instruction::UIToFP, spv::OpConvertUToF},
3480 {Instruction::SIToFP, spv::OpConvertSToF},
3481 {Instruction::FPTrunc, spv::OpFConvert},
3482 {Instruction::FPExt, spv::OpFConvert},
3483 {Instruction::BitCast, spv::OpBitcast}};
3484
3485 assert(0 != Map.count(I.getOpcode()));
3486
3487 return Map.at(I.getOpcode());
3488}
3489
3490spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
Kévin Petit24272b62018-10-18 19:16:12 +00003491 if (I.getType()->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003492 switch (I.getOpcode()) {
3493 default:
3494 break;
3495 case Instruction::Or:
3496 return spv::OpLogicalOr;
3497 case Instruction::And:
3498 return spv::OpLogicalAnd;
3499 case Instruction::Xor:
3500 return spv::OpLogicalNotEqual;
3501 }
3502 }
3503
alan-bakerb6b09dc2018-11-08 16:59:28 -05003504 const std::map<unsigned, spv::Op> Map{
David Neto22f144c2017-06-12 14:26:21 -04003505 {Instruction::Add, spv::OpIAdd},
3506 {Instruction::FAdd, spv::OpFAdd},
3507 {Instruction::Sub, spv::OpISub},
3508 {Instruction::FSub, spv::OpFSub},
3509 {Instruction::Mul, spv::OpIMul},
3510 {Instruction::FMul, spv::OpFMul},
3511 {Instruction::UDiv, spv::OpUDiv},
3512 {Instruction::SDiv, spv::OpSDiv},
3513 {Instruction::FDiv, spv::OpFDiv},
3514 {Instruction::URem, spv::OpUMod},
3515 {Instruction::SRem, spv::OpSRem},
3516 {Instruction::FRem, spv::OpFRem},
3517 {Instruction::Or, spv::OpBitwiseOr},
3518 {Instruction::Xor, spv::OpBitwiseXor},
3519 {Instruction::And, spv::OpBitwiseAnd},
3520 {Instruction::Shl, spv::OpShiftLeftLogical},
3521 {Instruction::LShr, spv::OpShiftRightLogical},
3522 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3523
3524 assert(0 != Map.count(I.getOpcode()));
3525
3526 return Map.at(I.getOpcode());
3527}
3528
3529void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
3530 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3531 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04003532 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
3533 LLVMContext &Context = I.getParent()->getParent()->getParent()->getContext();
3534
3535 // Register Instruction to ValueMap.
3536 if (0 == VMap[&I]) {
3537 VMap[&I] = nextID;
3538 }
3539
3540 switch (I.getOpcode()) {
3541 default: {
3542 if (Instruction::isCast(I.getOpcode())) {
3543 //
3544 // Generate SPIRV instructions for cast operators.
3545 //
3546
David Netod2de94a2017-08-28 17:27:47 -04003547 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003548 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003549 auto toI8 = Ty == Type::getInt8Ty(Context);
3550 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003551 // Handle zext, sext and uitofp with i1 type specially.
3552 if ((I.getOpcode() == Instruction::ZExt ||
3553 I.getOpcode() == Instruction::SExt ||
3554 I.getOpcode() == Instruction::UIToFP) &&
alan-bakerb6b09dc2018-11-08 16:59:28 -05003555 OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003556 //
3557 // Generate OpSelect.
3558 //
3559
3560 // Ops[0] = Result Type ID
3561 // Ops[1] = Condition ID
3562 // Ops[2] = True Constant ID
3563 // Ops[3] = False Constant ID
3564 SPIRVOperandList Ops;
3565
David Neto257c3892018-04-11 13:19:45 -04003566 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003567
David Neto22f144c2017-06-12 14:26:21 -04003568 uint32_t CondID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003569 Ops << MkId(CondID);
David Neto22f144c2017-06-12 14:26:21 -04003570
3571 uint32_t TrueID = 0;
3572 if (I.getOpcode() == Instruction::ZExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00003573 TrueID = VMap[ConstantInt::get(I.getType(), 1)];
David Neto22f144c2017-06-12 14:26:21 -04003574 } else if (I.getOpcode() == Instruction::SExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00003575 TrueID = VMap[ConstantInt::getSigned(I.getType(), -1)];
David Neto22f144c2017-06-12 14:26:21 -04003576 } else {
3577 TrueID = VMap[ConstantFP::get(Context, APFloat(1.0f))];
3578 }
David Neto257c3892018-04-11 13:19:45 -04003579 Ops << MkId(TrueID);
David Neto22f144c2017-06-12 14:26:21 -04003580
3581 uint32_t FalseID = 0;
3582 if (I.getOpcode() == Instruction::ZExt) {
3583 FalseID = VMap[Constant::getNullValue(I.getType())];
3584 } else if (I.getOpcode() == Instruction::SExt) {
3585 FalseID = VMap[Constant::getNullValue(I.getType())];
3586 } else {
3587 FalseID = VMap[ConstantFP::get(Context, APFloat(0.0f))];
3588 }
David Neto257c3892018-04-11 13:19:45 -04003589 Ops << MkId(FalseID);
David Neto22f144c2017-06-12 14:26:21 -04003590
David Neto87846742018-04-11 17:36:22 -04003591 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003592 SPIRVInstList.push_back(Inst);
alan-bakerb39c8262019-03-08 14:03:37 -05003593 } else if (!clspv::Option::Int8Support() &&
3594 I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
David Netod2de94a2017-08-28 17:27:47 -04003595 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3596 // 8 bits.
3597 // Before:
3598 // %result = trunc i32 %a to i8
3599 // After
3600 // %result = OpBitwiseAnd %uint %a %uint_255
3601
3602 SPIRVOperandList Ops;
3603
David Neto257c3892018-04-11 13:19:45 -04003604 Ops << MkId(lookupType(OpTy)) << MkId(VMap[I.getOperand(0)]);
David Netod2de94a2017-08-28 17:27:47 -04003605
3606 Type *UintTy = Type::getInt32Ty(Context);
3607 uint32_t MaskID = VMap[ConstantInt::get(UintTy, 255)];
David Neto257c3892018-04-11 13:19:45 -04003608 Ops << MkId(MaskID);
David Netod2de94a2017-08-28 17:27:47 -04003609
David Neto87846742018-04-11 17:36:22 -04003610 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Netod2de94a2017-08-28 17:27:47 -04003611 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003612 } else {
3613 // Ops[0] = Result Type ID
3614 // Ops[1] = Source Value ID
3615 SPIRVOperandList Ops;
3616
David Neto257c3892018-04-11 13:19:45 -04003617 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003618
David Neto87846742018-04-11 17:36:22 -04003619 auto *Inst = new SPIRVInstruction(GetSPIRVCastOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003620 SPIRVInstList.push_back(Inst);
3621 }
3622 } else if (isa<BinaryOperator>(I)) {
3623 //
3624 // Generate SPIRV instructions for binary operators.
3625 //
3626
3627 // Handle xor with i1 type specially.
3628 if (I.getOpcode() == Instruction::Xor &&
3629 I.getType() == Type::getInt1Ty(Context) &&
Kévin Petit24272b62018-10-18 19:16:12 +00003630 ((isa<ConstantInt>(I.getOperand(0)) &&
3631 !cast<ConstantInt>(I.getOperand(0))->isZero()) ||
3632 (isa<ConstantInt>(I.getOperand(1)) &&
3633 !cast<ConstantInt>(I.getOperand(1))->isZero()))) {
David Neto22f144c2017-06-12 14:26:21 -04003634 //
3635 // Generate OpLogicalNot.
3636 //
3637 // Ops[0] = Result Type ID
3638 // Ops[1] = Operand
3639 SPIRVOperandList Ops;
3640
David Neto257c3892018-04-11 13:19:45 -04003641 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003642
3643 Value *CondV = I.getOperand(0);
3644 if (isa<Constant>(I.getOperand(0))) {
3645 CondV = I.getOperand(1);
3646 }
David Neto257c3892018-04-11 13:19:45 -04003647 Ops << MkId(VMap[CondV]);
David Neto22f144c2017-06-12 14:26:21 -04003648
David Neto87846742018-04-11 17:36:22 -04003649 auto *Inst = new SPIRVInstruction(spv::OpLogicalNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003650 SPIRVInstList.push_back(Inst);
3651 } else {
3652 // Ops[0] = Result Type ID
3653 // Ops[1] = Operand 0
3654 // Ops[2] = Operand 1
3655 SPIRVOperandList Ops;
3656
David Neto257c3892018-04-11 13:19:45 -04003657 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
3658 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003659
David Neto87846742018-04-11 17:36:22 -04003660 auto *Inst =
3661 new SPIRVInstruction(GetSPIRVBinaryOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003662 SPIRVInstList.push_back(Inst);
3663 }
3664 } else {
3665 I.print(errs());
3666 llvm_unreachable("Unsupported instruction???");
3667 }
3668 break;
3669 }
3670 case Instruction::GetElementPtr: {
3671 auto &GlobalConstArgSet = getGlobalConstArgSet();
3672
3673 //
3674 // Generate OpAccessChain.
3675 //
3676 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
3677
3678 //
3679 // Generate OpAccessChain.
3680 //
3681
3682 // Ops[0] = Result Type ID
3683 // Ops[1] = Base ID
3684 // Ops[2] ... Ops[n] = Indexes ID
3685 SPIRVOperandList Ops;
3686
alan-bakerb6b09dc2018-11-08 16:59:28 -05003687 PointerType *ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04003688 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
3689 GlobalConstArgSet.count(GEP->getPointerOperand())) {
3690 // Use pointer type with private address space for global constant.
3691 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04003692 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04003693 }
David Neto257c3892018-04-11 13:19:45 -04003694
3695 Ops << MkId(lookupType(ResultType));
David Neto22f144c2017-06-12 14:26:21 -04003696
David Neto862b7d82018-06-14 18:48:37 -04003697 // Generate the base pointer.
3698 Ops << MkId(VMap[GEP->getPointerOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04003699
David Neto862b7d82018-06-14 18:48:37 -04003700 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04003701
3702 //
3703 // Follows below rules for gep.
3704 //
David Neto862b7d82018-06-14 18:48:37 -04003705 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
3706 // first index.
David Neto22f144c2017-06-12 14:26:21 -04003707 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
3708 // first index.
3709 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
3710 // use gep's first index.
3711 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
3712 // gep's first index.
3713 //
3714 spv::Op Opcode = spv::OpAccessChain;
3715 unsigned offset = 0;
3716 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04003717 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04003718 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04003719 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04003720 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04003721 }
David Neto862b7d82018-06-14 18:48:37 -04003722 } else {
David Neto22f144c2017-06-12 14:26:21 -04003723 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04003724 }
3725
3726 if (Opcode == spv::OpPtrAccessChain) {
David Neto1a1a0582017-07-07 12:01:44 -04003727 // Do we need to generate ArrayStride? Check against the GEP result type
3728 // rather than the pointer type of the base because when indexing into
3729 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
3730 // for something else in the SPIR-V.
3731 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
alan-baker5b86ed72019-02-15 08:26:50 -05003732 auto address_space = ResultType->getAddressSpace();
3733 setVariablePointersCapabilities(address_space);
3734 switch (GetStorageClass(address_space)) {
Alan Bakerfcda9482018-10-02 17:09:59 -04003735 case spv::StorageClassStorageBuffer:
3736 case spv::StorageClassUniform:
David Neto1a1a0582017-07-07 12:01:44 -04003737 // Save the need to generate an ArrayStride decoration. But defer
3738 // generation until later, so we only make one decoration.
David Neto85082642018-03-24 06:55:20 -07003739 getTypesNeedingArrayStride().insert(ResultType);
Alan Bakerfcda9482018-10-02 17:09:59 -04003740 break;
3741 default:
3742 break;
David Neto1a1a0582017-07-07 12:01:44 -04003743 }
David Neto22f144c2017-06-12 14:26:21 -04003744 }
3745
3746 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
David Neto257c3892018-04-11 13:19:45 -04003747 Ops << MkId(VMap[*II]);
David Neto22f144c2017-06-12 14:26:21 -04003748 }
3749
David Neto87846742018-04-11 17:36:22 -04003750 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003751 SPIRVInstList.push_back(Inst);
3752 break;
3753 }
3754 case Instruction::ExtractValue: {
3755 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3756 // Ops[0] = Result Type ID
3757 // Ops[1] = Composite ID
3758 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3759 SPIRVOperandList Ops;
3760
David Neto257c3892018-04-11 13:19:45 -04003761 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003762
3763 uint32_t CompositeID = VMap[EVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003764 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003765
3766 for (auto &Index : EVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003767 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003768 }
3769
David Neto87846742018-04-11 17:36:22 -04003770 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003771 SPIRVInstList.push_back(Inst);
3772 break;
3773 }
3774 case Instruction::InsertValue: {
3775 InsertValueInst *IVI = cast<InsertValueInst>(&I);
3776 // Ops[0] = Result Type ID
3777 // Ops[1] = Object ID
3778 // Ops[2] = Composite ID
3779 // Ops[3] ... Ops[n] = Indexes (Literal Number)
3780 SPIRVOperandList Ops;
3781
3782 uint32_t ResTyID = lookupType(I.getType());
David Neto257c3892018-04-11 13:19:45 -04003783 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04003784
3785 uint32_t ObjectID = VMap[IVI->getInsertedValueOperand()];
David Neto257c3892018-04-11 13:19:45 -04003786 Ops << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04003787
3788 uint32_t CompositeID = VMap[IVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003789 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003790
3791 for (auto &Index : IVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003792 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003793 }
3794
David Neto87846742018-04-11 17:36:22 -04003795 auto *Inst = new SPIRVInstruction(spv::OpCompositeInsert, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003796 SPIRVInstList.push_back(Inst);
3797 break;
3798 }
3799 case Instruction::Select: {
3800 //
3801 // Generate OpSelect.
3802 //
3803
3804 // Ops[0] = Result Type ID
3805 // Ops[1] = Condition ID
3806 // Ops[2] = True Constant ID
3807 // Ops[3] = False Constant ID
3808 SPIRVOperandList Ops;
3809
3810 // Find SPIRV instruction for parameter type.
3811 auto Ty = I.getType();
3812 if (Ty->isPointerTy()) {
3813 auto PointeeTy = Ty->getPointerElementType();
3814 if (PointeeTy->isStructTy() &&
3815 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
3816 Ty = PointeeTy;
alan-baker5b86ed72019-02-15 08:26:50 -05003817 } else {
3818 // Selecting between pointers requires variable pointers.
3819 setVariablePointersCapabilities(Ty->getPointerAddressSpace());
3820 if (!hasVariablePointers() && !selectFromSameObject(&I)) {
3821 setVariablePointers(true);
3822 }
David Neto22f144c2017-06-12 14:26:21 -04003823 }
3824 }
3825
David Neto257c3892018-04-11 13:19:45 -04003826 Ops << MkId(lookupType(Ty)) << MkId(VMap[I.getOperand(0)])
3827 << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003828
David Neto87846742018-04-11 17:36:22 -04003829 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003830 SPIRVInstList.push_back(Inst);
3831 break;
3832 }
3833 case Instruction::ExtractElement: {
3834 // Handle <4 x i8> type manually.
3835 Type *CompositeTy = I.getOperand(0)->getType();
3836 if (is4xi8vec(CompositeTy)) {
3837 //
3838 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
3839 // <4 x i8>.
3840 //
3841
3842 //
3843 // Generate OpShiftRightLogical
3844 //
3845 // Ops[0] = Result Type ID
3846 // Ops[1] = Operand 0
3847 // Ops[2] = Operand 1
3848 //
3849 SPIRVOperandList Ops;
3850
David Neto257c3892018-04-11 13:19:45 -04003851 Ops << MkId(lookupType(CompositeTy));
David Neto22f144c2017-06-12 14:26:21 -04003852
3853 uint32_t Op0ID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003854 Ops << MkId(Op0ID);
David Neto22f144c2017-06-12 14:26:21 -04003855
3856 uint32_t Op1ID = 0;
3857 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
3858 // Handle constant index.
3859 uint64_t Idx = CI->getZExtValue();
3860 Value *ShiftAmount =
3861 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3862 Op1ID = VMap[ShiftAmount];
3863 } else {
3864 // Handle variable index.
3865 SPIRVOperandList TmpOps;
3866
David Neto257c3892018-04-11 13:19:45 -04003867 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3868 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003869
3870 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003871 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003872
3873 Op1ID = nextID;
3874
David Neto87846742018-04-11 17:36:22 -04003875 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003876 SPIRVInstList.push_back(TmpInst);
3877 }
David Neto257c3892018-04-11 13:19:45 -04003878 Ops << MkId(Op1ID);
David Neto22f144c2017-06-12 14:26:21 -04003879
3880 uint32_t ShiftID = nextID;
3881
David Neto87846742018-04-11 17:36:22 -04003882 auto *Inst =
3883 new SPIRVInstruction(spv::OpShiftRightLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003884 SPIRVInstList.push_back(Inst);
3885
3886 //
3887 // Generate OpBitwiseAnd
3888 //
3889 // Ops[0] = Result Type ID
3890 // Ops[1] = Operand 0
3891 // Ops[2] = Operand 1
3892 //
3893 Ops.clear();
3894
David Neto257c3892018-04-11 13:19:45 -04003895 Ops << MkId(lookupType(CompositeTy)) << MkId(ShiftID);
David Neto22f144c2017-06-12 14:26:21 -04003896
3897 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
David Neto257c3892018-04-11 13:19:45 -04003898 Ops << MkId(VMap[CstFF]);
David Neto22f144c2017-06-12 14:26:21 -04003899
David Neto9b2d6252017-09-06 15:47:37 -04003900 // Reset mapping for this value to the result of the bitwise and.
3901 VMap[&I] = nextID;
3902
David Neto87846742018-04-11 17:36:22 -04003903 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003904 SPIRVInstList.push_back(Inst);
3905 break;
3906 }
3907
3908 // Ops[0] = Result Type ID
3909 // Ops[1] = Composite ID
3910 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3911 SPIRVOperandList Ops;
3912
David Neto257c3892018-04-11 13:19:45 -04003913 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003914
3915 spv::Op Opcode = spv::OpCompositeExtract;
3916 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
David Neto257c3892018-04-11 13:19:45 -04003917 Ops << MkNum(static_cast<uint32_t>(CI->getZExtValue()));
David Neto22f144c2017-06-12 14:26:21 -04003918 } else {
David Neto257c3892018-04-11 13:19:45 -04003919 Ops << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003920 Opcode = spv::OpVectorExtractDynamic;
3921 }
3922
David Neto87846742018-04-11 17:36:22 -04003923 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003924 SPIRVInstList.push_back(Inst);
3925 break;
3926 }
3927 case Instruction::InsertElement: {
3928 // Handle <4 x i8> type manually.
3929 Type *CompositeTy = I.getOperand(0)->getType();
3930 if (is4xi8vec(CompositeTy)) {
3931 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
3932 uint32_t CstFFID = VMap[CstFF];
3933
3934 uint32_t ShiftAmountID = 0;
3935 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
3936 // Handle constant index.
3937 uint64_t Idx = CI->getZExtValue();
3938 Value *ShiftAmount =
3939 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3940 ShiftAmountID = VMap[ShiftAmount];
3941 } else {
3942 // Handle variable index.
3943 SPIRVOperandList TmpOps;
3944
David Neto257c3892018-04-11 13:19:45 -04003945 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3946 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003947
3948 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003949 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003950
3951 ShiftAmountID = nextID;
3952
David Neto87846742018-04-11 17:36:22 -04003953 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003954 SPIRVInstList.push_back(TmpInst);
3955 }
3956
3957 //
3958 // Generate mask operations.
3959 //
3960
3961 // ShiftLeft mask according to index of insertelement.
3962 SPIRVOperandList Ops;
3963
David Neto257c3892018-04-11 13:19:45 -04003964 const uint32_t ResTyID = lookupType(CompositeTy);
3965 Ops << MkId(ResTyID) << MkId(CstFFID) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04003966
3967 uint32_t MaskID = nextID;
3968
David Neto87846742018-04-11 17:36:22 -04003969 auto *Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003970 SPIRVInstList.push_back(Inst);
3971
3972 // Inverse mask.
3973 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003974 Ops << MkId(ResTyID) << MkId(MaskID);
David Neto22f144c2017-06-12 14:26:21 -04003975
3976 uint32_t InvMaskID = nextID;
3977
David Neto87846742018-04-11 17:36:22 -04003978 Inst = new SPIRVInstruction(spv::OpNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003979 SPIRVInstList.push_back(Inst);
3980
3981 // Apply mask.
3982 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003983 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(0)]) << MkId(InvMaskID);
David Neto22f144c2017-06-12 14:26:21 -04003984
3985 uint32_t OrgValID = nextID;
3986
David Neto87846742018-04-11 17:36:22 -04003987 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003988 SPIRVInstList.push_back(Inst);
3989
3990 // Create correct value according to index of insertelement.
3991 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003992 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(1)])
3993 << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04003994
3995 uint32_t InsertValID = nextID;
3996
David Neto87846742018-04-11 17:36:22 -04003997 Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003998 SPIRVInstList.push_back(Inst);
3999
4000 // Insert value to original value.
4001 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004002 Ops << MkId(ResTyID) << MkId(OrgValID) << MkId(InsertValID);
David Neto22f144c2017-06-12 14:26:21 -04004003
David Netoa394f392017-08-26 20:45:29 -04004004 VMap[&I] = nextID;
4005
David Neto87846742018-04-11 17:36:22 -04004006 Inst = new SPIRVInstruction(spv::OpBitwiseOr, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004007 SPIRVInstList.push_back(Inst);
4008
4009 break;
4010 }
4011
David Neto22f144c2017-06-12 14:26:21 -04004012 SPIRVOperandList Ops;
4013
James Priced26efea2018-06-09 23:28:32 +01004014 // Ops[0] = Result Type ID
4015 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004016
4017 spv::Op Opcode = spv::OpCompositeInsert;
4018 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04004019 const auto value = CI->getZExtValue();
4020 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01004021 // Ops[1] = Object ID
4022 // Ops[2] = Composite ID
4023 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004024 Ops << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(0)])
James Priced26efea2018-06-09 23:28:32 +01004025 << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004026 } else {
James Priced26efea2018-06-09 23:28:32 +01004027 // Ops[1] = Composite ID
4028 // Ops[2] = Object ID
4029 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004030 Ops << MkId(VMap[I.getOperand(0)]) << MkId(VMap[I.getOperand(1)])
James Priced26efea2018-06-09 23:28:32 +01004031 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004032 Opcode = spv::OpVectorInsertDynamic;
4033 }
4034
David Neto87846742018-04-11 17:36:22 -04004035 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004036 SPIRVInstList.push_back(Inst);
4037 break;
4038 }
4039 case Instruction::ShuffleVector: {
4040 // Ops[0] = Result Type ID
4041 // Ops[1] = Vector 1 ID
4042 // Ops[2] = Vector 2 ID
4043 // Ops[3] ... Ops[n] = Components (Literal Number)
4044 SPIRVOperandList Ops;
4045
David Neto257c3892018-04-11 13:19:45 -04004046 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4047 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004048
4049 uint64_t NumElements = 0;
4050 if (Constant *Cst = dyn_cast<Constant>(I.getOperand(2))) {
4051 NumElements = cast<VectorType>(Cst->getType())->getNumElements();
4052
4053 if (Cst->isNullValue()) {
4054 for (unsigned i = 0; i < NumElements; i++) {
David Neto257c3892018-04-11 13:19:45 -04004055 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04004056 }
4057 } else if (const ConstantDataSequential *CDS =
4058 dyn_cast<ConstantDataSequential>(Cst)) {
4059 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
4060 std::vector<uint32_t> LiteralNum;
David Neto257c3892018-04-11 13:19:45 -04004061 const auto value = CDS->getElementAsInteger(i);
4062 assert(value <= UINT32_MAX);
4063 Ops << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004064 }
4065 } else if (const ConstantVector *CV = dyn_cast<ConstantVector>(Cst)) {
4066 for (unsigned i = 0; i < CV->getNumOperands(); i++) {
4067 auto Op = CV->getOperand(i);
4068
4069 uint32_t literal = 0;
4070
4071 if (auto CI = dyn_cast<ConstantInt>(Op)) {
4072 literal = static_cast<uint32_t>(CI->getZExtValue());
4073 } else if (auto UI = dyn_cast<UndefValue>(Op)) {
4074 literal = 0xFFFFFFFFu;
4075 } else {
4076 Op->print(errs());
4077 llvm_unreachable("Unsupported element in ConstantVector!");
4078 }
4079
David Neto257c3892018-04-11 13:19:45 -04004080 Ops << MkNum(literal);
David Neto22f144c2017-06-12 14:26:21 -04004081 }
4082 } else {
4083 Cst->print(errs());
4084 llvm_unreachable("Unsupported constant mask in ShuffleVector!");
4085 }
4086 }
4087
David Neto87846742018-04-11 17:36:22 -04004088 auto *Inst = new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004089 SPIRVInstList.push_back(Inst);
4090 break;
4091 }
4092 case Instruction::ICmp:
4093 case Instruction::FCmp: {
4094 CmpInst *CmpI = cast<CmpInst>(&I);
4095
David Netod4ca2e62017-07-06 18:47:35 -04004096 // Pointer equality is invalid.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004097 Type *ArgTy = CmpI->getOperand(0)->getType();
David Netod4ca2e62017-07-06 18:47:35 -04004098 if (isa<PointerType>(ArgTy)) {
4099 CmpI->print(errs());
4100 std::string name = I.getParent()->getParent()->getName();
4101 errs()
4102 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4103 << "in function " << name << "\n";
4104 llvm_unreachable("Pointer equality check is invalid");
4105 break;
4106 }
4107
David Neto257c3892018-04-11 13:19:45 -04004108 // Ops[0] = Result Type ID
4109 // Ops[1] = Operand 1 ID
4110 // Ops[2] = Operand 2 ID
4111 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004112
David Neto257c3892018-04-11 13:19:45 -04004113 Ops << MkId(lookupType(CmpI->getType())) << MkId(VMap[CmpI->getOperand(0)])
4114 << MkId(VMap[CmpI->getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004115
4116 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
David Neto87846742018-04-11 17:36:22 -04004117 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004118 SPIRVInstList.push_back(Inst);
4119 break;
4120 }
4121 case Instruction::Br: {
4122 // Branch instrucion is deferred because it needs label's ID. Record slot's
4123 // location on SPIRVInstructionList.
4124 DeferredInsts.push_back(
4125 std::make_tuple(&I, --SPIRVInstList.end(), 0 /* No id */));
4126 break;
4127 }
4128 case Instruction::Switch: {
4129 I.print(errs());
4130 llvm_unreachable("Unsupported instruction???");
4131 break;
4132 }
4133 case Instruction::IndirectBr: {
4134 I.print(errs());
4135 llvm_unreachable("Unsupported instruction???");
4136 break;
4137 }
4138 case Instruction::PHI: {
4139 // Branch instrucion is deferred because it needs label's ID. Record slot's
4140 // location on SPIRVInstructionList.
4141 DeferredInsts.push_back(
4142 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4143 break;
4144 }
4145 case Instruction::Alloca: {
4146 //
4147 // Generate OpVariable.
4148 //
4149 // Ops[0] : Result Type ID
4150 // Ops[1] : Storage Class
4151 SPIRVOperandList Ops;
4152
David Neto257c3892018-04-11 13:19:45 -04004153 Ops << MkId(lookupType(I.getType())) << MkNum(spv::StorageClassFunction);
David Neto22f144c2017-06-12 14:26:21 -04004154
David Neto87846742018-04-11 17:36:22 -04004155 auto *Inst = new SPIRVInstruction(spv::OpVariable, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004156 SPIRVInstList.push_back(Inst);
4157 break;
4158 }
4159 case Instruction::Load: {
4160 LoadInst *LD = cast<LoadInst>(&I);
4161 //
4162 // Generate OpLoad.
4163 //
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04004164
alan-baker5b86ed72019-02-15 08:26:50 -05004165 if (LD->getType()->isPointerTy()) {
4166 // Loading a pointer requires variable pointers.
4167 setVariablePointersCapabilities(LD->getType()->getPointerAddressSpace());
4168 }
David Neto22f144c2017-06-12 14:26:21 -04004169
David Neto0a2f98d2017-09-15 19:38:40 -04004170 uint32_t ResTyID = lookupType(LD->getType());
David Netoa60b00b2017-09-15 16:34:09 -04004171 uint32_t PointerID = VMap[LD->getPointerOperand()];
4172
4173 // This is a hack to work around what looks like a driver bug.
4174 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004175 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4176 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004177 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004178 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004179 // Generate a bitwise-and of the original value with itself.
4180 // We should have been able to get away with just an OpCopyObject,
4181 // but we need something more complex to get past certain driver bugs.
4182 // This is ridiculous, but necessary.
4183 // TODO(dneto): Revisit this once drivers fix their bugs.
4184
4185 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004186 Ops << MkId(ResTyID) << MkId(WorkgroupSizeValueID)
4187 << MkId(WorkgroupSizeValueID);
David Neto0a2f98d2017-09-15 19:38:40 -04004188
David Neto87846742018-04-11 17:36:22 -04004189 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto0a2f98d2017-09-15 19:38:40 -04004190 SPIRVInstList.push_back(Inst);
David Netoa60b00b2017-09-15 16:34:09 -04004191 break;
4192 }
4193
4194 // This is the normal path. Generate a load.
4195
David Neto22f144c2017-06-12 14:26:21 -04004196 // Ops[0] = Result Type ID
4197 // Ops[1] = Pointer ID
4198 // Ops[2] ... Ops[n] = Optional Memory Access
4199 //
4200 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004201
David Neto22f144c2017-06-12 14:26:21 -04004202 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004203 Ops << MkId(ResTyID) << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04004204
David Neto87846742018-04-11 17:36:22 -04004205 auto *Inst = new SPIRVInstruction(spv::OpLoad, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004206 SPIRVInstList.push_back(Inst);
4207 break;
4208 }
4209 case Instruction::Store: {
4210 StoreInst *ST = cast<StoreInst>(&I);
4211 //
4212 // Generate OpStore.
4213 //
4214
alan-baker5b86ed72019-02-15 08:26:50 -05004215 if (ST->getValueOperand()->getType()->isPointerTy()) {
4216 // Storing a pointer requires variable pointers.
4217 setVariablePointersCapabilities(
4218 ST->getValueOperand()->getType()->getPointerAddressSpace());
4219 }
4220
David Neto22f144c2017-06-12 14:26:21 -04004221 // Ops[0] = Pointer ID
4222 // Ops[1] = Object ID
4223 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4224 //
4225 // TODO: Do we need to implement Optional Memory Access???
David Neto257c3892018-04-11 13:19:45 -04004226 SPIRVOperandList Ops;
4227 Ops << MkId(VMap[ST->getPointerOperand()])
4228 << MkId(VMap[ST->getValueOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004229
David Neto87846742018-04-11 17:36:22 -04004230 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004231 SPIRVInstList.push_back(Inst);
4232 break;
4233 }
4234 case Instruction::AtomicCmpXchg: {
4235 I.print(errs());
4236 llvm_unreachable("Unsupported instruction???");
4237 break;
4238 }
4239 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004240 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4241
4242 spv::Op opcode;
4243
4244 switch (AtomicRMW->getOperation()) {
4245 default:
4246 I.print(errs());
4247 llvm_unreachable("Unsupported instruction???");
4248 case llvm::AtomicRMWInst::Add:
4249 opcode = spv::OpAtomicIAdd;
4250 break;
4251 case llvm::AtomicRMWInst::Sub:
4252 opcode = spv::OpAtomicISub;
4253 break;
4254 case llvm::AtomicRMWInst::Xchg:
4255 opcode = spv::OpAtomicExchange;
4256 break;
4257 case llvm::AtomicRMWInst::Min:
4258 opcode = spv::OpAtomicSMin;
4259 break;
4260 case llvm::AtomicRMWInst::Max:
4261 opcode = spv::OpAtomicSMax;
4262 break;
4263 case llvm::AtomicRMWInst::UMin:
4264 opcode = spv::OpAtomicUMin;
4265 break;
4266 case llvm::AtomicRMWInst::UMax:
4267 opcode = spv::OpAtomicUMax;
4268 break;
4269 case llvm::AtomicRMWInst::And:
4270 opcode = spv::OpAtomicAnd;
4271 break;
4272 case llvm::AtomicRMWInst::Or:
4273 opcode = spv::OpAtomicOr;
4274 break;
4275 case llvm::AtomicRMWInst::Xor:
4276 opcode = spv::OpAtomicXor;
4277 break;
4278 }
4279
4280 //
4281 // Generate OpAtomic*.
4282 //
4283 SPIRVOperandList Ops;
4284
David Neto257c3892018-04-11 13:19:45 -04004285 Ops << MkId(lookupType(I.getType()))
4286 << MkId(VMap[AtomicRMW->getPointerOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004287
4288 auto IntTy = Type::getInt32Ty(I.getContext());
Neil Henning39672102017-09-29 14:33:13 +01004289 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
David Neto257c3892018-04-11 13:19:45 -04004290 Ops << MkId(VMap[ConstantScopeDevice]);
Neil Henning39672102017-09-29 14:33:13 +01004291
4292 const auto ConstantMemorySemantics = ConstantInt::get(
4293 IntTy, spv::MemorySemanticsUniformMemoryMask |
4294 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto257c3892018-04-11 13:19:45 -04004295 Ops << MkId(VMap[ConstantMemorySemantics]);
Neil Henning39672102017-09-29 14:33:13 +01004296
David Neto257c3892018-04-11 13:19:45 -04004297 Ops << MkId(VMap[AtomicRMW->getValOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004298
4299 VMap[&I] = nextID;
4300
David Neto87846742018-04-11 17:36:22 -04004301 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
Neil Henning39672102017-09-29 14:33:13 +01004302 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004303 break;
4304 }
4305 case Instruction::Fence: {
4306 I.print(errs());
4307 llvm_unreachable("Unsupported instruction???");
4308 break;
4309 }
4310 case Instruction::Call: {
4311 CallInst *Call = dyn_cast<CallInst>(&I);
4312 Function *Callee = Call->getCalledFunction();
4313
Alan Baker202c8c72018-08-13 13:47:44 -04004314 if (Callee->getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004315 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
4316 // Generate an OpLoad
4317 SPIRVOperandList Ops;
4318 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004319
David Neto862b7d82018-06-14 18:48:37 -04004320 Ops << MkId(lookupType(Call->getType()->getPointerElementType()))
4321 << MkId(ResourceVarDeferredLoadCalls[Call]);
4322
4323 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
4324 SPIRVInstList.push_back(Inst);
4325 VMap[Call] = load_id;
4326 break;
4327
4328 } else {
4329 // This maps to an OpVariable we've already generated.
4330 // No code is generated for the call.
4331 }
4332 break;
alan-bakerb6b09dc2018-11-08 16:59:28 -05004333 } else if (Callee->getName().startswith(
4334 clspv::WorkgroupAccessorFunction())) {
Alan Baker202c8c72018-08-13 13:47:44 -04004335 // Don't codegen an instruction here, but instead map this call directly
4336 // to the workgroup variable id.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004337 int spec_id = static_cast<int>(
4338 cast<ConstantInt>(Call->getOperand(0))->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04004339 const auto &info = LocalSpecIdInfoMap[spec_id];
4340 VMap[Call] = info.variable_id;
4341 break;
David Neto862b7d82018-06-14 18:48:37 -04004342 }
4343
4344 // Sampler initializers become a load of the corresponding sampler.
4345
Kévin Petitdf71de32019-04-09 14:09:50 +01004346 if (Callee->getName().equals(clspv::LiteralSamplerFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004347 // Map this to a load from the variable.
4348 const auto index_into_sampler_map =
4349 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4350
4351 // Generate an OpLoad
David Neto22f144c2017-06-12 14:26:21 -04004352 SPIRVOperandList Ops;
David Neto862b7d82018-06-14 18:48:37 -04004353 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004354
David Neto257c3892018-04-11 13:19:45 -04004355 Ops << MkId(lookupType(SamplerTy->getPointerElementType()))
alan-bakerb6b09dc2018-11-08 16:59:28 -05004356 << MkId(SamplerMapIndexToIDMap[static_cast<unsigned>(
4357 index_into_sampler_map)]);
David Neto22f144c2017-06-12 14:26:21 -04004358
David Neto862b7d82018-06-14 18:48:37 -04004359 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004360 SPIRVInstList.push_back(Inst);
David Neto862b7d82018-06-14 18:48:37 -04004361 VMap[Call] = load_id;
David Neto22f144c2017-06-12 14:26:21 -04004362 break;
4363 }
4364
Kévin Petit349c9502019-03-28 17:24:14 +00004365 // Handle SPIR-V intrinsics
Kévin Petit9b340262019-06-19 18:31:11 +01004366 spv::Op opcode = StringSwitch<spv::Op>(Callee->getName())
4367 .Case("spirv.atomic_xor", spv::OpAtomicXor)
4368 .Default(spv::OpNop);
David Neto22f144c2017-06-12 14:26:21 -04004369
Kévin Petit617a76d2019-04-04 13:54:16 +01004370 // If the switch above didn't have an entry maybe the intrinsic
4371 // is using the name mangling logic.
4372 bool usesMangler = false;
4373 if (opcode == spv::OpNop) {
4374 if (Callee->getName().startswith(clspv::SPIRVOpIntrinsicFunction())) {
4375 auto OpCst = cast<ConstantInt>(Call->getOperand(0));
4376 opcode = static_cast<spv::Op>(OpCst->getZExtValue());
4377 usesMangler = true;
4378 }
4379 }
4380
Kévin Petit349c9502019-03-28 17:24:14 +00004381 if (opcode != spv::OpNop) {
4382
David Neto22f144c2017-06-12 14:26:21 -04004383 SPIRVOperandList Ops;
4384
Kévin Petit349c9502019-03-28 17:24:14 +00004385 if (!I.getType()->isVoidTy()) {
4386 Ops << MkId(lookupType(I.getType()));
4387 }
David Neto22f144c2017-06-12 14:26:21 -04004388
Kévin Petit617a76d2019-04-04 13:54:16 +01004389 unsigned firstOperand = usesMangler ? 1 : 0;
4390 for (unsigned i = firstOperand; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004391 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004392 }
4393
Kévin Petit349c9502019-03-28 17:24:14 +00004394 if (!I.getType()->isVoidTy()) {
4395 VMap[&I] = nextID;
Kévin Petit8a560882019-03-21 15:24:34 +00004396 }
4397
Kévin Petit349c9502019-03-28 17:24:14 +00004398 SPIRVInstruction *Inst;
4399 if (!I.getType()->isVoidTy()) {
4400 Inst = new SPIRVInstruction(opcode, nextID++, Ops);
4401 } else {
4402 Inst = new SPIRVInstruction(opcode, Ops);
4403 }
Kévin Petit8a560882019-03-21 15:24:34 +00004404 SPIRVInstList.push_back(Inst);
4405 break;
4406 }
4407
David Neto8505ebf2017-10-13 18:50:50 -04004408 if (Callee->getName().startswith("_Z4fmod")) {
4409 // OpenCL fmod(x,y) is x - y * trunc(x/y)
4410 // The sign for a non-zero result is taken from x.
4411 // (Try an example.)
4412 // So translate to OpFRem
4413
4414 SPIRVOperandList Ops;
4415
David Neto257c3892018-04-11 13:19:45 -04004416 Ops << MkId(lookupType(I.getType()));
David Neto8505ebf2017-10-13 18:50:50 -04004417
4418 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004419 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto8505ebf2017-10-13 18:50:50 -04004420 }
4421
4422 VMap[&I] = nextID;
4423
David Neto87846742018-04-11 17:36:22 -04004424 auto *Inst = new SPIRVInstruction(spv::OpFRem, nextID++, Ops);
David Neto8505ebf2017-10-13 18:50:50 -04004425 SPIRVInstList.push_back(Inst);
4426 break;
4427 }
4428
David Neto22f144c2017-06-12 14:26:21 -04004429 // spirv.copy_memory.* intrinsics become OpMemoryMemory's.
4430 if (Callee->getName().startswith("spirv.copy_memory")) {
4431 //
4432 // Generate OpCopyMemory.
4433 //
4434
4435 // Ops[0] = Dst ID
4436 // Ops[1] = Src ID
4437 // Ops[2] = Memory Access
4438 // Ops[3] = Alignment
4439
4440 auto IsVolatile =
4441 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
4442
4443 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
4444 : spv::MemoryAccessMaskNone;
4445
4446 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
4447
4448 auto Alignment =
4449 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4450
David Neto257c3892018-04-11 13:19:45 -04004451 SPIRVOperandList Ops;
4452 Ops << MkId(VMap[Call->getArgOperand(0)])
4453 << MkId(VMap[Call->getArgOperand(1)]) << MkNum(MemoryAccess)
4454 << MkNum(static_cast<uint32_t>(Alignment));
David Neto22f144c2017-06-12 14:26:21 -04004455
David Neto87846742018-04-11 17:36:22 -04004456 auto *Inst = new SPIRVInstruction(spv::OpCopyMemory, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004457
4458 SPIRVInstList.push_back(Inst);
4459
4460 break;
4461 }
4462
David Neto22f144c2017-06-12 14:26:21 -04004463 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
4464 // Additionally, OpTypeSampledImage is generated.
4465 if (Callee->getName().equals(
4466 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
4467 Callee->getName().equals(
4468 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
4469 //
4470 // Generate OpSampledImage.
4471 //
4472 // Ops[0] = Result Type ID
4473 // Ops[1] = Image ID
4474 // Ops[2] = Sampler ID
4475 //
4476 SPIRVOperandList Ops;
4477
4478 Value *Image = Call->getArgOperand(0);
4479 Value *Sampler = Call->getArgOperand(1);
4480 Value *Coordinate = Call->getArgOperand(2);
4481
4482 TypeMapType &OpImageTypeMap = getImageTypeMap();
4483 Type *ImageTy = Image->getType()->getPointerElementType();
4484 uint32_t ImageTyID = OpImageTypeMap[ImageTy];
David Neto22f144c2017-06-12 14:26:21 -04004485 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004486 uint32_t SamplerID = VMap[Sampler];
David Neto257c3892018-04-11 13:19:45 -04004487
4488 Ops << MkId(ImageTyID) << MkId(ImageID) << MkId(SamplerID);
David Neto22f144c2017-06-12 14:26:21 -04004489
4490 uint32_t SampledImageID = nextID;
4491
David Neto87846742018-04-11 17:36:22 -04004492 auto *Inst = new SPIRVInstruction(spv::OpSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004493 SPIRVInstList.push_back(Inst);
4494
4495 //
4496 // Generate OpImageSampleExplicitLod.
4497 //
4498 // Ops[0] = Result Type ID
4499 // Ops[1] = Sampled Image ID
4500 // Ops[2] = Coordinate ID
4501 // Ops[3] = Image Operands Type ID
4502 // Ops[4] ... Ops[n] = Operands ID
4503 //
4504 Ops.clear();
4505
David Neto257c3892018-04-11 13:19:45 -04004506 Ops << MkId(lookupType(Call->getType())) << MkId(SampledImageID)
4507 << MkId(VMap[Coordinate]) << MkNum(spv::ImageOperandsLodMask);
David Neto22f144c2017-06-12 14:26:21 -04004508
4509 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
David Neto257c3892018-04-11 13:19:45 -04004510 Ops << MkId(VMap[CstFP0]);
David Neto22f144c2017-06-12 14:26:21 -04004511
4512 VMap[&I] = nextID;
4513
David Neto87846742018-04-11 17:36:22 -04004514 Inst = new SPIRVInstruction(spv::OpImageSampleExplicitLod, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004515 SPIRVInstList.push_back(Inst);
4516 break;
4517 }
4518
4519 // write_imagef is mapped to OpImageWrite.
4520 if (Callee->getName().equals(
4521 "_Z12write_imagef14ocl_image2d_woDv2_iDv4_f") ||
4522 Callee->getName().equals(
4523 "_Z12write_imagef14ocl_image3d_woDv4_iDv4_f")) {
4524 //
4525 // Generate OpImageWrite.
4526 //
4527 // Ops[0] = Image ID
4528 // Ops[1] = Coordinate ID
4529 // Ops[2] = Texel ID
4530 // Ops[3] = (Optional) Image Operands Type (Literal Number)
4531 // Ops[4] ... Ops[n] = (Optional) Operands ID
4532 //
4533 SPIRVOperandList Ops;
4534
4535 Value *Image = Call->getArgOperand(0);
4536 Value *Coordinate = Call->getArgOperand(1);
4537 Value *Texel = Call->getArgOperand(2);
4538
4539 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004540 uint32_t CoordinateID = VMap[Coordinate];
David Neto22f144c2017-06-12 14:26:21 -04004541 uint32_t TexelID = VMap[Texel];
David Neto257c3892018-04-11 13:19:45 -04004542 Ops << MkId(ImageID) << MkId(CoordinateID) << MkId(TexelID);
David Neto22f144c2017-06-12 14:26:21 -04004543
David Neto87846742018-04-11 17:36:22 -04004544 auto *Inst = new SPIRVInstruction(spv::OpImageWrite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004545 SPIRVInstList.push_back(Inst);
4546 break;
4547 }
4548
David Neto5c22a252018-03-15 16:07:41 -04004549 // get_image_width is mapped to OpImageQuerySize
4550 if (Callee->getName().equals("_Z15get_image_width14ocl_image2d_ro") ||
4551 Callee->getName().equals("_Z15get_image_width14ocl_image2d_wo") ||
4552 Callee->getName().equals("_Z16get_image_height14ocl_image2d_ro") ||
4553 Callee->getName().equals("_Z16get_image_height14ocl_image2d_wo")) {
4554 //
4555 // Generate OpImageQuerySize, then pull out the right component.
4556 // Assume 2D image for now.
4557 //
4558 // Ops[0] = Image ID
4559 //
4560 // %sizes = OpImageQuerySizes %uint2 %im
4561 // %result = OpCompositeExtract %uint %sizes 0-or-1
4562 SPIRVOperandList Ops;
4563
4564 // Implement:
4565 // %sizes = OpImageQuerySizes %uint2 %im
4566 uint32_t SizesTypeID =
4567 TypeMap[VectorType::get(Type::getInt32Ty(Context), 2)];
David Neto5c22a252018-03-15 16:07:41 -04004568 Value *Image = Call->getArgOperand(0);
4569 uint32_t ImageID = VMap[Image];
David Neto257c3892018-04-11 13:19:45 -04004570 Ops << MkId(SizesTypeID) << MkId(ImageID);
David Neto5c22a252018-03-15 16:07:41 -04004571
4572 uint32_t SizesID = nextID++;
David Neto87846742018-04-11 17:36:22 -04004573 auto *QueryInst =
4574 new SPIRVInstruction(spv::OpImageQuerySize, SizesID, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004575 SPIRVInstList.push_back(QueryInst);
4576
4577 // Reset value map entry since we generated an intermediate instruction.
4578 VMap[&I] = nextID;
4579
4580 // Implement:
4581 // %result = OpCompositeExtract %uint %sizes 0-or-1
4582 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004583 Ops << MkId(TypeMap[I.getType()]) << MkId(SizesID);
David Neto5c22a252018-03-15 16:07:41 -04004584
4585 uint32_t component = Callee->getName().contains("height") ? 1 : 0;
David Neto257c3892018-04-11 13:19:45 -04004586 Ops << MkNum(component);
David Neto5c22a252018-03-15 16:07:41 -04004587
David Neto87846742018-04-11 17:36:22 -04004588 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004589 SPIRVInstList.push_back(Inst);
4590 break;
4591 }
4592
David Neto22f144c2017-06-12 14:26:21 -04004593 // Call instrucion is deferred because it needs function's ID. Record
4594 // slot's location on SPIRVInstructionList.
4595 DeferredInsts.push_back(
4596 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4597
David Neto3fbb4072017-10-16 11:28:14 -04004598 // Check whether the implementation of this call uses an extended
4599 // instruction plus one more value-producing instruction. If so, then
4600 // reserve the id for the extra value-producing slot.
4601 glsl::ExtInst EInst = getIndirectExtInstEnum(Callee->getName());
4602 if (EInst != kGlslExtInstBad) {
4603 // Reserve a spot for the extra value.
David Neto4d02a532017-09-17 12:57:44 -04004604 // Increase nextID.
David Neto22f144c2017-06-12 14:26:21 -04004605 VMap[&I] = nextID;
4606 nextID++;
4607 }
4608 break;
4609 }
4610 case Instruction::Ret: {
4611 unsigned NumOps = I.getNumOperands();
4612 if (NumOps == 0) {
4613 //
4614 // Generate OpReturn.
4615 //
David Neto87846742018-04-11 17:36:22 -04004616 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpReturn, {}));
David Neto22f144c2017-06-12 14:26:21 -04004617 } else {
4618 //
4619 // Generate OpReturnValue.
4620 //
4621
4622 // Ops[0] = Return Value ID
4623 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004624
4625 Ops << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004626
David Neto87846742018-04-11 17:36:22 -04004627 auto *Inst = new SPIRVInstruction(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004628 SPIRVInstList.push_back(Inst);
4629 break;
4630 }
4631 break;
4632 }
4633 }
4634}
4635
4636void SPIRVProducerPass::GenerateFuncEpilogue() {
4637 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4638
4639 //
4640 // Generate OpFunctionEnd
4641 //
4642
David Neto87846742018-04-11 17:36:22 -04004643 auto *Inst = new SPIRVInstruction(spv::OpFunctionEnd, {});
David Neto22f144c2017-06-12 14:26:21 -04004644 SPIRVInstList.push_back(Inst);
4645}
4646
4647bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
alan-bakerb39c8262019-03-08 14:03:37 -05004648 // Don't specialize <4 x i8> if i8 is generally supported.
4649 if (clspv::Option::Int8Support())
4650 return false;
4651
David Neto22f144c2017-06-12 14:26:21 -04004652 LLVMContext &Context = Ty->getContext();
4653 if (Ty->isVectorTy()) {
4654 if (Ty->getVectorElementType() == Type::getInt8Ty(Context) &&
4655 Ty->getVectorNumElements() == 4) {
4656 return true;
4657 }
4658 }
4659
4660 return false;
4661}
4662
4663void SPIRVProducerPass::HandleDeferredInstruction() {
4664 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4665 ValueMapType &VMap = getValueMap();
4666 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4667
4668 for (auto DeferredInst = DeferredInsts.rbegin();
4669 DeferredInst != DeferredInsts.rend(); ++DeferredInst) {
4670 Value *Inst = std::get<0>(*DeferredInst);
4671 SPIRVInstructionList::iterator InsertPoint = ++std::get<1>(*DeferredInst);
4672 if (InsertPoint != SPIRVInstList.end()) {
4673 while ((*InsertPoint)->getOpcode() == spv::OpPhi) {
4674 ++InsertPoint;
4675 }
4676 }
4677
4678 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
4679 // Check whether basic block, which has this branch instruction, is loop
4680 // header or not. If it is loop header, generate OpLoopMerge and
4681 // OpBranchConditional.
4682 Function *Func = Br->getParent()->getParent();
4683 DominatorTree &DT =
4684 getAnalysis<DominatorTreeWrapperPass>(*Func).getDomTree();
4685 const LoopInfo &LI =
4686 getAnalysis<LoopInfoWrapperPass>(*Func).getLoopInfo();
4687
4688 BasicBlock *BrBB = Br->getParent();
alan-baker49531082019-06-05 17:30:56 -04004689 Loop *L = LI.getLoopFor(BrBB);
David Neto22f144c2017-06-12 14:26:21 -04004690 if (LI.isLoopHeader(BrBB)) {
4691 Value *ContinueBB = nullptr;
4692 Value *MergeBB = nullptr;
4693
David Neto22f144c2017-06-12 14:26:21 -04004694 MergeBB = L->getExitBlock();
4695 if (!MergeBB) {
4696 // StructurizeCFG pass converts CFG into triangle shape and the cfg
4697 // has regions with single entry/exit. As a result, loop should not
4698 // have multiple exits.
4699 llvm_unreachable("Loop has multiple exits???");
4700 }
4701
4702 if (L->isLoopLatch(BrBB)) {
4703 ContinueBB = BrBB;
4704 } else {
4705 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
4706 // block.
4707 BasicBlock *Header = L->getHeader();
4708 BasicBlock *Latch = L->getLoopLatch();
4709 for (BasicBlock *BB : L->blocks()) {
4710 if (BB == Header) {
4711 continue;
4712 }
4713
4714 // Check whether block dominates block with back-edge.
4715 if (DT.dominates(BB, Latch)) {
4716 ContinueBB = BB;
4717 }
4718 }
4719
4720 if (!ContinueBB) {
4721 llvm_unreachable("Wrong continue block from loop");
4722 }
4723 }
4724
4725 //
4726 // Generate OpLoopMerge.
4727 //
4728 // Ops[0] = Merge Block ID
4729 // Ops[1] = Continue Target ID
4730 // Ops[2] = Selection Control
4731 SPIRVOperandList Ops;
4732
4733 // StructurizeCFG pass already manipulated CFG. Just use false block of
4734 // branch instruction as merge block.
4735 uint32_t MergeBBID = VMap[MergeBB];
David Neto22f144c2017-06-12 14:26:21 -04004736 uint32_t ContinueBBID = VMap[ContinueBB];
David Neto257c3892018-04-11 13:19:45 -04004737 Ops << MkId(MergeBBID) << MkId(ContinueBBID)
4738 << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004739
David Neto87846742018-04-11 17:36:22 -04004740 auto *MergeInst = new SPIRVInstruction(spv::OpLoopMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004741 SPIRVInstList.insert(InsertPoint, MergeInst);
4742
4743 } else if (Br->isConditional()) {
alan-baker49531082019-06-05 17:30:56 -04004744 // Generate a selection merge unless this is a back-edge block.
4745 bool HasBackedge = false;
4746 while (L && !HasBackedge) {
4747 if (L->isLoopLatch(BrBB)) {
4748 HasBackedge = true;
David Neto22f144c2017-06-12 14:26:21 -04004749 }
alan-baker49531082019-06-05 17:30:56 -04004750 L = L->getParentLoop();
David Neto22f144c2017-06-12 14:26:21 -04004751 }
alan-baker49531082019-06-05 17:30:56 -04004752 if (!HasBackedge) {
David Neto22f144c2017-06-12 14:26:21 -04004753 //
4754 // Generate OpSelectionMerge.
4755 //
4756 // Ops[0] = Merge Block ID
4757 // Ops[1] = Selection Control
4758 SPIRVOperandList Ops;
4759
4760 // StructurizeCFG pass already manipulated CFG. Just use false block
4761 // of branch instruction as merge block.
4762 uint32_t MergeBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004763 Ops << MkId(MergeBBID) << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004764
David Neto87846742018-04-11 17:36:22 -04004765 auto *MergeInst = new SPIRVInstruction(spv::OpSelectionMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004766 SPIRVInstList.insert(InsertPoint, MergeInst);
4767 }
4768 }
4769
4770 if (Br->isConditional()) {
4771 //
4772 // Generate OpBranchConditional.
4773 //
4774 // Ops[0] = Condition ID
4775 // Ops[1] = True Label ID
4776 // Ops[2] = False Label ID
4777 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
4778 SPIRVOperandList Ops;
4779
4780 uint32_t CondID = VMap[Br->getCondition()];
David Neto22f144c2017-06-12 14:26:21 -04004781 uint32_t TrueBBID = VMap[Br->getSuccessor(0)];
David Neto22f144c2017-06-12 14:26:21 -04004782 uint32_t FalseBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004783
4784 Ops << MkId(CondID) << MkId(TrueBBID) << MkId(FalseBBID);
David Neto22f144c2017-06-12 14:26:21 -04004785
David Neto87846742018-04-11 17:36:22 -04004786 auto *BrInst = new SPIRVInstruction(spv::OpBranchConditional, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004787 SPIRVInstList.insert(InsertPoint, BrInst);
4788 } else {
4789 //
4790 // Generate OpBranch.
4791 //
4792 // Ops[0] = Target Label ID
4793 SPIRVOperandList Ops;
4794
4795 uint32_t TargetID = VMap[Br->getSuccessor(0)];
David Neto257c3892018-04-11 13:19:45 -04004796 Ops << MkId(TargetID);
David Neto22f144c2017-06-12 14:26:21 -04004797
David Neto87846742018-04-11 17:36:22 -04004798 SPIRVInstList.insert(InsertPoint,
4799 new SPIRVInstruction(spv::OpBranch, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004800 }
4801 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
alan-baker5b86ed72019-02-15 08:26:50 -05004802 if (PHI->getType()->isPointerTy()) {
4803 // OpPhi on pointers requires variable pointers.
4804 setVariablePointersCapabilities(
4805 PHI->getType()->getPointerAddressSpace());
4806 if (!hasVariablePointers() && !selectFromSameObject(PHI)) {
4807 setVariablePointers(true);
4808 }
4809 }
4810
David Neto22f144c2017-06-12 14:26:21 -04004811 //
4812 // Generate OpPhi.
4813 //
4814 // Ops[0] = Result Type ID
4815 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
4816 SPIRVOperandList Ops;
4817
David Neto257c3892018-04-11 13:19:45 -04004818 Ops << MkId(lookupType(PHI->getType()));
David Neto22f144c2017-06-12 14:26:21 -04004819
David Neto22f144c2017-06-12 14:26:21 -04004820 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
4821 uint32_t VarID = VMap[PHI->getIncomingValue(i)];
David Neto22f144c2017-06-12 14:26:21 -04004822 uint32_t ParentID = VMap[PHI->getIncomingBlock(i)];
David Neto257c3892018-04-11 13:19:45 -04004823 Ops << MkId(VarID) << MkId(ParentID);
David Neto22f144c2017-06-12 14:26:21 -04004824 }
4825
4826 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04004827 InsertPoint,
4828 new SPIRVInstruction(spv::OpPhi, std::get<2>(*DeferredInst), Ops));
David Neto22f144c2017-06-12 14:26:21 -04004829 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
4830 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04004831 auto callee_name = Callee->getName();
4832 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04004833
4834 if (EInst) {
4835 uint32_t &ExtInstImportID = getOpExtInstImportID();
4836
4837 //
4838 // Generate OpExtInst.
4839 //
4840
4841 // Ops[0] = Result Type ID
4842 // Ops[1] = Set ID (OpExtInstImport ID)
4843 // Ops[2] = Instruction Number (Literal Number)
4844 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
4845 SPIRVOperandList Ops;
4846
David Neto862b7d82018-06-14 18:48:37 -04004847 Ops << MkId(lookupType(Call->getType())) << MkId(ExtInstImportID)
4848 << MkNum(EInst);
David Neto22f144c2017-06-12 14:26:21 -04004849
David Neto22f144c2017-06-12 14:26:21 -04004850 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
4851 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004852 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004853 }
4854
David Neto87846742018-04-11 17:36:22 -04004855 auto *ExtInst = new SPIRVInstruction(spv::OpExtInst,
4856 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04004857 SPIRVInstList.insert(InsertPoint, ExtInst);
4858
David Neto3fbb4072017-10-16 11:28:14 -04004859 const auto IndirectExtInst = getIndirectExtInstEnum(callee_name);
4860 if (IndirectExtInst != kGlslExtInstBad) {
4861 // Generate one more instruction that uses the result of the extended
4862 // instruction. Its result id is one more than the id of the
4863 // extended instruction.
David Neto22f144c2017-06-12 14:26:21 -04004864 LLVMContext &Context =
4865 Call->getParent()->getParent()->getParent()->getContext();
David Neto22f144c2017-06-12 14:26:21 -04004866
David Neto3fbb4072017-10-16 11:28:14 -04004867 auto generate_extra_inst = [this, &Context, &Call, &DeferredInst,
4868 &VMap, &SPIRVInstList, &InsertPoint](
4869 spv::Op opcode, Constant *constant) {
4870 //
4871 // Generate instruction like:
4872 // result = opcode constant <extinst-result>
4873 //
4874 // Ops[0] = Result Type ID
4875 // Ops[1] = Operand 0 ;; the constant, suitably splatted
4876 // Ops[2] = Operand 1 ;; the result of the extended instruction
4877 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004878
David Neto3fbb4072017-10-16 11:28:14 -04004879 Type *resultTy = Call->getType();
David Neto257c3892018-04-11 13:19:45 -04004880 Ops << MkId(lookupType(resultTy));
David Neto3fbb4072017-10-16 11:28:14 -04004881
4882 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
4883 constant = ConstantVector::getSplat(
4884 static_cast<unsigned>(vectorTy->getNumElements()), constant);
4885 }
David Neto257c3892018-04-11 13:19:45 -04004886 Ops << MkId(VMap[constant]) << MkId(std::get<2>(*DeferredInst));
David Neto3fbb4072017-10-16 11:28:14 -04004887
4888 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04004889 InsertPoint, new SPIRVInstruction(
4890 opcode, std::get<2>(*DeferredInst) + 1, Ops));
David Neto3fbb4072017-10-16 11:28:14 -04004891 };
4892
4893 switch (IndirectExtInst) {
4894 case glsl::ExtInstFindUMsb: // Implementing clz
4895 generate_extra_inst(
4896 spv::OpISub, ConstantInt::get(Type::getInt32Ty(Context), 31));
4897 break;
4898 case glsl::ExtInstAcos: // Implementing acospi
4899 case glsl::ExtInstAsin: // Implementing asinpi
Kévin Petiteb9f90a2018-09-29 12:29:34 +01004900 case glsl::ExtInstAtan: // Implementing atanpi
David Neto3fbb4072017-10-16 11:28:14 -04004901 case glsl::ExtInstAtan2: // Implementing atan2pi
4902 generate_extra_inst(
4903 spv::OpFMul,
4904 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
4905 break;
4906
4907 default:
4908 assert(false && "internally inconsistent");
David Neto4d02a532017-09-17 12:57:44 -04004909 }
David Neto22f144c2017-06-12 14:26:21 -04004910 }
David Neto3fbb4072017-10-16 11:28:14 -04004911
alan-bakerb39c8262019-03-08 14:03:37 -05004912 } else if (callee_name.startswith("_Z8popcount")) {
David Neto22f144c2017-06-12 14:26:21 -04004913 //
4914 // Generate OpBitCount
4915 //
4916 // Ops[0] = Result Type ID
4917 // Ops[1] = Base ID
David Neto257c3892018-04-11 13:19:45 -04004918 SPIRVOperandList Ops;
4919 Ops << MkId(lookupType(Call->getType()))
4920 << MkId(VMap[Call->getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004921
4922 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04004923 InsertPoint, new SPIRVInstruction(spv::OpBitCount,
David Neto22f144c2017-06-12 14:26:21 -04004924 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04004925
David Neto862b7d82018-06-14 18:48:37 -04004926 } else if (callee_name.startswith(kCompositeConstructFunctionPrefix)) {
David Netoab03f432017-11-03 17:00:44 -04004927
4928 // Generate an OpCompositeConstruct
4929 SPIRVOperandList Ops;
4930
4931 // The result type.
David Neto257c3892018-04-11 13:19:45 -04004932 Ops << MkId(lookupType(Call->getType()));
David Netoab03f432017-11-03 17:00:44 -04004933
4934 for (Use &use : Call->arg_operands()) {
David Neto257c3892018-04-11 13:19:45 -04004935 Ops << MkId(VMap[use.get()]);
David Netoab03f432017-11-03 17:00:44 -04004936 }
4937
4938 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04004939 InsertPoint, new SPIRVInstruction(spv::OpCompositeConstruct,
4940 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04004941
Alan Baker202c8c72018-08-13 13:47:44 -04004942 } else if (callee_name.startswith(clspv::ResourceAccessorFunction())) {
4943
4944 // We have already mapped the call's result value to an ID.
4945 // Don't generate any code now.
4946
4947 } else if (callee_name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004948
4949 // We have already mapped the call's result value to an ID.
4950 // Don't generate any code now.
4951
David Neto22f144c2017-06-12 14:26:21 -04004952 } else {
alan-baker5b86ed72019-02-15 08:26:50 -05004953 if (Call->getType()->isPointerTy()) {
4954 // Functions returning pointers require variable pointers.
4955 setVariablePointersCapabilities(
4956 Call->getType()->getPointerAddressSpace());
4957 }
4958
David Neto22f144c2017-06-12 14:26:21 -04004959 //
4960 // Generate OpFunctionCall.
4961 //
4962
4963 // Ops[0] = Result Type ID
4964 // Ops[1] = Callee Function ID
4965 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
4966 SPIRVOperandList Ops;
4967
David Neto862b7d82018-06-14 18:48:37 -04004968 Ops << MkId(lookupType(Call->getType()));
David Neto22f144c2017-06-12 14:26:21 -04004969
4970 uint32_t CalleeID = VMap[Callee];
David Neto43568eb2017-10-13 18:25:25 -04004971 if (CalleeID == 0) {
4972 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04004973 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04004974 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
4975 // causes an infinite loop. Instead, go ahead and generate
4976 // the bad function call. A validator will catch the 0-Id.
4977 // llvm_unreachable("Can't translate function call");
4978 }
David Neto22f144c2017-06-12 14:26:21 -04004979
David Neto257c3892018-04-11 13:19:45 -04004980 Ops << MkId(CalleeID);
David Neto22f144c2017-06-12 14:26:21 -04004981
David Neto22f144c2017-06-12 14:26:21 -04004982 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
4983 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
alan-baker5b86ed72019-02-15 08:26:50 -05004984 auto *operand = Call->getOperand(i);
4985 if (operand->getType()->isPointerTy()) {
4986 auto sc =
4987 GetStorageClass(operand->getType()->getPointerAddressSpace());
4988 if (sc == spv::StorageClassStorageBuffer) {
4989 // Passing SSBO by reference requires variable pointers storage
4990 // buffer.
4991 setVariablePointersStorageBuffer(true);
4992 } else if (sc == spv::StorageClassWorkgroup) {
4993 // Workgroup references require variable pointers if they are not
4994 // memory object declarations.
4995 if (auto *operand_call = dyn_cast<CallInst>(operand)) {
4996 // Workgroup accessor represents a variable reference.
4997 if (!operand_call->getCalledFunction()->getName().startswith(
4998 clspv::WorkgroupAccessorFunction()))
4999 setVariablePointers(true);
5000 } else {
5001 // Arguments are function parameters.
5002 if (!isa<Argument>(operand))
5003 setVariablePointers(true);
5004 }
5005 }
5006 }
5007 Ops << MkId(VMap[operand]);
David Neto22f144c2017-06-12 14:26:21 -04005008 }
5009
David Neto87846742018-04-11 17:36:22 -04005010 auto *CallInst = new SPIRVInstruction(spv::OpFunctionCall,
5011 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005012 SPIRVInstList.insert(InsertPoint, CallInst);
5013 }
5014 }
5015 }
5016}
5017
David Neto1a1a0582017-07-07 12:01:44 -04005018void SPIRVProducerPass::HandleDeferredDecorations(const DataLayout &DL) {
Alan Baker202c8c72018-08-13 13:47:44 -04005019 if (getTypesNeedingArrayStride().empty() && LocalArgSpecIds.empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04005020 return;
David Netoc6f3ab22018-04-06 18:02:31 -04005021 }
David Neto1a1a0582017-07-07 12:01:44 -04005022
5023 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto1a1a0582017-07-07 12:01:44 -04005024
5025 // Find an iterator pointing just past the last decoration.
5026 bool seen_decorations = false;
5027 auto DecoInsertPoint =
5028 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
5029 [&seen_decorations](SPIRVInstruction *Inst) -> bool {
5030 const bool is_decoration =
5031 Inst->getOpcode() == spv::OpDecorate ||
5032 Inst->getOpcode() == spv::OpMemberDecorate;
5033 if (is_decoration) {
5034 seen_decorations = true;
5035 return false;
5036 } else {
5037 return seen_decorations;
5038 }
5039 });
5040
David Netoc6f3ab22018-04-06 18:02:31 -04005041 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
5042 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07005043 for (auto *type : getTypesNeedingArrayStride()) {
5044 Type *elemTy = nullptr;
5045 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
5046 elemTy = ptrTy->getElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005047 } else if (auto *arrayTy = dyn_cast<ArrayType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005048 elemTy = arrayTy->getArrayElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005049 } else if (auto *seqTy = dyn_cast<SequentialType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005050 elemTy = seqTy->getSequentialElementType();
5051 } else {
5052 errs() << "Unhandled strided type " << *type << "\n";
5053 llvm_unreachable("Unhandled strided type");
5054 }
David Neto1a1a0582017-07-07 12:01:44 -04005055
5056 // Ops[0] = Target ID
5057 // Ops[1] = Decoration (ArrayStride)
5058 // Ops[2] = Stride number (Literal Number)
5059 SPIRVOperandList Ops;
5060
David Neto85082642018-03-24 06:55:20 -07005061 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Alan Bakerfcda9482018-10-02 17:09:59 -04005062 const uint32_t stride = static_cast<uint32_t>(GetTypeAllocSize(elemTy, DL));
David Neto257c3892018-04-11 13:19:45 -04005063
5064 Ops << MkId(lookupType(type)) << MkNum(spv::DecorationArrayStride)
5065 << MkNum(stride);
David Neto1a1a0582017-07-07 12:01:44 -04005066
David Neto87846742018-04-11 17:36:22 -04005067 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto1a1a0582017-07-07 12:01:44 -04005068 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
5069 }
David Netoc6f3ab22018-04-06 18:02:31 -04005070
5071 // Emit SpecId decorations targeting the array size value.
Alan Baker202c8c72018-08-13 13:47:44 -04005072 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
5073 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005074 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04005075 SPIRVOperandList Ops;
5076 Ops << MkId(arg_info.array_size_id) << MkNum(spv::DecorationSpecId)
5077 << MkNum(arg_info.spec_id);
5078 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04005079 new SPIRVInstruction(spv::OpDecorate, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04005080 }
David Neto1a1a0582017-07-07 12:01:44 -04005081}
5082
David Neto22f144c2017-06-12 14:26:21 -04005083glsl::ExtInst SPIRVProducerPass::getExtInstEnum(StringRef Name) {
5084 return StringSwitch<glsl::ExtInst>(Name)
alan-bakerb39c8262019-03-08 14:03:37 -05005085 .Case("_Z3absc", glsl::ExtInst::ExtInstSAbs)
5086 .Case("_Z3absDv2_c", glsl::ExtInst::ExtInstSAbs)
5087 .Case("_Z3absDv3_c", glsl::ExtInst::ExtInstSAbs)
5088 .Case("_Z3absDv4_c", glsl::ExtInst::ExtInstSAbs)
Kévin Petit2444e9b2018-11-09 14:14:37 +00005089 .Case("_Z3abss", glsl::ExtInst::ExtInstSAbs)
5090 .Case("_Z3absDv2_s", glsl::ExtInst::ExtInstSAbs)
5091 .Case("_Z3absDv3_s", glsl::ExtInst::ExtInstSAbs)
5092 .Case("_Z3absDv4_s", glsl::ExtInst::ExtInstSAbs)
David Neto22f144c2017-06-12 14:26:21 -04005093 .Case("_Z3absi", glsl::ExtInst::ExtInstSAbs)
5094 .Case("_Z3absDv2_i", glsl::ExtInst::ExtInstSAbs)
5095 .Case("_Z3absDv3_i", glsl::ExtInst::ExtInstSAbs)
5096 .Case("_Z3absDv4_i", glsl::ExtInst::ExtInstSAbs)
Kévin Petit2444e9b2018-11-09 14:14:37 +00005097 .Case("_Z3absl", glsl::ExtInst::ExtInstSAbs)
5098 .Case("_Z3absDv2_l", glsl::ExtInst::ExtInstSAbs)
5099 .Case("_Z3absDv3_l", glsl::ExtInst::ExtInstSAbs)
5100 .Case("_Z3absDv4_l", glsl::ExtInst::ExtInstSAbs)
alan-bakerb39c8262019-03-08 14:03:37 -05005101 .Case("_Z5clampccc", glsl::ExtInst::ExtInstSClamp)
5102 .Case("_Z5clampDv2_cS_S_", glsl::ExtInst::ExtInstSClamp)
5103 .Case("_Z5clampDv3_cS_S_", glsl::ExtInst::ExtInstSClamp)
5104 .Case("_Z5clampDv4_cS_S_", glsl::ExtInst::ExtInstSClamp)
5105 .Case("_Z5clamphhh", glsl::ExtInst::ExtInstUClamp)
5106 .Case("_Z5clampDv2_hS_S_", glsl::ExtInst::ExtInstUClamp)
5107 .Case("_Z5clampDv3_hS_S_", glsl::ExtInst::ExtInstUClamp)
5108 .Case("_Z5clampDv4_hS_S_", glsl::ExtInst::ExtInstUClamp)
Kévin Petit495255d2019-03-06 13:56:48 +00005109 .Case("_Z5clampsss", glsl::ExtInst::ExtInstSClamp)
5110 .Case("_Z5clampDv2_sS_S_", glsl::ExtInst::ExtInstSClamp)
5111 .Case("_Z5clampDv3_sS_S_", glsl::ExtInst::ExtInstSClamp)
5112 .Case("_Z5clampDv4_sS_S_", glsl::ExtInst::ExtInstSClamp)
5113 .Case("_Z5clampttt", glsl::ExtInst::ExtInstUClamp)
5114 .Case("_Z5clampDv2_tS_S_", glsl::ExtInst::ExtInstUClamp)
5115 .Case("_Z5clampDv3_tS_S_", glsl::ExtInst::ExtInstUClamp)
5116 .Case("_Z5clampDv4_tS_S_", glsl::ExtInst::ExtInstUClamp)
David Neto22f144c2017-06-12 14:26:21 -04005117 .Case("_Z5clampiii", glsl::ExtInst::ExtInstSClamp)
5118 .Case("_Z5clampDv2_iS_S_", glsl::ExtInst::ExtInstSClamp)
5119 .Case("_Z5clampDv3_iS_S_", glsl::ExtInst::ExtInstSClamp)
5120 .Case("_Z5clampDv4_iS_S_", glsl::ExtInst::ExtInstSClamp)
5121 .Case("_Z5clampjjj", glsl::ExtInst::ExtInstUClamp)
5122 .Case("_Z5clampDv2_jS_S_", glsl::ExtInst::ExtInstUClamp)
5123 .Case("_Z5clampDv3_jS_S_", glsl::ExtInst::ExtInstUClamp)
5124 .Case("_Z5clampDv4_jS_S_", glsl::ExtInst::ExtInstUClamp)
Kévin Petit495255d2019-03-06 13:56:48 +00005125 .Case("_Z5clamplll", glsl::ExtInst::ExtInstSClamp)
5126 .Case("_Z5clampDv2_lS_S_", glsl::ExtInst::ExtInstSClamp)
5127 .Case("_Z5clampDv3_lS_S_", glsl::ExtInst::ExtInstSClamp)
5128 .Case("_Z5clampDv4_lS_S_", glsl::ExtInst::ExtInstSClamp)
5129 .Case("_Z5clampmmm", glsl::ExtInst::ExtInstUClamp)
5130 .Case("_Z5clampDv2_mS_S_", glsl::ExtInst::ExtInstUClamp)
5131 .Case("_Z5clampDv3_mS_S_", glsl::ExtInst::ExtInstUClamp)
5132 .Case("_Z5clampDv4_mS_S_", glsl::ExtInst::ExtInstUClamp)
David Neto22f144c2017-06-12 14:26:21 -04005133 .Case("_Z5clampfff", glsl::ExtInst::ExtInstFClamp)
5134 .Case("_Z5clampDv2_fS_S_", glsl::ExtInst::ExtInstFClamp)
5135 .Case("_Z5clampDv3_fS_S_", glsl::ExtInst::ExtInstFClamp)
5136 .Case("_Z5clampDv4_fS_S_", glsl::ExtInst::ExtInstFClamp)
alan-bakerb39c8262019-03-08 14:03:37 -05005137 .Case("_Z3maxcc", glsl::ExtInst::ExtInstSMax)
5138 .Case("_Z3maxDv2_cS_", glsl::ExtInst::ExtInstSMax)
5139 .Case("_Z3maxDv3_cS_", glsl::ExtInst::ExtInstSMax)
5140 .Case("_Z3maxDv4_cS_", glsl::ExtInst::ExtInstSMax)
5141 .Case("_Z3maxhh", glsl::ExtInst::ExtInstUMax)
5142 .Case("_Z3maxDv2_hS_", glsl::ExtInst::ExtInstUMax)
5143 .Case("_Z3maxDv3_hS_", glsl::ExtInst::ExtInstUMax)
5144 .Case("_Z3maxDv4_hS_", glsl::ExtInst::ExtInstUMax)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005145 .Case("_Z3maxss", glsl::ExtInst::ExtInstSMax)
5146 .Case("_Z3maxDv2_sS_", glsl::ExtInst::ExtInstSMax)
5147 .Case("_Z3maxDv3_sS_", glsl::ExtInst::ExtInstSMax)
5148 .Case("_Z3maxDv4_sS_", glsl::ExtInst::ExtInstSMax)
5149 .Case("_Z3maxtt", glsl::ExtInst::ExtInstUMax)
5150 .Case("_Z3maxDv2_tS_", glsl::ExtInst::ExtInstUMax)
5151 .Case("_Z3maxDv3_tS_", glsl::ExtInst::ExtInstUMax)
5152 .Case("_Z3maxDv4_tS_", glsl::ExtInst::ExtInstUMax)
David Neto22f144c2017-06-12 14:26:21 -04005153 .Case("_Z3maxii", glsl::ExtInst::ExtInstSMax)
5154 .Case("_Z3maxDv2_iS_", glsl::ExtInst::ExtInstSMax)
5155 .Case("_Z3maxDv3_iS_", glsl::ExtInst::ExtInstSMax)
5156 .Case("_Z3maxDv4_iS_", glsl::ExtInst::ExtInstSMax)
5157 .Case("_Z3maxjj", glsl::ExtInst::ExtInstUMax)
5158 .Case("_Z3maxDv2_jS_", glsl::ExtInst::ExtInstUMax)
5159 .Case("_Z3maxDv3_jS_", glsl::ExtInst::ExtInstUMax)
5160 .Case("_Z3maxDv4_jS_", glsl::ExtInst::ExtInstUMax)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005161 .Case("_Z3maxll", glsl::ExtInst::ExtInstSMax)
5162 .Case("_Z3maxDv2_lS_", glsl::ExtInst::ExtInstSMax)
5163 .Case("_Z3maxDv3_lS_", glsl::ExtInst::ExtInstSMax)
5164 .Case("_Z3maxDv4_lS_", glsl::ExtInst::ExtInstSMax)
5165 .Case("_Z3maxmm", glsl::ExtInst::ExtInstUMax)
5166 .Case("_Z3maxDv2_mS_", glsl::ExtInst::ExtInstUMax)
5167 .Case("_Z3maxDv3_mS_", glsl::ExtInst::ExtInstUMax)
5168 .Case("_Z3maxDv4_mS_", glsl::ExtInst::ExtInstUMax)
David Neto22f144c2017-06-12 14:26:21 -04005169 .Case("_Z3maxff", glsl::ExtInst::ExtInstFMax)
5170 .Case("_Z3maxDv2_fS_", glsl::ExtInst::ExtInstFMax)
5171 .Case("_Z3maxDv3_fS_", glsl::ExtInst::ExtInstFMax)
5172 .Case("_Z3maxDv4_fS_", glsl::ExtInst::ExtInstFMax)
5173 .StartsWith("_Z4fmax", glsl::ExtInst::ExtInstFMax)
alan-bakerb39c8262019-03-08 14:03:37 -05005174 .Case("_Z3mincc", glsl::ExtInst::ExtInstSMin)
5175 .Case("_Z3minDv2_cS_", glsl::ExtInst::ExtInstSMin)
5176 .Case("_Z3minDv3_cS_", glsl::ExtInst::ExtInstSMin)
5177 .Case("_Z3minDv4_cS_", glsl::ExtInst::ExtInstSMin)
5178 .Case("_Z3minhh", glsl::ExtInst::ExtInstUMin)
5179 .Case("_Z3minDv2_hS_", glsl::ExtInst::ExtInstUMin)
5180 .Case("_Z3minDv3_hS_", glsl::ExtInst::ExtInstUMin)
5181 .Case("_Z3minDv4_hS_", glsl::ExtInst::ExtInstUMin)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005182 .Case("_Z3minss", glsl::ExtInst::ExtInstSMin)
5183 .Case("_Z3minDv2_sS_", glsl::ExtInst::ExtInstSMin)
5184 .Case("_Z3minDv3_sS_", glsl::ExtInst::ExtInstSMin)
5185 .Case("_Z3minDv4_sS_", glsl::ExtInst::ExtInstSMin)
5186 .Case("_Z3mintt", glsl::ExtInst::ExtInstUMin)
5187 .Case("_Z3minDv2_tS_", glsl::ExtInst::ExtInstUMin)
5188 .Case("_Z3minDv3_tS_", glsl::ExtInst::ExtInstUMin)
5189 .Case("_Z3minDv4_tS_", glsl::ExtInst::ExtInstUMin)
David Neto22f144c2017-06-12 14:26:21 -04005190 .Case("_Z3minii", glsl::ExtInst::ExtInstSMin)
5191 .Case("_Z3minDv2_iS_", glsl::ExtInst::ExtInstSMin)
5192 .Case("_Z3minDv3_iS_", glsl::ExtInst::ExtInstSMin)
5193 .Case("_Z3minDv4_iS_", glsl::ExtInst::ExtInstSMin)
5194 .Case("_Z3minjj", glsl::ExtInst::ExtInstUMin)
5195 .Case("_Z3minDv2_jS_", glsl::ExtInst::ExtInstUMin)
5196 .Case("_Z3minDv3_jS_", glsl::ExtInst::ExtInstUMin)
5197 .Case("_Z3minDv4_jS_", glsl::ExtInst::ExtInstUMin)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005198 .Case("_Z3minll", glsl::ExtInst::ExtInstSMin)
5199 .Case("_Z3minDv2_lS_", glsl::ExtInst::ExtInstSMin)
5200 .Case("_Z3minDv3_lS_", glsl::ExtInst::ExtInstSMin)
5201 .Case("_Z3minDv4_lS_", glsl::ExtInst::ExtInstSMin)
5202 .Case("_Z3minmm", glsl::ExtInst::ExtInstUMin)
5203 .Case("_Z3minDv2_mS_", glsl::ExtInst::ExtInstUMin)
5204 .Case("_Z3minDv3_mS_", glsl::ExtInst::ExtInstUMin)
5205 .Case("_Z3minDv4_mS_", glsl::ExtInst::ExtInstUMin)
David Neto22f144c2017-06-12 14:26:21 -04005206 .Case("_Z3minff", glsl::ExtInst::ExtInstFMin)
5207 .Case("_Z3minDv2_fS_", glsl::ExtInst::ExtInstFMin)
5208 .Case("_Z3minDv3_fS_", glsl::ExtInst::ExtInstFMin)
5209 .Case("_Z3minDv4_fS_", glsl::ExtInst::ExtInstFMin)
5210 .StartsWith("_Z4fmin", glsl::ExtInst::ExtInstFMin)
5211 .StartsWith("_Z7degrees", glsl::ExtInst::ExtInstDegrees)
5212 .StartsWith("_Z7radians", glsl::ExtInst::ExtInstRadians)
5213 .StartsWith("_Z3mix", glsl::ExtInst::ExtInstFMix)
5214 .StartsWith("_Z4acos", glsl::ExtInst::ExtInstAcos)
5215 .StartsWith("_Z5acosh", glsl::ExtInst::ExtInstAcosh)
5216 .StartsWith("_Z4asin", glsl::ExtInst::ExtInstAsin)
5217 .StartsWith("_Z5asinh", glsl::ExtInst::ExtInstAsinh)
5218 .StartsWith("_Z4atan", glsl::ExtInst::ExtInstAtan)
5219 .StartsWith("_Z5atan2", glsl::ExtInst::ExtInstAtan2)
5220 .StartsWith("_Z5atanh", glsl::ExtInst::ExtInstAtanh)
5221 .StartsWith("_Z4ceil", glsl::ExtInst::ExtInstCeil)
5222 .StartsWith("_Z3sin", glsl::ExtInst::ExtInstSin)
5223 .StartsWith("_Z4sinh", glsl::ExtInst::ExtInstSinh)
5224 .StartsWith("_Z8half_sin", glsl::ExtInst::ExtInstSin)
5225 .StartsWith("_Z10native_sin", glsl::ExtInst::ExtInstSin)
5226 .StartsWith("_Z3cos", glsl::ExtInst::ExtInstCos)
5227 .StartsWith("_Z4cosh", glsl::ExtInst::ExtInstCosh)
5228 .StartsWith("_Z8half_cos", glsl::ExtInst::ExtInstCos)
5229 .StartsWith("_Z10native_cos", glsl::ExtInst::ExtInstCos)
5230 .StartsWith("_Z3tan", glsl::ExtInst::ExtInstTan)
5231 .StartsWith("_Z4tanh", glsl::ExtInst::ExtInstTanh)
5232 .StartsWith("_Z8half_tan", glsl::ExtInst::ExtInstTan)
5233 .StartsWith("_Z10native_tan", glsl::ExtInst::ExtInstTan)
5234 .StartsWith("_Z3exp", glsl::ExtInst::ExtInstExp)
5235 .StartsWith("_Z8half_exp", glsl::ExtInst::ExtInstExp)
5236 .StartsWith("_Z10native_exp", glsl::ExtInst::ExtInstExp)
5237 .StartsWith("_Z4exp2", glsl::ExtInst::ExtInstExp2)
5238 .StartsWith("_Z9half_exp2", glsl::ExtInst::ExtInstExp2)
5239 .StartsWith("_Z11native_exp2", glsl::ExtInst::ExtInstExp2)
5240 .StartsWith("_Z3log", glsl::ExtInst::ExtInstLog)
5241 .StartsWith("_Z8half_log", glsl::ExtInst::ExtInstLog)
5242 .StartsWith("_Z10native_log", glsl::ExtInst::ExtInstLog)
5243 .StartsWith("_Z4log2", glsl::ExtInst::ExtInstLog2)
5244 .StartsWith("_Z9half_log2", glsl::ExtInst::ExtInstLog2)
5245 .StartsWith("_Z11native_log2", glsl::ExtInst::ExtInstLog2)
5246 .StartsWith("_Z4fabs", glsl::ExtInst::ExtInstFAbs)
kpet3458e942018-10-03 14:35:21 +01005247 .StartsWith("_Z3fma", glsl::ExtInst::ExtInstFma)
David Neto22f144c2017-06-12 14:26:21 -04005248 .StartsWith("_Z5floor", glsl::ExtInst::ExtInstFloor)
5249 .StartsWith("_Z5ldexp", glsl::ExtInst::ExtInstLdexp)
5250 .StartsWith("_Z3pow", glsl::ExtInst::ExtInstPow)
5251 .StartsWith("_Z4powr", glsl::ExtInst::ExtInstPow)
5252 .StartsWith("_Z9half_powr", glsl::ExtInst::ExtInstPow)
5253 .StartsWith("_Z11native_powr", glsl::ExtInst::ExtInstPow)
5254 .StartsWith("_Z5round", glsl::ExtInst::ExtInstRound)
5255 .StartsWith("_Z4sqrt", glsl::ExtInst::ExtInstSqrt)
5256 .StartsWith("_Z9half_sqrt", glsl::ExtInst::ExtInstSqrt)
5257 .StartsWith("_Z11native_sqrt", glsl::ExtInst::ExtInstSqrt)
5258 .StartsWith("_Z5rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5259 .StartsWith("_Z10half_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5260 .StartsWith("_Z12native_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5261 .StartsWith("_Z5trunc", glsl::ExtInst::ExtInstTrunc)
5262 .StartsWith("_Z5frexp", glsl::ExtInst::ExtInstFrexp)
5263 .StartsWith("_Z4sign", glsl::ExtInst::ExtInstFSign)
5264 .StartsWith("_Z6length", glsl::ExtInst::ExtInstLength)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005265 .StartsWith("_Z11fast_length", glsl::ExtInst::ExtInstLength)
David Neto22f144c2017-06-12 14:26:21 -04005266 .StartsWith("_Z8distance", glsl::ExtInst::ExtInstDistance)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005267 .StartsWith("_Z13fast_distance", glsl::ExtInst::ExtInstDistance)
David Netoe9a03512017-10-16 10:08:27 -04005268 .StartsWith("_Z4step", glsl::ExtInst::ExtInstStep)
kpet6fd2a262018-10-03 14:48:01 +01005269 .StartsWith("_Z10smoothstep", glsl::ExtInst::ExtInstSmoothStep)
David Neto22f144c2017-06-12 14:26:21 -04005270 .Case("_Z5crossDv3_fS_", glsl::ExtInst::ExtInstCross)
5271 .StartsWith("_Z9normalize", glsl::ExtInst::ExtInstNormalize)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005272 .StartsWith("_Z14fast_normalize", glsl::ExtInst::ExtInstNormalize)
David Neto22f144c2017-06-12 14:26:21 -04005273 .StartsWith("llvm.fmuladd.", glsl::ExtInst::ExtInstFma)
5274 .Case("spirv.unpack.v2f16", glsl::ExtInst::ExtInstUnpackHalf2x16)
5275 .Case("spirv.pack.v2f16", glsl::ExtInst::ExtInstPackHalf2x16)
David Neto62653202017-10-16 19:05:18 -04005276 .Case("clspv.fract.f", glsl::ExtInst::ExtInstFract)
5277 .Case("clspv.fract.v2f", glsl::ExtInst::ExtInstFract)
5278 .Case("clspv.fract.v3f", glsl::ExtInst::ExtInstFract)
5279 .Case("clspv.fract.v4f", glsl::ExtInst::ExtInstFract)
David Neto3fbb4072017-10-16 11:28:14 -04005280 .Default(kGlslExtInstBad);
5281}
5282
5283glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(StringRef Name) {
5284 // Check indirect cases.
5285 return StringSwitch<glsl::ExtInst>(Name)
5286 .StartsWith("_Z3clz", glsl::ExtInst::ExtInstFindUMsb)
5287 // Use exact match on float arg because these need a multiply
5288 // of a constant of the right floating point type.
5289 .Case("_Z6acospif", glsl::ExtInst::ExtInstAcos)
5290 .Case("_Z6acospiDv2_f", glsl::ExtInst::ExtInstAcos)
5291 .Case("_Z6acospiDv3_f", glsl::ExtInst::ExtInstAcos)
5292 .Case("_Z6acospiDv4_f", glsl::ExtInst::ExtInstAcos)
5293 .Case("_Z6asinpif", glsl::ExtInst::ExtInstAsin)
5294 .Case("_Z6asinpiDv2_f", glsl::ExtInst::ExtInstAsin)
5295 .Case("_Z6asinpiDv3_f", glsl::ExtInst::ExtInstAsin)
5296 .Case("_Z6asinpiDv4_f", glsl::ExtInst::ExtInstAsin)
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005297 .Case("_Z6atanpif", glsl::ExtInst::ExtInstAtan)
5298 .Case("_Z6atanpiDv2_f", glsl::ExtInst::ExtInstAtan)
5299 .Case("_Z6atanpiDv3_f", glsl::ExtInst::ExtInstAtan)
5300 .Case("_Z6atanpiDv4_f", glsl::ExtInst::ExtInstAtan)
David Neto3fbb4072017-10-16 11:28:14 -04005301 .Case("_Z7atan2piff", glsl::ExtInst::ExtInstAtan2)
5302 .Case("_Z7atan2piDv2_fS_", glsl::ExtInst::ExtInstAtan2)
5303 .Case("_Z7atan2piDv3_fS_", glsl::ExtInst::ExtInstAtan2)
5304 .Case("_Z7atan2piDv4_fS_", glsl::ExtInst::ExtInstAtan2)
5305 .Default(kGlslExtInstBad);
5306}
5307
alan-bakerb6b09dc2018-11-08 16:59:28 -05005308glsl::ExtInst
5309SPIRVProducerPass::getDirectOrIndirectExtInstEnum(StringRef Name) {
David Neto3fbb4072017-10-16 11:28:14 -04005310 auto direct = getExtInstEnum(Name);
5311 if (direct != kGlslExtInstBad)
5312 return direct;
5313 return getIndirectExtInstEnum(Name);
David Neto22f144c2017-06-12 14:26:21 -04005314}
5315
David Neto22f144c2017-06-12 14:26:21 -04005316void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04005317 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04005318}
5319
5320void SPIRVProducerPass::WriteResultID(SPIRVInstruction *Inst) {
5321 WriteOneWord(Inst->getResultID());
5322}
5323
5324void SPIRVProducerPass::WriteWordCountAndOpcode(SPIRVInstruction *Inst) {
5325 // High 16 bit : Word Count
5326 // Low 16 bit : Opcode
5327 uint32_t Word = Inst->getOpcode();
David Netoee2660d2018-06-28 16:31:29 -04005328 const uint32_t count = Inst->getWordCount();
5329 if (count > 65535) {
5330 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
5331 llvm_unreachable("Word count too high");
5332 }
David Neto22f144c2017-06-12 14:26:21 -04005333 Word |= Inst->getWordCount() << 16;
5334 WriteOneWord(Word);
5335}
5336
5337void SPIRVProducerPass::WriteOperand(SPIRVOperand *Op) {
5338 SPIRVOperandType OpTy = Op->getType();
5339 switch (OpTy) {
5340 default: {
5341 llvm_unreachable("Unsupported SPIRV Operand Type???");
5342 break;
5343 }
5344 case SPIRVOperandType::NUMBERID: {
5345 WriteOneWord(Op->getNumID());
5346 break;
5347 }
5348 case SPIRVOperandType::LITERAL_STRING: {
5349 std::string Str = Op->getLiteralStr();
5350 const char *Data = Str.c_str();
5351 size_t WordSize = Str.size() / 4;
5352 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
5353 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
5354 }
5355
5356 uint32_t Remainder = Str.size() % 4;
5357 uint32_t LastWord = 0;
5358 if (Remainder) {
5359 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
5360 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
5361 }
5362 }
5363
5364 WriteOneWord(LastWord);
5365 break;
5366 }
5367 case SPIRVOperandType::LITERAL_INTEGER:
5368 case SPIRVOperandType::LITERAL_FLOAT: {
5369 auto LiteralNum = Op->getLiteralNum();
5370 // TODO: Handle LiteranNum carefully.
5371 for (auto Word : LiteralNum) {
5372 WriteOneWord(Word);
5373 }
5374 break;
5375 }
5376 }
5377}
5378
5379void SPIRVProducerPass::WriteSPIRVBinary() {
5380 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5381
5382 for (auto Inst : SPIRVInstList) {
David Netoc6f3ab22018-04-06 18:02:31 -04005383 SPIRVOperandList Ops{Inst->getOperands()};
David Neto22f144c2017-06-12 14:26:21 -04005384 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5385
5386 switch (Opcode) {
5387 default: {
David Neto5c22a252018-03-15 16:07:41 -04005388 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04005389 llvm_unreachable("Unsupported SPIRV instruction");
5390 break;
5391 }
5392 case spv::OpCapability:
5393 case spv::OpExtension:
5394 case spv::OpMemoryModel:
5395 case spv::OpEntryPoint:
5396 case spv::OpExecutionMode:
5397 case spv::OpSource:
5398 case spv::OpDecorate:
5399 case spv::OpMemberDecorate:
5400 case spv::OpBranch:
5401 case spv::OpBranchConditional:
5402 case spv::OpSelectionMerge:
5403 case spv::OpLoopMerge:
5404 case spv::OpStore:
5405 case spv::OpImageWrite:
5406 case spv::OpReturnValue:
5407 case spv::OpControlBarrier:
5408 case spv::OpMemoryBarrier:
5409 case spv::OpReturn:
5410 case spv::OpFunctionEnd:
5411 case spv::OpCopyMemory: {
5412 WriteWordCountAndOpcode(Inst);
5413 for (uint32_t i = 0; i < Ops.size(); i++) {
5414 WriteOperand(Ops[i]);
5415 }
5416 break;
5417 }
5418 case spv::OpTypeBool:
5419 case spv::OpTypeVoid:
5420 case spv::OpTypeSampler:
5421 case spv::OpLabel:
5422 case spv::OpExtInstImport:
5423 case spv::OpTypePointer:
5424 case spv::OpTypeRuntimeArray:
5425 case spv::OpTypeStruct:
5426 case spv::OpTypeImage:
5427 case spv::OpTypeSampledImage:
5428 case spv::OpTypeInt:
5429 case spv::OpTypeFloat:
5430 case spv::OpTypeArray:
5431 case spv::OpTypeVector:
5432 case spv::OpTypeFunction: {
5433 WriteWordCountAndOpcode(Inst);
5434 WriteResultID(Inst);
5435 for (uint32_t i = 0; i < Ops.size(); i++) {
5436 WriteOperand(Ops[i]);
5437 }
5438 break;
5439 }
5440 case spv::OpFunction:
5441 case spv::OpFunctionParameter:
5442 case spv::OpAccessChain:
5443 case spv::OpPtrAccessChain:
5444 case spv::OpInBoundsAccessChain:
5445 case spv::OpUConvert:
5446 case spv::OpSConvert:
5447 case spv::OpConvertFToU:
5448 case spv::OpConvertFToS:
5449 case spv::OpConvertUToF:
5450 case spv::OpConvertSToF:
5451 case spv::OpFConvert:
5452 case spv::OpConvertPtrToU:
5453 case spv::OpConvertUToPtr:
5454 case spv::OpBitcast:
5455 case spv::OpIAdd:
5456 case spv::OpFAdd:
5457 case spv::OpISub:
5458 case spv::OpFSub:
5459 case spv::OpIMul:
5460 case spv::OpFMul:
5461 case spv::OpUDiv:
5462 case spv::OpSDiv:
5463 case spv::OpFDiv:
5464 case spv::OpUMod:
5465 case spv::OpSRem:
5466 case spv::OpFRem:
Kévin Petit8a560882019-03-21 15:24:34 +00005467 case spv::OpUMulExtended:
5468 case spv::OpSMulExtended:
David Neto22f144c2017-06-12 14:26:21 -04005469 case spv::OpBitwiseOr:
5470 case spv::OpBitwiseXor:
5471 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005472 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005473 case spv::OpShiftLeftLogical:
5474 case spv::OpShiftRightLogical:
5475 case spv::OpShiftRightArithmetic:
5476 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04005477 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04005478 case spv::OpCompositeExtract:
5479 case spv::OpVectorExtractDynamic:
5480 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04005481 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04005482 case spv::OpVectorInsertDynamic:
5483 case spv::OpVectorShuffle:
5484 case spv::OpIEqual:
5485 case spv::OpINotEqual:
5486 case spv::OpUGreaterThan:
5487 case spv::OpUGreaterThanEqual:
5488 case spv::OpULessThan:
5489 case spv::OpULessThanEqual:
5490 case spv::OpSGreaterThan:
5491 case spv::OpSGreaterThanEqual:
5492 case spv::OpSLessThan:
5493 case spv::OpSLessThanEqual:
5494 case spv::OpFOrdEqual:
5495 case spv::OpFOrdGreaterThan:
5496 case spv::OpFOrdGreaterThanEqual:
5497 case spv::OpFOrdLessThan:
5498 case spv::OpFOrdLessThanEqual:
5499 case spv::OpFOrdNotEqual:
5500 case spv::OpFUnordEqual:
5501 case spv::OpFUnordGreaterThan:
5502 case spv::OpFUnordGreaterThanEqual:
5503 case spv::OpFUnordLessThan:
5504 case spv::OpFUnordLessThanEqual:
5505 case spv::OpFUnordNotEqual:
5506 case spv::OpExtInst:
5507 case spv::OpIsInf:
5508 case spv::OpIsNan:
5509 case spv::OpAny:
5510 case spv::OpAll:
5511 case spv::OpUndef:
5512 case spv::OpConstantNull:
5513 case spv::OpLogicalOr:
5514 case spv::OpLogicalAnd:
5515 case spv::OpLogicalNot:
5516 case spv::OpLogicalNotEqual:
5517 case spv::OpConstantComposite:
5518 case spv::OpSpecConstantComposite:
5519 case spv::OpConstantTrue:
5520 case spv::OpConstantFalse:
5521 case spv::OpConstant:
5522 case spv::OpSpecConstant:
5523 case spv::OpVariable:
5524 case spv::OpFunctionCall:
5525 case spv::OpSampledImage:
5526 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04005527 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04005528 case spv::OpSelect:
5529 case spv::OpPhi:
5530 case spv::OpLoad:
5531 case spv::OpAtomicIAdd:
5532 case spv::OpAtomicISub:
5533 case spv::OpAtomicExchange:
5534 case spv::OpAtomicIIncrement:
5535 case spv::OpAtomicIDecrement:
5536 case spv::OpAtomicCompareExchange:
5537 case spv::OpAtomicUMin:
5538 case spv::OpAtomicSMin:
5539 case spv::OpAtomicUMax:
5540 case spv::OpAtomicSMax:
5541 case spv::OpAtomicAnd:
5542 case spv::OpAtomicOr:
5543 case spv::OpAtomicXor:
5544 case spv::OpDot: {
5545 WriteWordCountAndOpcode(Inst);
5546 WriteOperand(Ops[0]);
5547 WriteResultID(Inst);
5548 for (uint32_t i = 1; i < Ops.size(); i++) {
5549 WriteOperand(Ops[i]);
5550 }
5551 break;
5552 }
5553 }
5554 }
5555}
Alan Baker9bf93fb2018-08-28 16:59:26 -04005556
alan-bakerb6b09dc2018-11-08 16:59:28 -05005557bool SPIRVProducerPass::IsTypeNullable(const Type *type) const {
Alan Baker9bf93fb2018-08-28 16:59:26 -04005558 switch (type->getTypeID()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005559 case Type::HalfTyID:
5560 case Type::FloatTyID:
5561 case Type::DoubleTyID:
5562 case Type::IntegerTyID:
5563 case Type::VectorTyID:
5564 return true;
5565 case Type::PointerTyID: {
5566 const PointerType *pointer_type = cast<PointerType>(type);
5567 if (pointer_type->getPointerAddressSpace() !=
5568 AddressSpace::UniformConstant) {
5569 auto pointee_type = pointer_type->getPointerElementType();
5570 if (pointee_type->isStructTy() &&
5571 cast<StructType>(pointee_type)->isOpaque()) {
5572 // Images and samplers are not nullable.
5573 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04005574 }
Alan Baker9bf93fb2018-08-28 16:59:26 -04005575 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05005576 return true;
5577 }
5578 case Type::ArrayTyID:
5579 return IsTypeNullable(cast<CompositeType>(type)->getTypeAtIndex(0u));
5580 case Type::StructTyID: {
5581 const StructType *struct_type = cast<StructType>(type);
5582 // Images and samplers are not nullable.
5583 if (struct_type->isOpaque())
Alan Baker9bf93fb2018-08-28 16:59:26 -04005584 return false;
alan-bakerb6b09dc2018-11-08 16:59:28 -05005585 for (const auto element : struct_type->elements()) {
5586 if (!IsTypeNullable(element))
5587 return false;
5588 }
5589 return true;
5590 }
5591 default:
5592 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04005593 }
5594}
Alan Bakerfcda9482018-10-02 17:09:59 -04005595
5596void SPIRVProducerPass::PopulateUBOTypeMaps(Module &module) {
5597 if (auto *offsets_md =
5598 module.getNamedMetadata(clspv::RemappedTypeOffsetMetadataName())) {
5599 // Metdata is stored as key-value pair operands. The first element of each
5600 // operand is the type and the second is a vector of offsets.
5601 for (const auto *operand : offsets_md->operands()) {
5602 const auto *pair = cast<MDTuple>(operand);
5603 auto *type =
5604 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
5605 const auto *offset_vector = cast<MDTuple>(pair->getOperand(1));
5606 std::vector<uint32_t> offsets;
5607 for (const Metadata *offset_md : offset_vector->operands()) {
5608 const auto *constant_md = cast<ConstantAsMetadata>(offset_md);
alan-bakerb6b09dc2018-11-08 16:59:28 -05005609 offsets.push_back(static_cast<uint32_t>(
5610 cast<ConstantInt>(constant_md->getValue())->getZExtValue()));
Alan Bakerfcda9482018-10-02 17:09:59 -04005611 }
5612 RemappedUBOTypeOffsets.insert(std::make_pair(type, offsets));
5613 }
5614 }
5615
5616 if (auto *sizes_md =
5617 module.getNamedMetadata(clspv::RemappedTypeSizesMetadataName())) {
5618 // Metadata is stored as key-value pair operands. The first element of each
5619 // operand is the type and the second is a triple of sizes: type size in
5620 // bits, store size and alloc size.
5621 for (const auto *operand : sizes_md->operands()) {
5622 const auto *pair = cast<MDTuple>(operand);
5623 auto *type =
5624 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
5625 const auto *size_triple = cast<MDTuple>(pair->getOperand(1));
5626 uint64_t type_size_in_bits =
5627 cast<ConstantInt>(
5628 cast<ConstantAsMetadata>(size_triple->getOperand(0))->getValue())
5629 ->getZExtValue();
5630 uint64_t type_store_size =
5631 cast<ConstantInt>(
5632 cast<ConstantAsMetadata>(size_triple->getOperand(1))->getValue())
5633 ->getZExtValue();
5634 uint64_t type_alloc_size =
5635 cast<ConstantInt>(
5636 cast<ConstantAsMetadata>(size_triple->getOperand(2))->getValue())
5637 ->getZExtValue();
5638 RemappedUBOTypeSizes.insert(std::make_pair(
5639 type, std::make_tuple(type_size_in_bits, type_store_size,
5640 type_alloc_size)));
5641 }
5642 }
5643}
5644
5645uint64_t SPIRVProducerPass::GetTypeSizeInBits(Type *type,
5646 const DataLayout &DL) {
5647 auto iter = RemappedUBOTypeSizes.find(type);
5648 if (iter != RemappedUBOTypeSizes.end()) {
5649 return std::get<0>(iter->second);
5650 }
5651
5652 return DL.getTypeSizeInBits(type);
5653}
5654
5655uint64_t SPIRVProducerPass::GetTypeStoreSize(Type *type, const DataLayout &DL) {
5656 auto iter = RemappedUBOTypeSizes.find(type);
5657 if (iter != RemappedUBOTypeSizes.end()) {
5658 return std::get<1>(iter->second);
5659 }
5660
5661 return DL.getTypeStoreSize(type);
5662}
5663
5664uint64_t SPIRVProducerPass::GetTypeAllocSize(Type *type, const DataLayout &DL) {
5665 auto iter = RemappedUBOTypeSizes.find(type);
5666 if (iter != RemappedUBOTypeSizes.end()) {
5667 return std::get<2>(iter->second);
5668 }
5669
5670 return DL.getTypeAllocSize(type);
5671}
alan-baker5b86ed72019-02-15 08:26:50 -05005672
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04005673void SPIRVProducerPass::setVariablePointersCapabilities(
5674 unsigned address_space) {
alan-baker5b86ed72019-02-15 08:26:50 -05005675 if (GetStorageClass(address_space) == spv::StorageClassStorageBuffer) {
5676 setVariablePointersStorageBuffer(true);
5677 } else {
5678 setVariablePointers(true);
5679 }
5680}
5681
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04005682Value *SPIRVProducerPass::GetBasePointer(Value *v) {
alan-baker5b86ed72019-02-15 08:26:50 -05005683 if (auto *gep = dyn_cast<GetElementPtrInst>(v)) {
5684 return GetBasePointer(gep->getPointerOperand());
5685 }
5686
5687 // Conservatively return |v|.
5688 return v;
5689}
5690
5691bool SPIRVProducerPass::sameResource(Value *lhs, Value *rhs) const {
5692 if (auto *lhs_call = dyn_cast<CallInst>(lhs)) {
5693 if (auto *rhs_call = dyn_cast<CallInst>(rhs)) {
5694 if (lhs_call->getCalledFunction()->getName().startswith(
5695 clspv::ResourceAccessorFunction()) &&
5696 rhs_call->getCalledFunction()->getName().startswith(
5697 clspv::ResourceAccessorFunction())) {
5698 // For resource accessors, match descriptor set and binding.
5699 if (lhs_call->getOperand(0) == rhs_call->getOperand(0) &&
5700 lhs_call->getOperand(1) == rhs_call->getOperand(1))
5701 return true;
5702 } else if (lhs_call->getCalledFunction()->getName().startswith(
5703 clspv::WorkgroupAccessorFunction()) &&
5704 rhs_call->getCalledFunction()->getName().startswith(
5705 clspv::WorkgroupAccessorFunction())) {
5706 // For workgroup resources, match spec id.
5707 if (lhs_call->getOperand(0) == rhs_call->getOperand(0))
5708 return true;
5709 }
5710 }
5711 }
5712
5713 return false;
5714}
5715
5716bool SPIRVProducerPass::selectFromSameObject(Instruction *inst) {
5717 assert(inst->getType()->isPointerTy());
5718 assert(GetStorageClass(inst->getType()->getPointerAddressSpace()) ==
5719 spv::StorageClassStorageBuffer);
5720 const bool hack_undef = clspv::Option::HackUndef();
5721 if (auto *select = dyn_cast<SelectInst>(inst)) {
5722 auto *true_base = GetBasePointer(select->getTrueValue());
5723 auto *false_base = GetBasePointer(select->getFalseValue());
5724
5725 if (true_base == false_base)
5726 return true;
5727
5728 // If either the true or false operand is a null, then we satisfy the same
5729 // object constraint.
5730 if (auto *true_cst = dyn_cast<Constant>(true_base)) {
5731 if (true_cst->isNullValue() || (hack_undef && isa<UndefValue>(true_base)))
5732 return true;
5733 }
5734
5735 if (auto *false_cst = dyn_cast<Constant>(false_base)) {
5736 if (false_cst->isNullValue() ||
5737 (hack_undef && isa<UndefValue>(false_base)))
5738 return true;
5739 }
5740
5741 if (sameResource(true_base, false_base))
5742 return true;
5743 } else if (auto *phi = dyn_cast<PHINode>(inst)) {
5744 Value *value = nullptr;
5745 bool ok = true;
5746 for (unsigned i = 0; ok && i != phi->getNumIncomingValues(); ++i) {
5747 auto *base = GetBasePointer(phi->getIncomingValue(i));
5748 // Null values satisfy the constraint of selecting of selecting from the
5749 // same object.
5750 if (!value) {
5751 if (auto *cst = dyn_cast<Constant>(base)) {
5752 if (!cst->isNullValue() && !(hack_undef && isa<UndefValue>(base)))
5753 value = base;
5754 } else {
5755 value = base;
5756 }
5757 } else if (base != value) {
5758 if (auto *base_cst = dyn_cast<Constant>(base)) {
5759 if (base_cst->isNullValue() || (hack_undef && isa<UndefValue>(base)))
5760 continue;
5761 }
5762
5763 if (sameResource(value, base))
5764 continue;
5765
5766 // Values don't represent the same base.
5767 ok = false;
5768 }
5769 }
5770
5771 return ok;
5772 }
5773
5774 // Conservatively return false.
5775 return false;
5776}
alan-bakere9308012019-03-15 10:25:13 -04005777
5778bool SPIRVProducerPass::CalledWithCoherentResource(Argument &Arg) {
5779 if (!Arg.getType()->isPointerTy() ||
5780 Arg.getType()->getPointerAddressSpace() != clspv::AddressSpace::Global) {
5781 // Only SSBOs need to be annotated as coherent.
5782 return false;
5783 }
5784
5785 DenseSet<Value *> visited;
5786 std::vector<Value *> stack;
5787 for (auto *U : Arg.getParent()->users()) {
5788 if (auto *call = dyn_cast<CallInst>(U)) {
5789 stack.push_back(call->getOperand(Arg.getArgNo()));
5790 }
5791 }
5792
5793 while (!stack.empty()) {
5794 Value *v = stack.back();
5795 stack.pop_back();
5796
5797 if (!visited.insert(v).second)
5798 continue;
5799
5800 auto *resource_call = dyn_cast<CallInst>(v);
5801 if (resource_call &&
5802 resource_call->getCalledFunction()->getName().startswith(
5803 clspv::ResourceAccessorFunction())) {
5804 // If this is a resource accessor function, check if the coherent operand
5805 // is set.
5806 const auto coherent =
5807 unsigned(dyn_cast<ConstantInt>(resource_call->getArgOperand(5))
5808 ->getZExtValue());
5809 if (coherent == 1)
5810 return true;
5811 } else if (auto *arg = dyn_cast<Argument>(v)) {
5812 // If this is a function argument, trace through its callers.
alan-bakere98f3f92019-04-08 15:06:36 -04005813 for (auto U : arg->getParent()->users()) {
alan-bakere9308012019-03-15 10:25:13 -04005814 if (auto *call = dyn_cast<CallInst>(U)) {
5815 stack.push_back(call->getOperand(arg->getArgNo()));
5816 }
5817 }
5818 } else if (auto *user = dyn_cast<User>(v)) {
5819 // If this is a user, traverse all operands that could lead to resource
5820 // variables.
5821 for (unsigned i = 0; i != user->getNumOperands(); ++i) {
5822 Value *operand = user->getOperand(i);
5823 if (operand->getType()->isPointerTy() &&
5824 operand->getType()->getPointerAddressSpace() ==
5825 clspv::AddressSpace::Global) {
5826 stack.push_back(operand);
5827 }
5828 }
5829 }
5830 }
5831
5832 // No coherent resource variables encountered.
5833 return false;
5834}