blob: 5e3f58185537d5ad845f331e2d5ee15872d50f34 [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
alan-bakerdcd97412019-09-16 15:32:30 -04001273 // If module constants are clustered in a storage buffer then that struct
1274 // needs layout decorations.
1275 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
1276 for (GlobalVariable &GV : M.globals()) {
1277 PointerType *PTy = cast<PointerType>(GV.getType());
1278 const auto AS = PTy->getAddressSpace();
1279 const bool module_scope_constant_external_init =
1280 (AS == AddressSpace::Constant) && GV.hasInitializer();
1281 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
1282 if (module_scope_constant_external_init &&
1283 spv::BuiltInMax == BuiltinType) {
1284 StructTypesNeedingBlock.insert(
1285 cast<StructType>(PTy->getPointerElementType()));
1286 }
1287 }
1288 }
1289
David Neto862b7d82018-06-14 18:48:37 -04001290 // Traverse the arrays and structures underneath each Block, and
1291 // mark them as needing layout.
1292 std::vector<Type *> work_list(StructTypesNeedingBlock.begin(),
1293 StructTypesNeedingBlock.end());
1294 while (!work_list.empty()) {
1295 Type *type = work_list.back();
1296 work_list.pop_back();
1297 TypesNeedingLayout.insert(type);
1298 switch (type->getTypeID()) {
1299 case Type::ArrayTyID:
1300 work_list.push_back(type->getArrayElementType());
1301 if (!Hack_generate_runtime_array_stride_early) {
1302 // Remember this array type for deferred decoration.
1303 TypesNeedingArrayStride.insert(type);
1304 }
1305 break;
1306 case Type::StructTyID:
1307 for (auto *elem_ty : cast<StructType>(type)->elements()) {
1308 work_list.push_back(elem_ty);
1309 }
1310 default:
1311 // This type and its contained types don't get layout.
1312 break;
1313 }
1314 }
1315}
1316
Alan Baker202c8c72018-08-13 13:47:44 -04001317void SPIRVProducerPass::FindWorkgroupVars(Module &M) {
1318 // The SpecId assignment for pointer-to-local arguments is recorded in
1319 // module-level metadata. Translate that information into local argument
1320 // information.
1321 NamedMDNode *nmd = M.getNamedMetadata(clspv::LocalSpecIdMetadataName());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001322 if (!nmd)
1323 return;
Alan Baker202c8c72018-08-13 13:47:44 -04001324 for (auto operand : nmd->operands()) {
1325 MDTuple *tuple = cast<MDTuple>(operand);
1326 ValueAsMetadata *fn_md = cast<ValueAsMetadata>(tuple->getOperand(0));
1327 Function *func = cast<Function>(fn_md->getValue());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001328 ConstantAsMetadata *arg_index_md =
1329 cast<ConstantAsMetadata>(tuple->getOperand(1));
1330 int arg_index = static_cast<int>(
1331 cast<ConstantInt>(arg_index_md->getValue())->getSExtValue());
1332 Argument *arg = &*(func->arg_begin() + arg_index);
Alan Baker202c8c72018-08-13 13:47:44 -04001333
1334 ConstantAsMetadata *spec_id_md =
1335 cast<ConstantAsMetadata>(tuple->getOperand(2));
alan-bakerb6b09dc2018-11-08 16:59:28 -05001336 int spec_id = static_cast<int>(
1337 cast<ConstantInt>(spec_id_md->getValue())->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04001338
1339 max_local_spec_id_ = std::max(max_local_spec_id_, spec_id + 1);
1340 LocalArgSpecIds[arg] = spec_id;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001341 if (LocalSpecIdInfoMap.count(spec_id))
1342 continue;
Alan Baker202c8c72018-08-13 13:47:44 -04001343
1344 // We haven't seen this SpecId yet, so generate the LocalArgInfo for it.
1345 LocalArgInfo info{nextID, arg->getType()->getPointerElementType(),
1346 nextID + 1, nextID + 2,
1347 nextID + 3, spec_id};
1348 LocalSpecIdInfoMap[spec_id] = info;
1349 nextID += 4;
1350
1351 // Ensure the types necessary for this argument get generated.
1352 Type *IdxTy = Type::getInt32Ty(M.getContext());
1353 FindConstant(ConstantInt::get(IdxTy, 0));
1354 FindType(IdxTy);
1355 FindType(arg->getType());
1356 }
1357}
1358
David Neto22f144c2017-06-12 14:26:21 -04001359void SPIRVProducerPass::FindType(Type *Ty) {
1360 TypeList &TyList = getTypeList();
1361
1362 if (0 != TyList.idFor(Ty)) {
1363 return;
1364 }
1365
1366 if (Ty->isPointerTy()) {
1367 auto AddrSpace = Ty->getPointerAddressSpace();
1368 if ((AddressSpace::Constant == AddrSpace) ||
1369 (AddressSpace::Global == AddrSpace)) {
1370 auto PointeeTy = Ty->getPointerElementType();
1371
1372 if (PointeeTy->isStructTy() &&
1373 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1374 FindType(PointeeTy);
1375 auto ActualPointerTy =
1376 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1377 FindType(ActualPointerTy);
1378 return;
1379 }
1380 }
1381 }
1382
David Neto862b7d82018-06-14 18:48:37 -04001383 // By convention, LLVM array type with 0 elements will map to
1384 // OpTypeRuntimeArray. Otherwise, it will map to OpTypeArray, which
1385 // has a constant number of elements. We need to support type of the
1386 // constant.
1387 if (auto *arrayTy = dyn_cast<ArrayType>(Ty)) {
1388 if (arrayTy->getNumElements() > 0) {
1389 LLVMContext &Context = Ty->getContext();
1390 FindType(Type::getInt32Ty(Context));
1391 }
David Neto22f144c2017-06-12 14:26:21 -04001392 }
1393
1394 for (Type *SubTy : Ty->subtypes()) {
1395 FindType(SubTy);
1396 }
1397
1398 TyList.insert(Ty);
1399}
1400
1401void SPIRVProducerPass::FindConstantPerGlobalVar(GlobalVariable &GV) {
1402 // If the global variable has a (non undef) initializer.
1403 if (GV.hasInitializer() && !isa<UndefValue>(GV.getInitializer())) {
David Neto862b7d82018-06-14 18:48:37 -04001404 // Generate the constant if it's not the initializer to a module scope
1405 // constant that we will expect in a storage buffer.
1406 const bool module_scope_constant_external_init =
1407 (GV.getType()->getPointerAddressSpace() == AddressSpace::Constant) &&
1408 clspv::Option::ModuleConstantsInStorageBuffer();
1409 if (!module_scope_constant_external_init) {
1410 FindConstant(GV.getInitializer());
1411 }
David Neto22f144c2017-06-12 14:26:21 -04001412 }
1413}
1414
1415void SPIRVProducerPass::FindConstantPerFunc(Function &F) {
1416 // Investigate constants in function body.
1417 for (BasicBlock &BB : F) {
1418 for (Instruction &I : BB) {
David Neto862b7d82018-06-14 18:48:37 -04001419 if (auto *call = dyn_cast<CallInst>(&I)) {
1420 auto name = call->getCalledFunction()->getName();
Kévin Petitdf71de32019-04-09 14:09:50 +01001421 if (name == clspv::LiteralSamplerFunction()) {
David Neto862b7d82018-06-14 18:48:37 -04001422 // We've handled these constants elsewhere, so skip it.
1423 continue;
1424 }
Alan Baker202c8c72018-08-13 13:47:44 -04001425 if (name.startswith(clspv::ResourceAccessorFunction())) {
1426 continue;
1427 }
1428 if (name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001429 continue;
1430 }
Kévin Petit617a76d2019-04-04 13:54:16 +01001431 if (name.startswith(clspv::SPIRVOpIntrinsicFunction())) {
1432 // Skip the first operand that has the SPIR-V Opcode
1433 for (unsigned i = 1; i < I.getNumOperands(); i++) {
1434 if (isa<Constant>(I.getOperand(i)) &&
1435 !isa<GlobalValue>(I.getOperand(i))) {
1436 FindConstant(I.getOperand(i));
1437 }
1438 }
1439 continue;
1440 }
David Neto22f144c2017-06-12 14:26:21 -04001441 }
1442
1443 if (isa<AllocaInst>(I)) {
1444 // Alloca instruction has constant for the number of element. Ignore it.
1445 continue;
1446 } else if (isa<ShuffleVectorInst>(I)) {
1447 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1448 // Ignore constant for mask of shuffle vector instruction.
1449 if (i == 2) {
1450 continue;
1451 }
1452
1453 if (isa<Constant>(I.getOperand(i)) &&
1454 !isa<GlobalValue>(I.getOperand(i))) {
1455 FindConstant(I.getOperand(i));
1456 }
1457 }
1458
1459 continue;
1460 } else if (isa<InsertElementInst>(I)) {
1461 // Handle InsertElement with <4 x i8> specially.
1462 Type *CompositeTy = I.getOperand(0)->getType();
1463 if (is4xi8vec(CompositeTy)) {
1464 LLVMContext &Context = CompositeTy->getContext();
1465 if (isa<Constant>(I.getOperand(0))) {
1466 FindConstant(I.getOperand(0));
1467 }
1468
1469 if (isa<Constant>(I.getOperand(1))) {
1470 FindConstant(I.getOperand(1));
1471 }
1472
1473 // Add mask constant 0xFF.
1474 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1475 FindConstant(CstFF);
1476
1477 // Add shift amount constant.
1478 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
1479 uint64_t Idx = CI->getZExtValue();
1480 Constant *CstShiftAmount =
1481 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1482 FindConstant(CstShiftAmount);
1483 }
1484
1485 continue;
1486 }
1487
1488 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1489 // Ignore constant for index of InsertElement instruction.
1490 if (i == 2) {
1491 continue;
1492 }
1493
1494 if (isa<Constant>(I.getOperand(i)) &&
1495 !isa<GlobalValue>(I.getOperand(i))) {
1496 FindConstant(I.getOperand(i));
1497 }
1498 }
1499
1500 continue;
1501 } else if (isa<ExtractElementInst>(I)) {
1502 // Handle ExtractElement with <4 x i8> specially.
1503 Type *CompositeTy = I.getOperand(0)->getType();
1504 if (is4xi8vec(CompositeTy)) {
1505 LLVMContext &Context = CompositeTy->getContext();
1506 if (isa<Constant>(I.getOperand(0))) {
1507 FindConstant(I.getOperand(0));
1508 }
1509
1510 // Add mask constant 0xFF.
1511 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1512 FindConstant(CstFF);
1513
1514 // Add shift amount constant.
1515 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1516 uint64_t Idx = CI->getZExtValue();
1517 Constant *CstShiftAmount =
1518 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1519 FindConstant(CstShiftAmount);
1520 } else {
1521 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
1522 FindConstant(Cst8);
1523 }
1524
1525 continue;
1526 }
1527
1528 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1529 // Ignore constant for index of ExtractElement instruction.
1530 if (i == 1) {
1531 continue;
1532 }
1533
1534 if (isa<Constant>(I.getOperand(i)) &&
1535 !isa<GlobalValue>(I.getOperand(i))) {
1536 FindConstant(I.getOperand(i));
1537 }
1538 }
1539
1540 continue;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001541 } else if ((Instruction::Xor == I.getOpcode()) &&
1542 I.getType()->isIntegerTy(1)) {
1543 // We special case for Xor where the type is i1 and one of the arguments
1544 // is a constant 1 (true), this is an OpLogicalNot in SPIR-V, and we
1545 // don't need the constant
David Neto22f144c2017-06-12 14:26:21 -04001546 bool foundConstantTrue = false;
1547 for (Use &Op : I.operands()) {
1548 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1549 auto CI = cast<ConstantInt>(Op);
1550
1551 if (CI->isZero() || foundConstantTrue) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05001552 // If we already found the true constant, we might (probably only
1553 // on -O0) have an OpLogicalNot which is taking a constant
1554 // argument, so discover it anyway.
David Neto22f144c2017-06-12 14:26:21 -04001555 FindConstant(Op);
1556 } else {
1557 foundConstantTrue = true;
1558 }
1559 }
1560 }
1561
1562 continue;
David Netod2de94a2017-08-28 17:27:47 -04001563 } else if (isa<TruncInst>(I)) {
alan-bakerb39c8262019-03-08 14:03:37 -05001564 // Special case if i8 is not generally handled.
1565 if (!clspv::Option::Int8Support()) {
1566 // For truncation to i8 we mask against 255.
1567 Type *ToTy = I.getType();
1568 if (8u == ToTy->getPrimitiveSizeInBits()) {
1569 LLVMContext &Context = ToTy->getContext();
1570 Constant *Cst255 =
1571 ConstantInt::get(Type::getInt32Ty(Context), 0xff);
1572 FindConstant(Cst255);
1573 }
David Netod2de94a2017-08-28 17:27:47 -04001574 }
Neil Henning39672102017-09-29 14:33:13 +01001575 } else if (isa<AtomicRMWInst>(I)) {
1576 LLVMContext &Context = I.getContext();
1577
1578 FindConstant(
1579 ConstantInt::get(Type::getInt32Ty(Context), spv::ScopeDevice));
1580 FindConstant(ConstantInt::get(
1581 Type::getInt32Ty(Context),
1582 spv::MemorySemanticsUniformMemoryMask |
1583 spv::MemorySemanticsSequentiallyConsistentMask));
David Neto22f144c2017-06-12 14:26:21 -04001584 }
1585
1586 for (Use &Op : I.operands()) {
1587 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1588 FindConstant(Op);
1589 }
1590 }
1591 }
1592 }
1593}
1594
1595void SPIRVProducerPass::FindConstant(Value *V) {
David Neto22f144c2017-06-12 14:26:21 -04001596 ValueList &CstList = getConstantList();
1597
David Netofb9a7972017-08-25 17:08:24 -04001598 // If V is already tracked, ignore it.
1599 if (0 != CstList.idFor(V)) {
David Neto22f144c2017-06-12 14:26:21 -04001600 return;
1601 }
1602
David Neto862b7d82018-06-14 18:48:37 -04001603 if (isa<GlobalValue>(V) && clspv::Option::ModuleConstantsInStorageBuffer()) {
1604 return;
1605 }
1606
David Neto22f144c2017-06-12 14:26:21 -04001607 Constant *Cst = cast<Constant>(V);
David Neto862b7d82018-06-14 18:48:37 -04001608 Type *CstTy = Cst->getType();
David Neto22f144c2017-06-12 14:26:21 -04001609
1610 // Handle constant with <4 x i8> type specially.
David Neto22f144c2017-06-12 14:26:21 -04001611 if (is4xi8vec(CstTy)) {
1612 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001613 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001614 }
1615 }
1616
1617 if (Cst->getNumOperands()) {
1618 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end(); I != E;
1619 ++I) {
1620 FindConstant(*I);
1621 }
1622
David Netofb9a7972017-08-25 17:08:24 -04001623 CstList.insert(Cst);
David Neto22f144c2017-06-12 14:26:21 -04001624 return;
1625 } else if (const ConstantDataSequential *CDS =
1626 dyn_cast<ConstantDataSequential>(Cst)) {
1627 // Add constants for each element to constant list.
1628 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
1629 Constant *EleCst = CDS->getElementAsConstant(i);
1630 FindConstant(EleCst);
1631 }
1632 }
1633
1634 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001635 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001636 }
1637}
1638
1639spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1640 switch (AddrSpace) {
1641 default:
1642 llvm_unreachable("Unsupported OpenCL address space");
1643 case AddressSpace::Private:
1644 return spv::StorageClassFunction;
1645 case AddressSpace::Global:
David Neto22f144c2017-06-12 14:26:21 -04001646 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001647 case AddressSpace::Constant:
1648 return clspv::Option::ConstantArgsInUniformBuffer()
1649 ? spv::StorageClassUniform
1650 : spv::StorageClassStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -04001651 case AddressSpace::Input:
1652 return spv::StorageClassInput;
1653 case AddressSpace::Local:
1654 return spv::StorageClassWorkgroup;
1655 case AddressSpace::UniformConstant:
1656 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001657 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001658 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001659 case AddressSpace::ModuleScopePrivate:
1660 return spv::StorageClassPrivate;
1661 }
1662}
1663
David Neto862b7d82018-06-14 18:48:37 -04001664spv::StorageClass
1665SPIRVProducerPass::GetStorageClassForArgKind(clspv::ArgKind arg_kind) const {
1666 switch (arg_kind) {
1667 case clspv::ArgKind::Buffer:
1668 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001669 case clspv::ArgKind::BufferUBO:
1670 return spv::StorageClassUniform;
David Neto862b7d82018-06-14 18:48:37 -04001671 case clspv::ArgKind::Pod:
1672 return clspv::Option::PodArgsInUniformBuffer()
1673 ? spv::StorageClassUniform
1674 : spv::StorageClassStorageBuffer;
1675 case clspv::ArgKind::Local:
1676 return spv::StorageClassWorkgroup;
1677 case clspv::ArgKind::ReadOnlyImage:
1678 case clspv::ArgKind::WriteOnlyImage:
1679 case clspv::ArgKind::Sampler:
1680 return spv::StorageClassUniformConstant;
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001681 default:
1682 llvm_unreachable("Unsupported storage class for argument kind");
David Neto862b7d82018-06-14 18:48:37 -04001683 }
1684}
1685
David Neto22f144c2017-06-12 14:26:21 -04001686spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1687 return StringSwitch<spv::BuiltIn>(Name)
1688 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1689 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1690 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1691 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1692 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
1693 .Default(spv::BuiltInMax);
1694}
1695
1696void SPIRVProducerPass::GenerateExtInstImport() {
1697 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1698 uint32_t &ExtInstImportID = getOpExtInstImportID();
1699
1700 //
1701 // Generate OpExtInstImport.
1702 //
1703 // Ops[0] ... Ops[n] = Name (Literal String)
David Neto22f144c2017-06-12 14:26:21 -04001704 ExtInstImportID = nextID;
David Neto87846742018-04-11 17:36:22 -04001705 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpExtInstImport, nextID++,
1706 MkString("GLSL.std.450")));
David Neto22f144c2017-06-12 14:26:21 -04001707}
1708
alan-bakerb6b09dc2018-11-08 16:59:28 -05001709void SPIRVProducerPass::GenerateSPIRVTypes(LLVMContext &Context,
1710 Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04001711 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1712 ValueMapType &VMap = getValueMap();
1713 ValueMapType &AllocatedVMap = getAllocatedValueMap();
Alan Bakerfcda9482018-10-02 17:09:59 -04001714 const auto &DL = module.getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04001715
1716 // Map for OpTypeRuntimeArray. If argument has pointer type, 2 spirv type
1717 // instructions are generated. They are OpTypePointer and OpTypeRuntimeArray.
1718 DenseMap<Type *, uint32_t> OpRuntimeTyMap;
1719
1720 for (Type *Ty : getTypeList()) {
1721 // Update TypeMap with nextID for reference later.
1722 TypeMap[Ty] = nextID;
1723
1724 switch (Ty->getTypeID()) {
1725 default: {
1726 Ty->print(errs());
1727 llvm_unreachable("Unsupported type???");
1728 break;
1729 }
1730 case Type::MetadataTyID:
1731 case Type::LabelTyID: {
1732 // Ignore these types.
1733 break;
1734 }
1735 case Type::PointerTyID: {
1736 PointerType *PTy = cast<PointerType>(Ty);
1737 unsigned AddrSpace = PTy->getAddressSpace();
1738
1739 // For the purposes of our Vulkan SPIR-V type system, constant and global
1740 // are conflated.
1741 bool UseExistingOpTypePointer = false;
1742 if (AddressSpace::Constant == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001743 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1744 AddrSpace = AddressSpace::Global;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001745 // Check to see if we already created this type (for instance, if we
1746 // had a constant <type>* and a global <type>*, the type would be
1747 // created by one of these types, and shared by both).
Alan Bakerfcda9482018-10-02 17:09:59 -04001748 auto GlobalTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1749 if (0 < TypeMap.count(GlobalTy)) {
1750 TypeMap[PTy] = TypeMap[GlobalTy];
1751 UseExistingOpTypePointer = true;
1752 break;
1753 }
David Neto22f144c2017-06-12 14:26:21 -04001754 }
1755 } else if (AddressSpace::Global == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001756 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1757 AddrSpace = AddressSpace::Constant;
David Neto22f144c2017-06-12 14:26:21 -04001758
alan-bakerb6b09dc2018-11-08 16:59:28 -05001759 // Check to see if we already created this type (for instance, if we
1760 // had a constant <type>* and a global <type>*, the type would be
1761 // created by one of these types, and shared by both).
1762 auto ConstantTy =
1763 PTy->getPointerElementType()->getPointerTo(AddrSpace);
Alan Bakerfcda9482018-10-02 17:09:59 -04001764 if (0 < TypeMap.count(ConstantTy)) {
1765 TypeMap[PTy] = TypeMap[ConstantTy];
1766 UseExistingOpTypePointer = true;
1767 }
David Neto22f144c2017-06-12 14:26:21 -04001768 }
1769 }
1770
David Neto862b7d82018-06-14 18:48:37 -04001771 const bool HasArgUser = true;
David Neto22f144c2017-06-12 14:26:21 -04001772
David Neto862b7d82018-06-14 18:48:37 -04001773 if (HasArgUser && !UseExistingOpTypePointer) {
David Neto22f144c2017-06-12 14:26:21 -04001774 //
1775 // Generate OpTypePointer.
1776 //
1777
1778 // OpTypePointer
1779 // Ops[0] = Storage Class
1780 // Ops[1] = Element Type ID
1781 SPIRVOperandList Ops;
1782
David Neto257c3892018-04-11 13:19:45 -04001783 Ops << MkNum(GetStorageClass(AddrSpace))
1784 << MkId(lookupType(PTy->getElementType()));
David Neto22f144c2017-06-12 14:26:21 -04001785
David Neto87846742018-04-11 17:36:22 -04001786 auto *Inst = new SPIRVInstruction(spv::OpTypePointer, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001787 SPIRVInstList.push_back(Inst);
1788 }
David Neto22f144c2017-06-12 14:26:21 -04001789 break;
1790 }
1791 case Type::StructTyID: {
David Neto22f144c2017-06-12 14:26:21 -04001792 StructType *STy = cast<StructType>(Ty);
1793
1794 // Handle sampler type.
1795 if (STy->isOpaque()) {
1796 if (STy->getName().equals("opencl.sampler_t")) {
1797 //
1798 // Generate OpTypeSampler
1799 //
1800 // Empty Ops.
1801 SPIRVOperandList Ops;
1802
David Neto87846742018-04-11 17:36:22 -04001803 auto *Inst = new SPIRVInstruction(spv::OpTypeSampler, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001804 SPIRVInstList.push_back(Inst);
1805 break;
1806 } else if (STy->getName().equals("opencl.image2d_ro_t") ||
1807 STy->getName().equals("opencl.image2d_wo_t") ||
1808 STy->getName().equals("opencl.image3d_ro_t") ||
1809 STy->getName().equals("opencl.image3d_wo_t")) {
1810 //
1811 // Generate OpTypeImage
1812 //
1813 // Ops[0] = Sampled Type ID
1814 // Ops[1] = Dim ID
1815 // Ops[2] = Depth (Literal Number)
1816 // Ops[3] = Arrayed (Literal Number)
1817 // Ops[4] = MS (Literal Number)
1818 // Ops[5] = Sampled (Literal Number)
1819 // Ops[6] = Image Format ID
1820 //
1821 SPIRVOperandList Ops;
1822
1823 // TODO: Changed Sampled Type according to situations.
1824 uint32_t SampledTyID = lookupType(Type::getFloatTy(Context));
David Neto257c3892018-04-11 13:19:45 -04001825 Ops << MkId(SampledTyID);
David Neto22f144c2017-06-12 14:26:21 -04001826
1827 spv::Dim DimID = spv::Dim2D;
1828 if (STy->getName().equals("opencl.image3d_ro_t") ||
1829 STy->getName().equals("opencl.image3d_wo_t")) {
1830 DimID = spv::Dim3D;
1831 }
David Neto257c3892018-04-11 13:19:45 -04001832 Ops << MkNum(DimID);
David Neto22f144c2017-06-12 14:26:21 -04001833
1834 // TODO: Set up Depth.
David Neto257c3892018-04-11 13:19:45 -04001835 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001836
1837 // TODO: Set up Arrayed.
David Neto257c3892018-04-11 13:19:45 -04001838 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001839
1840 // TODO: Set up MS.
David Neto257c3892018-04-11 13:19:45 -04001841 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001842
1843 // TODO: Set up Sampled.
1844 //
1845 // From Spec
1846 //
1847 // 0 indicates this is only known at run time, not at compile time
1848 // 1 indicates will be used with sampler
1849 // 2 indicates will be used without a sampler (a storage image)
1850 uint32_t Sampled = 1;
1851 if (STy->getName().equals("opencl.image2d_wo_t") ||
1852 STy->getName().equals("opencl.image3d_wo_t")) {
1853 Sampled = 2;
1854 }
David Neto257c3892018-04-11 13:19:45 -04001855 Ops << MkNum(Sampled);
David Neto22f144c2017-06-12 14:26:21 -04001856
1857 // TODO: Set up Image Format.
David Neto257c3892018-04-11 13:19:45 -04001858 Ops << MkNum(spv::ImageFormatUnknown);
David Neto22f144c2017-06-12 14:26:21 -04001859
David Neto87846742018-04-11 17:36:22 -04001860 auto *Inst = new SPIRVInstruction(spv::OpTypeImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001861 SPIRVInstList.push_back(Inst);
1862 break;
1863 }
1864 }
1865
1866 //
1867 // Generate OpTypeStruct
1868 //
1869 // Ops[0] ... Ops[n] = Member IDs
1870 SPIRVOperandList Ops;
1871
1872 for (auto *EleTy : STy->elements()) {
David Neto862b7d82018-06-14 18:48:37 -04001873 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04001874 }
1875
David Neto22f144c2017-06-12 14:26:21 -04001876 uint32_t STyID = nextID;
1877
alan-bakerb6b09dc2018-11-08 16:59:28 -05001878 auto *Inst = new SPIRVInstruction(spv::OpTypeStruct, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001879 SPIRVInstList.push_back(Inst);
1880
1881 // Generate OpMemberDecorate.
1882 auto DecoInsertPoint =
1883 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
1884 [](SPIRVInstruction *Inst) -> bool {
1885 return Inst->getOpcode() != spv::OpDecorate &&
1886 Inst->getOpcode() != spv::OpMemberDecorate &&
1887 Inst->getOpcode() != spv::OpExtInstImport;
1888 });
1889
David Netoc463b372017-08-10 15:32:21 -04001890 const auto StructLayout = DL.getStructLayout(STy);
Alan Bakerfcda9482018-10-02 17:09:59 -04001891 // Search for the correct offsets if this type was remapped.
1892 std::vector<uint32_t> *offsets = nullptr;
1893 auto iter = RemappedUBOTypeOffsets.find(STy);
1894 if (iter != RemappedUBOTypeOffsets.end()) {
1895 offsets = &iter->second;
1896 }
David Netoc463b372017-08-10 15:32:21 -04001897
David Neto862b7d82018-06-14 18:48:37 -04001898 // #error TODO(dneto): Only do this if in TypesNeedingLayout.
David Neto22f144c2017-06-12 14:26:21 -04001899 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
1900 MemberIdx++) {
1901 // Ops[0] = Structure Type ID
1902 // Ops[1] = Member Index(Literal Number)
1903 // Ops[2] = Decoration (Offset)
1904 // Ops[3] = Byte Offset (Literal Number)
1905 Ops.clear();
1906
David Neto257c3892018-04-11 13:19:45 -04001907 Ops << MkId(STyID) << MkNum(MemberIdx) << MkNum(spv::DecorationOffset);
David Neto22f144c2017-06-12 14:26:21 -04001908
alan-bakerb6b09dc2018-11-08 16:59:28 -05001909 auto ByteOffset =
1910 static_cast<uint32_t>(StructLayout->getElementOffset(MemberIdx));
Alan Bakerfcda9482018-10-02 17:09:59 -04001911 if (offsets) {
1912 ByteOffset = (*offsets)[MemberIdx];
1913 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05001914 // const auto ByteOffset =
Alan Bakerfcda9482018-10-02 17:09:59 -04001915 // uint32_t(StructLayout->getElementOffset(MemberIdx));
David Neto257c3892018-04-11 13:19:45 -04001916 Ops << MkNum(ByteOffset);
David Neto22f144c2017-06-12 14:26:21 -04001917
David Neto87846742018-04-11 17:36:22 -04001918 auto *DecoInst = new SPIRVInstruction(spv::OpMemberDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001919 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04001920 }
1921
1922 // Generate OpDecorate.
David Neto862b7d82018-06-14 18:48:37 -04001923 if (StructTypesNeedingBlock.idFor(STy)) {
1924 Ops.clear();
1925 // Use Block decorations with StorageBuffer storage class.
1926 Ops << MkId(STyID) << MkNum(spv::DecorationBlock);
David Neto22f144c2017-06-12 14:26:21 -04001927
David Neto862b7d82018-06-14 18:48:37 -04001928 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
1929 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04001930 }
1931 break;
1932 }
1933 case Type::IntegerTyID: {
1934 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
1935
1936 if (BitWidth == 1) {
David Neto87846742018-04-11 17:36:22 -04001937 auto *Inst = new SPIRVInstruction(spv::OpTypeBool, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04001938 SPIRVInstList.push_back(Inst);
1939 } else {
alan-bakerb39c8262019-03-08 14:03:37 -05001940 if (!clspv::Option::Int8Support()) {
1941 // i8 is added to TypeMap as i32.
1942 // No matter what LLVM type is requested first, always alias the
1943 // second one's SPIR-V type to be the same as the one we generated
1944 // first.
1945 unsigned aliasToWidth = 0;
1946 if (BitWidth == 8) {
1947 aliasToWidth = 32;
1948 BitWidth = 32;
1949 } else if (BitWidth == 32) {
1950 aliasToWidth = 8;
1951 }
1952 if (aliasToWidth) {
1953 Type *otherType = Type::getIntNTy(Ty->getContext(), aliasToWidth);
1954 auto where = TypeMap.find(otherType);
1955 if (where == TypeMap.end()) {
1956 // Go ahead and make it, but also map the other type to it.
1957 TypeMap[otherType] = nextID;
1958 } else {
1959 // Alias this SPIR-V type the existing type.
1960 TypeMap[Ty] = where->second;
1961 break;
1962 }
David Neto391aeb12017-08-26 15:51:58 -04001963 }
David Neto22f144c2017-06-12 14:26:21 -04001964 }
1965
David Neto257c3892018-04-11 13:19:45 -04001966 SPIRVOperandList Ops;
1967 Ops << MkNum(BitWidth) << MkNum(0 /* not signed */);
David Neto22f144c2017-06-12 14:26:21 -04001968
1969 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04001970 new SPIRVInstruction(spv::OpTypeInt, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04001971 }
1972 break;
1973 }
1974 case Type::HalfTyID:
1975 case Type::FloatTyID:
1976 case Type::DoubleTyID: {
1977 SPIRVOperand *WidthOp = new SPIRVOperand(
1978 SPIRVOperandType::LITERAL_INTEGER, Ty->getPrimitiveSizeInBits());
1979
1980 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04001981 new SPIRVInstruction(spv::OpTypeFloat, nextID++, WidthOp));
David Neto22f144c2017-06-12 14:26:21 -04001982 break;
1983 }
1984 case Type::ArrayTyID: {
David Neto22f144c2017-06-12 14:26:21 -04001985 ArrayType *ArrTy = cast<ArrayType>(Ty);
David Neto862b7d82018-06-14 18:48:37 -04001986 const uint64_t Length = ArrTy->getArrayNumElements();
1987 if (Length == 0) {
1988 // By convention, map it to a RuntimeArray.
David Neto22f144c2017-06-12 14:26:21 -04001989
David Neto862b7d82018-06-14 18:48:37 -04001990 // Only generate the type once.
1991 // TODO(dneto): Can it ever be generated more than once?
1992 // Doesn't LLVM type uniqueness guarantee we'll only see this
1993 // once?
1994 Type *EleTy = ArrTy->getArrayElementType();
1995 if (OpRuntimeTyMap.count(EleTy) == 0) {
1996 uint32_t OpTypeRuntimeArrayID = nextID;
1997 OpRuntimeTyMap[Ty] = nextID;
David Neto22f144c2017-06-12 14:26:21 -04001998
David Neto862b7d82018-06-14 18:48:37 -04001999 //
2000 // Generate OpTypeRuntimeArray.
2001 //
David Neto22f144c2017-06-12 14:26:21 -04002002
David Neto862b7d82018-06-14 18:48:37 -04002003 // OpTypeRuntimeArray
2004 // Ops[0] = Element Type ID
2005 SPIRVOperandList Ops;
2006 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04002007
David Neto862b7d82018-06-14 18:48:37 -04002008 SPIRVInstList.push_back(
2009 new SPIRVInstruction(spv::OpTypeRuntimeArray, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002010
David Neto862b7d82018-06-14 18:48:37 -04002011 if (Hack_generate_runtime_array_stride_early) {
2012 // Generate OpDecorate.
2013 auto DecoInsertPoint = std::find_if(
2014 SPIRVInstList.begin(), SPIRVInstList.end(),
2015 [](SPIRVInstruction *Inst) -> bool {
2016 return Inst->getOpcode() != spv::OpDecorate &&
2017 Inst->getOpcode() != spv::OpMemberDecorate &&
2018 Inst->getOpcode() != spv::OpExtInstImport;
2019 });
David Neto22f144c2017-06-12 14:26:21 -04002020
David Neto862b7d82018-06-14 18:48:37 -04002021 // Ops[0] = Target ID
2022 // Ops[1] = Decoration (ArrayStride)
2023 // Ops[2] = Stride Number(Literal Number)
2024 Ops.clear();
David Neto85082642018-03-24 06:55:20 -07002025
David Neto862b7d82018-06-14 18:48:37 -04002026 Ops << MkId(OpTypeRuntimeArrayID)
2027 << MkNum(spv::DecorationArrayStride)
Alan Bakerfcda9482018-10-02 17:09:59 -04002028 << MkNum(static_cast<uint32_t>(GetTypeAllocSize(EleTy, DL)));
David Neto22f144c2017-06-12 14:26:21 -04002029
David Neto862b7d82018-06-14 18:48:37 -04002030 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
2031 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
2032 }
2033 }
David Neto22f144c2017-06-12 14:26:21 -04002034
David Neto862b7d82018-06-14 18:48:37 -04002035 } else {
David Neto22f144c2017-06-12 14:26:21 -04002036
David Neto862b7d82018-06-14 18:48:37 -04002037 //
2038 // Generate OpConstant and OpTypeArray.
2039 //
2040
2041 //
2042 // Generate OpConstant for array length.
2043 //
2044 // Ops[0] = Result Type ID
2045 // Ops[1] .. Ops[n] = Values LiteralNumber
2046 SPIRVOperandList Ops;
2047
2048 Type *LengthTy = Type::getInt32Ty(Context);
2049 uint32_t ResTyID = lookupType(LengthTy);
2050 Ops << MkId(ResTyID);
2051
2052 assert(Length < UINT32_MAX);
2053 Ops << MkNum(static_cast<uint32_t>(Length));
2054
2055 // Add constant for length to constant list.
2056 Constant *CstLength = ConstantInt::get(LengthTy, Length);
2057 AllocatedVMap[CstLength] = nextID;
2058 VMap[CstLength] = nextID;
2059 uint32_t LengthID = nextID;
2060
2061 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
2062 SPIRVInstList.push_back(CstInst);
2063
2064 // Remember to generate ArrayStride later
2065 getTypesNeedingArrayStride().insert(Ty);
2066
2067 //
2068 // Generate OpTypeArray.
2069 //
2070 // Ops[0] = Element Type ID
2071 // Ops[1] = Array Length Constant ID
2072 Ops.clear();
2073
2074 uint32_t EleTyID = lookupType(ArrTy->getElementType());
2075 Ops << MkId(EleTyID) << MkId(LengthID);
2076
2077 // Update TypeMap with nextID.
2078 TypeMap[Ty] = nextID;
2079
2080 auto *ArrayInst = new SPIRVInstruction(spv::OpTypeArray, nextID++, Ops);
2081 SPIRVInstList.push_back(ArrayInst);
2082 }
David Neto22f144c2017-06-12 14:26:21 -04002083 break;
2084 }
2085 case Type::VectorTyID: {
alan-bakerb39c8262019-03-08 14:03:37 -05002086 // <4 x i8> is changed to i32 if i8 is not generally supported.
2087 if (!clspv::Option::Int8Support() &&
2088 Ty->getVectorElementType() == Type::getInt8Ty(Context)) {
David Neto22f144c2017-06-12 14:26:21 -04002089 if (Ty->getVectorNumElements() == 4) {
2090 TypeMap[Ty] = lookupType(Ty->getVectorElementType());
2091 break;
2092 } else {
2093 Ty->print(errs());
2094 llvm_unreachable("Support above i8 vector type");
2095 }
2096 }
2097
2098 // Ops[0] = Component Type ID
2099 // Ops[1] = Component Count (Literal Number)
David Neto257c3892018-04-11 13:19:45 -04002100 SPIRVOperandList Ops;
2101 Ops << MkId(lookupType(Ty->getVectorElementType()))
2102 << MkNum(Ty->getVectorNumElements());
David Neto22f144c2017-06-12 14:26:21 -04002103
alan-bakerb6b09dc2018-11-08 16:59:28 -05002104 SPIRVInstruction *inst =
2105 new SPIRVInstruction(spv::OpTypeVector, nextID++, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002106 SPIRVInstList.push_back(inst);
David Neto22f144c2017-06-12 14:26:21 -04002107 break;
2108 }
2109 case Type::VoidTyID: {
David Neto87846742018-04-11 17:36:22 -04002110 auto *Inst = new SPIRVInstruction(spv::OpTypeVoid, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04002111 SPIRVInstList.push_back(Inst);
2112 break;
2113 }
2114 case Type::FunctionTyID: {
2115 // Generate SPIRV instruction for function type.
2116 FunctionType *FTy = cast<FunctionType>(Ty);
2117
2118 // Ops[0] = Return Type ID
2119 // Ops[1] ... Ops[n] = Parameter Type IDs
2120 SPIRVOperandList Ops;
2121
2122 // Find SPIRV instruction for return type
David Netoc6f3ab22018-04-06 18:02:31 -04002123 Ops << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04002124
2125 // Find SPIRV instructions for parameter types
2126 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
2127 // Find SPIRV instruction for parameter type.
2128 auto ParamTy = FTy->getParamType(k);
2129 if (ParamTy->isPointerTy()) {
2130 auto PointeeTy = ParamTy->getPointerElementType();
2131 if (PointeeTy->isStructTy() &&
2132 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
2133 ParamTy = PointeeTy;
2134 }
2135 }
2136
David Netoc6f3ab22018-04-06 18:02:31 -04002137 Ops << MkId(lookupType(ParamTy));
David Neto22f144c2017-06-12 14:26:21 -04002138 }
2139
David Neto87846742018-04-11 17:36:22 -04002140 auto *Inst = new SPIRVInstruction(spv::OpTypeFunction, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002141 SPIRVInstList.push_back(Inst);
2142 break;
2143 }
2144 }
2145 }
2146
2147 // Generate OpTypeSampledImage.
2148 TypeMapType &OpImageTypeMap = getImageTypeMap();
2149 for (auto &ImageType : OpImageTypeMap) {
2150 //
2151 // Generate OpTypeSampledImage.
2152 //
2153 // Ops[0] = Image Type ID
2154 //
2155 SPIRVOperandList Ops;
2156
2157 Type *ImgTy = ImageType.first;
David Netoc6f3ab22018-04-06 18:02:31 -04002158 Ops << MkId(TypeMap[ImgTy]);
David Neto22f144c2017-06-12 14:26:21 -04002159
2160 // Update OpImageTypeMap.
2161 ImageType.second = nextID;
2162
David Neto87846742018-04-11 17:36:22 -04002163 auto *Inst = new SPIRVInstruction(spv::OpTypeSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002164 SPIRVInstList.push_back(Inst);
2165 }
David Netoc6f3ab22018-04-06 18:02:31 -04002166
2167 // Generate types for pointer-to-local arguments.
Alan Baker202c8c72018-08-13 13:47:44 -04002168 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2169 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002170 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002171
2172 // Generate the spec constant.
2173 SPIRVOperandList Ops;
2174 Ops << MkId(lookupType(Type::getInt32Ty(Context))) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04002175 SPIRVInstList.push_back(
2176 new SPIRVInstruction(spv::OpSpecConstant, arg_info.array_size_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002177
2178 // Generate the array type.
2179 Ops.clear();
2180 // The element type must have been created.
2181 uint32_t elem_ty_id = lookupType(arg_info.elem_type);
2182 assert(elem_ty_id);
2183 Ops << MkId(elem_ty_id) << MkId(arg_info.array_size_id);
2184
2185 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002186 new SPIRVInstruction(spv::OpTypeArray, arg_info.array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002187
2188 Ops.clear();
2189 Ops << MkNum(spv::StorageClassWorkgroup) << MkId(arg_info.array_type_id);
David Neto87846742018-04-11 17:36:22 -04002190 SPIRVInstList.push_back(new SPIRVInstruction(
2191 spv::OpTypePointer, arg_info.ptr_array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002192 }
David Neto22f144c2017-06-12 14:26:21 -04002193}
2194
2195void SPIRVProducerPass::GenerateSPIRVConstants() {
2196 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2197 ValueMapType &VMap = getValueMap();
2198 ValueMapType &AllocatedVMap = getAllocatedValueMap();
2199 ValueList &CstList = getConstantList();
David Neto482550a2018-03-24 05:21:07 -07002200 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04002201
2202 for (uint32_t i = 0; i < CstList.size(); i++) {
David Netofb9a7972017-08-25 17:08:24 -04002203 // UniqueVector ids are 1-based.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002204 Constant *Cst = cast<Constant>(CstList[i + 1]);
David Neto22f144c2017-06-12 14:26:21 -04002205
2206 // OpTypeArray's constant was already generated.
David Netofb9a7972017-08-25 17:08:24 -04002207 if (AllocatedVMap.find_as(Cst) != AllocatedVMap.end()) {
David Neto22f144c2017-06-12 14:26:21 -04002208 continue;
2209 }
2210
David Netofb9a7972017-08-25 17:08:24 -04002211 // Set ValueMap with nextID for reference later.
David Neto22f144c2017-06-12 14:26:21 -04002212 VMap[Cst] = nextID;
2213
2214 //
2215 // Generate OpConstant.
2216 //
2217
2218 // Ops[0] = Result Type ID
2219 // Ops[1] .. Ops[n] = Values LiteralNumber
2220 SPIRVOperandList Ops;
2221
David Neto257c3892018-04-11 13:19:45 -04002222 Ops << MkId(lookupType(Cst->getType()));
David Neto22f144c2017-06-12 14:26:21 -04002223
2224 std::vector<uint32_t> LiteralNum;
David Neto22f144c2017-06-12 14:26:21 -04002225 spv::Op Opcode = spv::OpNop;
2226
2227 if (isa<UndefValue>(Cst)) {
2228 // Ops[0] = Result Type ID
David Netoc66b3352017-10-20 14:28:46 -04002229 Opcode = spv::OpUndef;
Alan Baker9bf93fb2018-08-28 16:59:26 -04002230 if (hack_undef && IsTypeNullable(Cst->getType())) {
2231 Opcode = spv::OpConstantNull;
David Netoc66b3352017-10-20 14:28:46 -04002232 }
David Neto22f144c2017-06-12 14:26:21 -04002233 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
2234 unsigned BitWidth = CI->getBitWidth();
2235 if (BitWidth == 1) {
2236 // If the bitwidth of constant is 1, generate OpConstantTrue or
2237 // OpConstantFalse.
2238 if (CI->getZExtValue()) {
2239 // Ops[0] = Result Type ID
2240 Opcode = spv::OpConstantTrue;
2241 } else {
2242 // Ops[0] = Result Type ID
2243 Opcode = spv::OpConstantFalse;
2244 }
David Neto22f144c2017-06-12 14:26:21 -04002245 } else {
2246 auto V = CI->getZExtValue();
2247 LiteralNum.push_back(V & 0xFFFFFFFF);
2248
2249 if (BitWidth > 32) {
2250 LiteralNum.push_back(V >> 32);
2251 }
2252
2253 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002254
David Neto257c3892018-04-11 13:19:45 -04002255 Ops << MkInteger(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002256 }
2257 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2258 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2259 Type *CFPTy = CFP->getType();
2260 if (CFPTy->isFloatTy()) {
2261 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
Kévin Petit02ee34e2019-04-04 19:03:22 +01002262 } else if (CFPTy->isDoubleTy()) {
2263 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2264 LiteralNum.push_back(FPVal >> 32);
David Neto22f144c2017-06-12 14:26:21 -04002265 } else {
2266 CFPTy->print(errs());
2267 llvm_unreachable("Implement this ConstantFP Type");
2268 }
2269
2270 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002271
David Neto257c3892018-04-11 13:19:45 -04002272 Ops << MkFloat(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002273 } else if (isa<ConstantDataSequential>(Cst) &&
2274 cast<ConstantDataSequential>(Cst)->isString()) {
2275 Cst->print(errs());
2276 llvm_unreachable("Implement this Constant");
2277
2278 } else if (const ConstantDataSequential *CDS =
2279 dyn_cast<ConstantDataSequential>(Cst)) {
David Neto49351ac2017-08-26 17:32:20 -04002280 // Let's convert <4 x i8> constant to int constant specially.
2281 // This case occurs when all the values are specified as constant
2282 // ints.
2283 Type *CstTy = Cst->getType();
2284 if (is4xi8vec(CstTy)) {
2285 LLVMContext &Context = CstTy->getContext();
2286
2287 //
2288 // Generate OpConstant with OpTypeInt 32 0.
2289 //
Neil Henning39672102017-09-29 14:33:13 +01002290 uint32_t IntValue = 0;
2291 for (unsigned k = 0; k < 4; k++) {
2292 const uint64_t Val = CDS->getElementAsInteger(k);
David Neto49351ac2017-08-26 17:32:20 -04002293 IntValue = (IntValue << 8) | (Val & 0xffu);
2294 }
2295
2296 Type *i32 = Type::getInt32Ty(Context);
2297 Constant *CstInt = ConstantInt::get(i32, IntValue);
2298 // If this constant is already registered on VMap, use it.
2299 if (VMap.count(CstInt)) {
2300 uint32_t CstID = VMap[CstInt];
2301 VMap[Cst] = CstID;
2302 continue;
2303 }
2304
David Neto257c3892018-04-11 13:19:45 -04002305 Ops << MkNum(IntValue);
David Neto49351ac2017-08-26 17:32:20 -04002306
David Neto87846742018-04-11 17:36:22 -04002307 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto49351ac2017-08-26 17:32:20 -04002308 SPIRVInstList.push_back(CstInst);
2309
2310 continue;
2311 }
2312
2313 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002314 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
2315 Constant *EleCst = CDS->getElementAsConstant(k);
2316 uint32_t EleCstID = VMap[EleCst];
David Neto257c3892018-04-11 13:19:45 -04002317 Ops << MkId(EleCstID);
David Neto22f144c2017-06-12 14:26:21 -04002318 }
2319
2320 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002321 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2322 // Let's convert <4 x i8> constant to int constant specially.
David Neto49351ac2017-08-26 17:32:20 -04002323 // This case occurs when at least one of the values is an undef.
David Neto22f144c2017-06-12 14:26:21 -04002324 Type *CstTy = Cst->getType();
2325 if (is4xi8vec(CstTy)) {
2326 LLVMContext &Context = CstTy->getContext();
2327
2328 //
2329 // Generate OpConstant with OpTypeInt 32 0.
2330 //
Neil Henning39672102017-09-29 14:33:13 +01002331 uint32_t IntValue = 0;
David Neto22f144c2017-06-12 14:26:21 -04002332 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2333 I != E; ++I) {
2334 uint64_t Val = 0;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002335 const Value *CV = *I;
Neil Henning39672102017-09-29 14:33:13 +01002336 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2337 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002338 }
David Neto49351ac2017-08-26 17:32:20 -04002339 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002340 }
2341
David Neto49351ac2017-08-26 17:32:20 -04002342 Type *i32 = Type::getInt32Ty(Context);
2343 Constant *CstInt = ConstantInt::get(i32, IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002344 // If this constant is already registered on VMap, use it.
2345 if (VMap.count(CstInt)) {
2346 uint32_t CstID = VMap[CstInt];
2347 VMap[Cst] = CstID;
David Neto19a1bad2017-08-25 15:01:41 -04002348 continue;
David Neto22f144c2017-06-12 14:26:21 -04002349 }
2350
David Neto257c3892018-04-11 13:19:45 -04002351 Ops << MkNum(IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002352
David Neto87846742018-04-11 17:36:22 -04002353 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002354 SPIRVInstList.push_back(CstInst);
2355
David Neto19a1bad2017-08-25 15:01:41 -04002356 continue;
David Neto22f144c2017-06-12 14:26:21 -04002357 }
2358
2359 // We use a constant composite in SPIR-V for our constant aggregate in
2360 // LLVM.
2361 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002362
2363 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
2364 // Look up the ID of the element of this aggregate (which we will
2365 // previously have created a constant for).
2366 uint32_t ElementConstantID = VMap[CA->getAggregateElement(k)];
2367
2368 // And add an operand to the composite we are constructing
David Neto257c3892018-04-11 13:19:45 -04002369 Ops << MkId(ElementConstantID);
David Neto22f144c2017-06-12 14:26:21 -04002370 }
2371 } else if (Cst->isNullValue()) {
2372 Opcode = spv::OpConstantNull;
David Neto22f144c2017-06-12 14:26:21 -04002373 } else {
2374 Cst->print(errs());
2375 llvm_unreachable("Unsupported Constant???");
2376 }
2377
alan-baker5b86ed72019-02-15 08:26:50 -05002378 if (Opcode == spv::OpConstantNull && Cst->getType()->isPointerTy()) {
2379 // Null pointer requires variable pointers.
2380 setVariablePointersCapabilities(Cst->getType()->getPointerAddressSpace());
2381 }
2382
David Neto87846742018-04-11 17:36:22 -04002383 auto *CstInst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002384 SPIRVInstList.push_back(CstInst);
2385 }
2386}
2387
2388void SPIRVProducerPass::GenerateSamplers(Module &M) {
2389 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto22f144c2017-06-12 14:26:21 -04002390
alan-bakerb6b09dc2018-11-08 16:59:28 -05002391 auto &sampler_map = getSamplerMap();
David Neto862b7d82018-06-14 18:48:37 -04002392 SamplerMapIndexToIDMap.clear();
David Neto22f144c2017-06-12 14:26:21 -04002393 DenseMap<unsigned, unsigned> SamplerLiteralToIDMap;
David Neto862b7d82018-06-14 18:48:37 -04002394 DenseMap<unsigned, unsigned> SamplerLiteralToDescriptorSetMap;
2395 DenseMap<unsigned, unsigned> SamplerLiteralToBindingMap;
David Neto22f144c2017-06-12 14:26:21 -04002396
David Neto862b7d82018-06-14 18:48:37 -04002397 // We might have samplers in the sampler map that are not used
2398 // in the translation unit. We need to allocate variables
2399 // for them and bindings too.
2400 DenseSet<unsigned> used_bindings;
David Neto22f144c2017-06-12 14:26:21 -04002401
Kévin Petitdf71de32019-04-09 14:09:50 +01002402 auto *var_fn = M.getFunction(clspv::LiteralSamplerFunction());
alan-bakerb6b09dc2018-11-08 16:59:28 -05002403 if (!var_fn)
2404 return;
David Neto862b7d82018-06-14 18:48:37 -04002405 for (auto user : var_fn->users()) {
2406 // Populate SamplerLiteralToDescriptorSetMap and
2407 // SamplerLiteralToBindingMap.
2408 //
2409 // Look for calls like
2410 // call %opencl.sampler_t addrspace(2)*
2411 // @clspv.sampler.var.literal(
2412 // i32 descriptor,
2413 // i32 binding,
2414 // i32 index-into-sampler-map)
alan-bakerb6b09dc2018-11-08 16:59:28 -05002415 if (auto *call = dyn_cast<CallInst>(user)) {
2416 const size_t index_into_sampler_map = static_cast<size_t>(
2417 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04002418 if (index_into_sampler_map >= sampler_map.size()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002419 errs() << "Out of bounds index to sampler map: "
2420 << index_into_sampler_map;
David Neto862b7d82018-06-14 18:48:37 -04002421 llvm_unreachable("bad sampler init: out of bounds");
2422 }
2423
2424 auto sampler_value = sampler_map[index_into_sampler_map].first;
2425 const auto descriptor_set = static_cast<unsigned>(
2426 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
2427 const auto binding = static_cast<unsigned>(
2428 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
2429
2430 SamplerLiteralToDescriptorSetMap[sampler_value] = descriptor_set;
2431 SamplerLiteralToBindingMap[sampler_value] = binding;
2432 used_bindings.insert(binding);
2433 }
2434 }
2435
2436 unsigned index = 0;
2437 for (auto SamplerLiteral : sampler_map) {
David Neto22f144c2017-06-12 14:26:21 -04002438 // Generate OpVariable.
2439 //
2440 // GIDOps[0] : Result Type ID
2441 // GIDOps[1] : Storage Class
2442 SPIRVOperandList Ops;
2443
David Neto257c3892018-04-11 13:19:45 -04002444 Ops << MkId(lookupType(SamplerTy))
2445 << MkNum(spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002446
David Neto862b7d82018-06-14 18:48:37 -04002447 auto sampler_var_id = nextID++;
2448 auto *Inst = new SPIRVInstruction(spv::OpVariable, sampler_var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002449 SPIRVInstList.push_back(Inst);
2450
David Neto862b7d82018-06-14 18:48:37 -04002451 SamplerMapIndexToIDMap[index] = sampler_var_id;
2452 SamplerLiteralToIDMap[SamplerLiteral.first] = sampler_var_id;
David Neto22f144c2017-06-12 14:26:21 -04002453
2454 // Find Insert Point for OpDecorate.
2455 auto DecoInsertPoint =
2456 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2457 [](SPIRVInstruction *Inst) -> bool {
2458 return Inst->getOpcode() != spv::OpDecorate &&
2459 Inst->getOpcode() != spv::OpMemberDecorate &&
2460 Inst->getOpcode() != spv::OpExtInstImport;
2461 });
2462
2463 // Ops[0] = Target ID
2464 // Ops[1] = Decoration (DescriptorSet)
2465 // Ops[2] = LiteralNumber according to Decoration
2466 Ops.clear();
2467
David Neto862b7d82018-06-14 18:48:37 -04002468 unsigned descriptor_set;
2469 unsigned binding;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002470 if (SamplerLiteralToBindingMap.find(SamplerLiteral.first) ==
2471 SamplerLiteralToBindingMap.end()) {
David Neto862b7d82018-06-14 18:48:37 -04002472 // This sampler is not actually used. Find the next one.
2473 for (binding = 0; used_bindings.count(binding); binding++)
2474 ;
2475 descriptor_set = 0; // Literal samplers always use descriptor set 0.
2476 used_bindings.insert(binding);
2477 } else {
2478 descriptor_set = SamplerLiteralToDescriptorSetMap[SamplerLiteral.first];
2479 binding = SamplerLiteralToBindingMap[SamplerLiteral.first];
alan-bakercff80152019-06-15 00:38:00 -04002480
2481 version0::DescriptorMapEntry::SamplerData sampler_data = {
2482 SamplerLiteral.first};
2483 descriptorMapEntries->emplace_back(std::move(sampler_data),
2484 descriptor_set, binding);
David Neto862b7d82018-06-14 18:48:37 -04002485 }
2486
2487 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationDescriptorSet)
2488 << MkNum(descriptor_set);
David Neto22f144c2017-06-12 14:26:21 -04002489
David Neto87846742018-04-11 17:36:22 -04002490 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002491 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2492
2493 // Ops[0] = Target ID
2494 // Ops[1] = Decoration (Binding)
2495 // Ops[2] = LiteralNumber according to Decoration
2496 Ops.clear();
David Neto862b7d82018-06-14 18:48:37 -04002497 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationBinding)
2498 << MkNum(binding);
David Neto22f144c2017-06-12 14:26:21 -04002499
David Neto87846742018-04-11 17:36:22 -04002500 auto *BindDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002501 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
David Neto862b7d82018-06-14 18:48:37 -04002502
2503 index++;
David Neto22f144c2017-06-12 14:26:21 -04002504 }
David Neto862b7d82018-06-14 18:48:37 -04002505}
David Neto22f144c2017-06-12 14:26:21 -04002506
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01002507void SPIRVProducerPass::GenerateResourceVars(Module &) {
David Neto862b7d82018-06-14 18:48:37 -04002508 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2509 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04002510
David Neto862b7d82018-06-14 18:48:37 -04002511 // Generate variables. Make one for each of resource var info object.
2512 for (auto *info : ModuleOrderedResourceVars) {
2513 Type *type = info->var_fn->getReturnType();
2514 // Remap the address space for opaque types.
2515 switch (info->arg_kind) {
2516 case clspv::ArgKind::Sampler:
2517 case clspv::ArgKind::ReadOnlyImage:
2518 case clspv::ArgKind::WriteOnlyImage:
2519 type = PointerType::get(type->getPointerElementType(),
2520 clspv::AddressSpace::UniformConstant);
2521 break;
2522 default:
2523 break;
2524 }
David Neto22f144c2017-06-12 14:26:21 -04002525
David Neto862b7d82018-06-14 18:48:37 -04002526 info->var_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04002527
David Neto862b7d82018-06-14 18:48:37 -04002528 const auto type_id = lookupType(type);
2529 const auto sc = GetStorageClassForArgKind(info->arg_kind);
2530 SPIRVOperandList Ops;
2531 Ops << MkId(type_id) << MkNum(sc);
David Neto22f144c2017-06-12 14:26:21 -04002532
David Neto862b7d82018-06-14 18:48:37 -04002533 auto *Inst = new SPIRVInstruction(spv::OpVariable, info->var_id, Ops);
2534 SPIRVInstList.push_back(Inst);
2535
2536 // Map calls to the variable-builtin-function.
2537 for (auto &U : info->var_fn->uses()) {
2538 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
2539 const auto set = unsigned(
2540 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
2541 const auto binding = unsigned(
2542 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
2543 if (set == info->descriptor_set && binding == info->binding) {
2544 switch (info->arg_kind) {
2545 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002546 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002547 case clspv::ArgKind::Pod:
2548 // The call maps to the variable directly.
2549 VMap[call] = info->var_id;
2550 break;
2551 case clspv::ArgKind::Sampler:
2552 case clspv::ArgKind::ReadOnlyImage:
2553 case clspv::ArgKind::WriteOnlyImage:
2554 // The call maps to a load we generate later.
2555 ResourceVarDeferredLoadCalls[call] = info->var_id;
2556 break;
2557 default:
2558 llvm_unreachable("Unhandled arg kind");
2559 }
2560 }
David Neto22f144c2017-06-12 14:26:21 -04002561 }
David Neto862b7d82018-06-14 18:48:37 -04002562 }
2563 }
David Neto22f144c2017-06-12 14:26:21 -04002564
David Neto862b7d82018-06-14 18:48:37 -04002565 // Generate associated decorations.
David Neto22f144c2017-06-12 14:26:21 -04002566
David Neto862b7d82018-06-14 18:48:37 -04002567 // Find Insert Point for OpDecorate.
2568 auto DecoInsertPoint =
2569 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2570 [](SPIRVInstruction *Inst) -> bool {
2571 return Inst->getOpcode() != spv::OpDecorate &&
2572 Inst->getOpcode() != spv::OpMemberDecorate &&
2573 Inst->getOpcode() != spv::OpExtInstImport;
2574 });
2575
2576 SPIRVOperandList Ops;
2577 for (auto *info : ModuleOrderedResourceVars) {
2578 // Decorate with DescriptorSet and Binding.
2579 Ops.clear();
2580 Ops << MkId(info->var_id) << MkNum(spv::DecorationDescriptorSet)
2581 << MkNum(info->descriptor_set);
2582 SPIRVInstList.insert(DecoInsertPoint,
2583 new SPIRVInstruction(spv::OpDecorate, Ops));
2584
2585 Ops.clear();
2586 Ops << MkId(info->var_id) << MkNum(spv::DecorationBinding)
2587 << MkNum(info->binding);
2588 SPIRVInstList.insert(DecoInsertPoint,
2589 new SPIRVInstruction(spv::OpDecorate, Ops));
2590
alan-bakere9308012019-03-15 10:25:13 -04002591 if (info->coherent) {
2592 // Decorate with Coherent if required for the variable.
2593 Ops.clear();
2594 Ops << MkId(info->var_id) << MkNum(spv::DecorationCoherent);
2595 SPIRVInstList.insert(DecoInsertPoint,
2596 new SPIRVInstruction(spv::OpDecorate, Ops));
2597 }
2598
David Neto862b7d82018-06-14 18:48:37 -04002599 // Generate NonWritable and NonReadable
2600 switch (info->arg_kind) {
2601 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002602 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002603 if (info->var_fn->getReturnType()->getPointerAddressSpace() ==
2604 clspv::AddressSpace::Constant) {
2605 Ops.clear();
2606 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
2607 SPIRVInstList.insert(DecoInsertPoint,
2608 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002609 }
David Neto862b7d82018-06-14 18:48:37 -04002610 break;
David Neto862b7d82018-06-14 18:48:37 -04002611 case clspv::ArgKind::WriteOnlyImage:
2612 Ops.clear();
2613 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonReadable);
2614 SPIRVInstList.insert(DecoInsertPoint,
2615 new SPIRVInstruction(spv::OpDecorate, Ops));
2616 break;
2617 default:
2618 break;
David Neto22f144c2017-06-12 14:26:21 -04002619 }
2620 }
2621}
2622
2623void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002624 Module &M = *GV.getParent();
David Neto22f144c2017-06-12 14:26:21 -04002625 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2626 ValueMapType &VMap = getValueMap();
2627 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07002628 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002629
2630 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2631 Type *Ty = GV.getType();
2632 PointerType *PTy = cast<PointerType>(Ty);
2633
2634 uint32_t InitializerID = 0;
2635
2636 // Workgroup size is handled differently (it goes into a constant)
2637 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2638 std::vector<bool> HasMDVec;
2639 uint32_t PrevXDimCst = 0xFFFFFFFF;
2640 uint32_t PrevYDimCst = 0xFFFFFFFF;
2641 uint32_t PrevZDimCst = 0xFFFFFFFF;
2642 for (Function &Func : *GV.getParent()) {
2643 if (Func.isDeclaration()) {
2644 continue;
2645 }
2646
2647 // We only need to check kernels.
2648 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2649 continue;
2650 }
2651
2652 if (const MDNode *MD =
2653 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2654 uint32_t CurXDimCst = static_cast<uint32_t>(
2655 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2656 uint32_t CurYDimCst = static_cast<uint32_t>(
2657 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2658 uint32_t CurZDimCst = static_cast<uint32_t>(
2659 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2660
2661 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2662 PrevZDimCst == 0xFFFFFFFF) {
2663 PrevXDimCst = CurXDimCst;
2664 PrevYDimCst = CurYDimCst;
2665 PrevZDimCst = CurZDimCst;
2666 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2667 CurZDimCst != PrevZDimCst) {
2668 llvm_unreachable(
2669 "reqd_work_group_size must be the same across all kernels");
2670 } else {
2671 continue;
2672 }
2673
2674 //
2675 // Generate OpConstantComposite.
2676 //
2677 // Ops[0] : Result Type ID
2678 // Ops[1] : Constant size for x dimension.
2679 // Ops[2] : Constant size for y dimension.
2680 // Ops[3] : Constant size for z dimension.
2681 SPIRVOperandList Ops;
2682
2683 uint32_t XDimCstID =
2684 VMap[mdconst::extract<ConstantInt>(MD->getOperand(0))];
2685 uint32_t YDimCstID =
2686 VMap[mdconst::extract<ConstantInt>(MD->getOperand(1))];
2687 uint32_t ZDimCstID =
2688 VMap[mdconst::extract<ConstantInt>(MD->getOperand(2))];
2689
2690 InitializerID = nextID;
2691
David Neto257c3892018-04-11 13:19:45 -04002692 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2693 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002694
David Neto87846742018-04-11 17:36:22 -04002695 auto *Inst =
2696 new SPIRVInstruction(spv::OpConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002697 SPIRVInstList.push_back(Inst);
2698
2699 HasMDVec.push_back(true);
2700 } else {
2701 HasMDVec.push_back(false);
2702 }
2703 }
2704
2705 // Check all kernels have same definitions for work_group_size.
2706 bool HasMD = false;
2707 if (!HasMDVec.empty()) {
2708 HasMD = HasMDVec[0];
2709 for (uint32_t i = 1; i < HasMDVec.size(); i++) {
2710 if (HasMD != HasMDVec[i]) {
2711 llvm_unreachable(
2712 "Kernels should have consistent work group size definition");
2713 }
2714 }
2715 }
2716
2717 // If all kernels do not have metadata for reqd_work_group_size, generate
2718 // OpSpecConstants for x/y/z dimension.
2719 if (!HasMD) {
2720 //
2721 // Generate OpSpecConstants for x/y/z dimension.
2722 //
2723 // Ops[0] : Result Type ID
2724 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
2725 uint32_t XDimCstID = 0;
2726 uint32_t YDimCstID = 0;
2727 uint32_t ZDimCstID = 0;
2728
David Neto22f144c2017-06-12 14:26:21 -04002729 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04002730 uint32_t result_type_id =
2731 lookupType(Ty->getPointerElementType()->getSequentialElementType());
David Neto22f144c2017-06-12 14:26:21 -04002732
David Neto257c3892018-04-11 13:19:45 -04002733 // X Dimension
2734 Ops << MkId(result_type_id) << MkNum(1);
2735 XDimCstID = nextID++;
2736 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002737 new SPIRVInstruction(spv::OpSpecConstant, XDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002738
2739 // Y Dimension
2740 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002741 Ops << MkId(result_type_id) << MkNum(1);
2742 YDimCstID = nextID++;
2743 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002744 new SPIRVInstruction(spv::OpSpecConstant, YDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002745
2746 // Z Dimension
2747 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002748 Ops << MkId(result_type_id) << MkNum(1);
2749 ZDimCstID = nextID++;
2750 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002751 new SPIRVInstruction(spv::OpSpecConstant, ZDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002752
David Neto257c3892018-04-11 13:19:45 -04002753 BuiltinDimVec.push_back(XDimCstID);
2754 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002755 BuiltinDimVec.push_back(ZDimCstID);
2756
David Neto22f144c2017-06-12 14:26:21 -04002757 //
2758 // Generate OpSpecConstantComposite.
2759 //
2760 // Ops[0] : Result Type ID
2761 // Ops[1] : Constant size for x dimension.
2762 // Ops[2] : Constant size for y dimension.
2763 // Ops[3] : Constant size for z dimension.
2764 InitializerID = nextID;
2765
2766 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002767 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2768 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002769
David Neto87846742018-04-11 17:36:22 -04002770 auto *Inst =
2771 new SPIRVInstruction(spv::OpSpecConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002772 SPIRVInstList.push_back(Inst);
2773 }
2774 }
2775
David Neto22f144c2017-06-12 14:26:21 -04002776 VMap[&GV] = nextID;
2777
2778 //
2779 // Generate OpVariable.
2780 //
2781 // GIDOps[0] : Result Type ID
2782 // GIDOps[1] : Storage Class
2783 SPIRVOperandList Ops;
2784
David Neto85082642018-03-24 06:55:20 -07002785 const auto AS = PTy->getAddressSpace();
David Netoc6f3ab22018-04-06 18:02:31 -04002786 Ops << MkId(lookupType(Ty)) << MkNum(GetStorageClass(AS));
David Neto22f144c2017-06-12 14:26:21 -04002787
David Neto85082642018-03-24 06:55:20 -07002788 const bool module_scope_constant_external_init =
David Neto862b7d82018-06-14 18:48:37 -04002789 (AS == AddressSpace::Constant) && GV.hasInitializer() &&
David Neto85082642018-03-24 06:55:20 -07002790 clspv::Option::ModuleConstantsInStorageBuffer();
2791
Kévin Petit23d5f182019-08-13 16:21:29 +01002792 if (GV.hasInitializer()) {
2793 auto GVInit = GV.getInitializer();
2794 if (!isa<UndefValue>(GVInit) && !module_scope_constant_external_init) {
2795 assert(VMap.count(GVInit) == 1);
2796 InitializerID = VMap[GVInit];
David Neto85082642018-03-24 06:55:20 -07002797 }
2798 }
Kévin Petit23d5f182019-08-13 16:21:29 +01002799
2800 if (0 != InitializerID) {
2801 // Emit the ID of the intiializer as part of the variable definition.
2802 Ops << MkId(InitializerID);
2803 }
David Neto85082642018-03-24 06:55:20 -07002804 const uint32_t var_id = nextID++;
2805
David Neto87846742018-04-11 17:36:22 -04002806 auto *Inst = new SPIRVInstruction(spv::OpVariable, var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002807 SPIRVInstList.push_back(Inst);
2808
2809 // If we have a builtin.
2810 if (spv::BuiltInMax != BuiltinType) {
2811 // Find Insert Point for OpDecorate.
2812 auto DecoInsertPoint =
2813 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2814 [](SPIRVInstruction *Inst) -> bool {
2815 return Inst->getOpcode() != spv::OpDecorate &&
2816 Inst->getOpcode() != spv::OpMemberDecorate &&
2817 Inst->getOpcode() != spv::OpExtInstImport;
2818 });
2819 //
2820 // Generate OpDecorate.
2821 //
2822 // DOps[0] = Target ID
2823 // DOps[1] = Decoration (Builtin)
2824 // DOps[2] = BuiltIn ID
2825 uint32_t ResultID;
2826
2827 // WorkgroupSize is different, we decorate the constant composite that has
2828 // its value, rather than the variable that we use to access the value.
2829 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2830 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04002831 // Save both the value and variable IDs for later.
2832 WorkgroupSizeValueID = InitializerID;
2833 WorkgroupSizeVarID = VMap[&GV];
David Neto22f144c2017-06-12 14:26:21 -04002834 } else {
2835 ResultID = VMap[&GV];
2836 }
2837
2838 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002839 DOps << MkId(ResultID) << MkNum(spv::DecorationBuiltIn)
2840 << MkNum(BuiltinType);
David Neto22f144c2017-06-12 14:26:21 -04002841
David Neto87846742018-04-11 17:36:22 -04002842 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, DOps);
David Neto22f144c2017-06-12 14:26:21 -04002843 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
David Neto85082642018-03-24 06:55:20 -07002844 } else if (module_scope_constant_external_init) {
2845 // This module scope constant is initialized from a storage buffer with data
2846 // provided by the host at binding 0 of the next descriptor set.
David Neto78383442018-06-15 20:31:56 -04002847 const uint32_t descriptor_set = TakeDescriptorIndex(&M);
David Neto85082642018-03-24 06:55:20 -07002848
David Neto862b7d82018-06-14 18:48:37 -04002849 // Emit the intializer to the descriptor map file.
David Neto85082642018-03-24 06:55:20 -07002850 // Use "kind,buffer" to indicate storage buffer. We might want to expand
2851 // that later to other types, like uniform buffer.
alan-bakerf5e5f692018-11-27 08:33:24 -05002852 std::string hexbytes;
2853 llvm::raw_string_ostream str(hexbytes);
2854 clspv::ConstantEmitter(DL, str).Emit(GV.getInitializer());
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002855 version0::DescriptorMapEntry::ConstantData constant_data = {ArgKind::Buffer,
2856 str.str()};
2857 descriptorMapEntries->emplace_back(std::move(constant_data), descriptor_set,
2858 0);
David Neto85082642018-03-24 06:55:20 -07002859
2860 // Find Insert Point for OpDecorate.
2861 auto DecoInsertPoint =
2862 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2863 [](SPIRVInstruction *Inst) -> bool {
2864 return Inst->getOpcode() != spv::OpDecorate &&
2865 Inst->getOpcode() != spv::OpMemberDecorate &&
2866 Inst->getOpcode() != spv::OpExtInstImport;
2867 });
2868
David Neto257c3892018-04-11 13:19:45 -04002869 // OpDecorate %var Binding <binding>
David Neto85082642018-03-24 06:55:20 -07002870 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002871 DOps << MkId(var_id) << MkNum(spv::DecorationBinding) << MkNum(0);
2872 DecoInsertPoint = SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04002873 DecoInsertPoint, new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto85082642018-03-24 06:55:20 -07002874
2875 // OpDecorate %var DescriptorSet <descriptor_set>
2876 DOps.clear();
David Neto257c3892018-04-11 13:19:45 -04002877 DOps << MkId(var_id) << MkNum(spv::DecorationDescriptorSet)
2878 << MkNum(descriptor_set);
David Netoc6f3ab22018-04-06 18:02:31 -04002879 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04002880 new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto22f144c2017-06-12 14:26:21 -04002881 }
2882}
2883
David Netoc6f3ab22018-04-06 18:02:31 -04002884void SPIRVProducerPass::GenerateWorkgroupVars() {
2885 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
Alan Baker202c8c72018-08-13 13:47:44 -04002886 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2887 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002888 LocalArgInfo &info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002889
2890 // Generate OpVariable.
2891 //
2892 // GIDOps[0] : Result Type ID
2893 // GIDOps[1] : Storage Class
2894 SPIRVOperandList Ops;
2895 Ops << MkId(info.ptr_array_type_id) << MkNum(spv::StorageClassWorkgroup);
2896
2897 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002898 new SPIRVInstruction(spv::OpVariable, info.variable_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002899 }
2900}
2901
David Neto862b7d82018-06-14 18:48:37 -04002902void SPIRVProducerPass::GenerateDescriptorMapInfo(const DataLayout &DL,
2903 Function &F) {
David Netoc5fb5242018-07-30 13:28:31 -04002904 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2905 return;
2906 }
David Neto862b7d82018-06-14 18:48:37 -04002907 // Gather the list of resources that are used by this function's arguments.
2908 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
2909
alan-bakerf5e5f692018-11-27 08:33:24 -05002910 // TODO(alan-baker): This should become unnecessary by fixing the rest of the
2911 // flow to generate pod_ubo arguments earlier.
David Neto862b7d82018-06-14 18:48:37 -04002912 auto remap_arg_kind = [](StringRef argKind) {
alan-bakerf5e5f692018-11-27 08:33:24 -05002913 std::string kind =
2914 clspv::Option::PodArgsInUniformBuffer() && argKind.equals("pod")
2915 ? "pod_ubo"
2916 : argKind;
2917 return GetArgKindFromName(kind);
David Neto862b7d82018-06-14 18:48:37 -04002918 };
2919
2920 auto *fty = F.getType()->getPointerElementType();
2921 auto *func_ty = dyn_cast<FunctionType>(fty);
2922
alan-baker038e9242019-04-19 22:14:41 -04002923 // If we've clustered POD arguments, then argument details are in metadata.
David Neto862b7d82018-06-14 18:48:37 -04002924 // If an argument maps to a resource variable, then get descriptor set and
2925 // binding from the resoure variable. Other info comes from the metadata.
2926 const auto *arg_map = F.getMetadata("kernel_arg_map");
2927 if (arg_map) {
2928 for (const auto &arg : arg_map->operands()) {
2929 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
Kévin PETITa353c832018-03-20 23:21:21 +00002930 assert(arg_node->getNumOperands() == 7);
David Neto862b7d82018-06-14 18:48:37 -04002931 const auto name =
2932 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
2933 const auto old_index =
2934 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
2935 // Remapped argument index
alan-bakerb6b09dc2018-11-08 16:59:28 -05002936 const size_t new_index = static_cast<size_t>(
2937 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04002938 const auto offset =
2939 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
Kévin PETITa353c832018-03-20 23:21:21 +00002940 const auto arg_size =
2941 dyn_extract<ConstantInt>(arg_node->getOperand(4))->getZExtValue();
David Neto862b7d82018-06-14 18:48:37 -04002942 const auto argKind = remap_arg_kind(
Kévin PETITa353c832018-03-20 23:21:21 +00002943 dyn_cast<MDString>(arg_node->getOperand(5))->getString());
David Neto862b7d82018-06-14 18:48:37 -04002944 const auto spec_id =
Kévin PETITa353c832018-03-20 23:21:21 +00002945 dyn_extract<ConstantInt>(arg_node->getOperand(6))->getSExtValue();
alan-bakerf5e5f692018-11-27 08:33:24 -05002946
2947 uint32_t descriptor_set = 0;
2948 uint32_t binding = 0;
2949 version0::DescriptorMapEntry::KernelArgData kernel_data = {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002950 F.getName(), name, static_cast<uint32_t>(old_index), argKind,
alan-bakerf5e5f692018-11-27 08:33:24 -05002951 static_cast<uint32_t>(spec_id),
2952 // This will be set below for pointer-to-local args.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002953 0, static_cast<uint32_t>(offset), static_cast<uint32_t>(arg_size)};
David Neto862b7d82018-06-14 18:48:37 -04002954 if (spec_id > 0) {
alan-bakerf5e5f692018-11-27 08:33:24 -05002955 kernel_data.local_element_size = static_cast<uint32_t>(GetTypeAllocSize(
2956 func_ty->getParamType(unsigned(new_index))->getPointerElementType(),
2957 DL));
David Neto862b7d82018-06-14 18:48:37 -04002958 } else {
2959 auto *info = resource_var_at_index[new_index];
2960 assert(info);
alan-bakerf5e5f692018-11-27 08:33:24 -05002961 descriptor_set = info->descriptor_set;
2962 binding = info->binding;
David Neto862b7d82018-06-14 18:48:37 -04002963 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002964 descriptorMapEntries->emplace_back(std::move(kernel_data), descriptor_set,
2965 binding);
David Neto862b7d82018-06-14 18:48:37 -04002966 }
2967 } else {
2968 // There is no argument map.
2969 // Take descriptor info from the resource variable calls.
Kévin PETITa353c832018-03-20 23:21:21 +00002970 // Take argument name and size from the arguments list.
David Neto862b7d82018-06-14 18:48:37 -04002971
2972 SmallVector<Argument *, 4> arguments;
2973 for (auto &arg : F.args()) {
2974 arguments.push_back(&arg);
2975 }
2976
2977 unsigned arg_index = 0;
2978 for (auto *info : resource_var_at_index) {
2979 if (info) {
Kévin PETITa353c832018-03-20 23:21:21 +00002980 auto arg = arguments[arg_index];
alan-bakerb6b09dc2018-11-08 16:59:28 -05002981 unsigned arg_size = 0;
Kévin PETITa353c832018-03-20 23:21:21 +00002982 if (info->arg_kind == clspv::ArgKind::Pod) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002983 arg_size = static_cast<uint32_t>(DL.getTypeStoreSize(arg->getType()));
Kévin PETITa353c832018-03-20 23:21:21 +00002984 }
2985
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002986 // Local pointer arguments are unused in this case. Offset is always
2987 // zero.
alan-bakerf5e5f692018-11-27 08:33:24 -05002988 version0::DescriptorMapEntry::KernelArgData kernel_data = {
2989 F.getName(), arg->getName(),
2990 arg_index, remap_arg_kind(clspv::GetArgKindName(info->arg_kind)),
2991 0, 0,
2992 0, arg_size};
2993 descriptorMapEntries->emplace_back(std::move(kernel_data),
2994 info->descriptor_set, info->binding);
David Neto862b7d82018-06-14 18:48:37 -04002995 }
2996 arg_index++;
2997 }
2998 // Generate mappings for pointer-to-local arguments.
2999 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
3000 Argument *arg = arguments[arg_index];
Alan Baker202c8c72018-08-13 13:47:44 -04003001 auto where = LocalArgSpecIds.find(arg);
3002 if (where != LocalArgSpecIds.end()) {
3003 auto &local_arg_info = LocalSpecIdInfoMap[where->second];
alan-bakerf5e5f692018-11-27 08:33:24 -05003004 // Pod arguments members are unused in this case.
3005 version0::DescriptorMapEntry::KernelArgData kernel_data = {
3006 F.getName(),
3007 arg->getName(),
3008 arg_index,
3009 ArgKind::Local,
3010 static_cast<uint32_t>(local_arg_info.spec_id),
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003011 static_cast<uint32_t>(
3012 GetTypeAllocSize(local_arg_info.elem_type, DL)),
alan-bakerf5e5f692018-11-27 08:33:24 -05003013 0,
3014 0};
3015 // Pointer-to-local arguments do not utilize descriptor set and binding.
3016 descriptorMapEntries->emplace_back(std::move(kernel_data), 0, 0);
David Neto862b7d82018-06-14 18:48:37 -04003017 }
3018 }
3019 }
3020}
3021
David Neto22f144c2017-06-12 14:26:21 -04003022void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
3023 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3024 ValueMapType &VMap = getValueMap();
3025 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04003026 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
3027 auto &GlobalConstArgSet = getGlobalConstArgSet();
3028
3029 FunctionType *FTy = F.getFunctionType();
3030
3031 //
David Neto22f144c2017-06-12 14:26:21 -04003032 // Generate OPFunction.
3033 //
3034
3035 // FOps[0] : Result Type ID
3036 // FOps[1] : Function Control
3037 // FOps[2] : Function Type ID
3038 SPIRVOperandList FOps;
3039
3040 // Find SPIRV instruction for return type.
David Neto257c3892018-04-11 13:19:45 -04003041 FOps << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04003042
3043 // Check function attributes for SPIRV Function Control.
3044 uint32_t FuncControl = spv::FunctionControlMaskNone;
3045 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
3046 FuncControl |= spv::FunctionControlInlineMask;
3047 }
3048 if (F.hasFnAttribute(Attribute::NoInline)) {
3049 FuncControl |= spv::FunctionControlDontInlineMask;
3050 }
3051 // TODO: Check llvm attribute for Function Control Pure.
3052 if (F.hasFnAttribute(Attribute::ReadOnly)) {
3053 FuncControl |= spv::FunctionControlPureMask;
3054 }
3055 // TODO: Check llvm attribute for Function Control Const.
3056 if (F.hasFnAttribute(Attribute::ReadNone)) {
3057 FuncControl |= spv::FunctionControlConstMask;
3058 }
3059
David Neto257c3892018-04-11 13:19:45 -04003060 FOps << MkNum(FuncControl);
David Neto22f144c2017-06-12 14:26:21 -04003061
3062 uint32_t FTyID;
3063 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3064 SmallVector<Type *, 4> NewFuncParamTys;
3065 FunctionType *NewFTy =
3066 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
3067 FTyID = lookupType(NewFTy);
3068 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07003069 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04003070 if (GlobalConstFuncTyMap.count(FTy)) {
3071 FTyID = lookupType(GlobalConstFuncTyMap[FTy].first);
3072 } else {
3073 FTyID = lookupType(FTy);
3074 }
3075 }
3076
David Neto257c3892018-04-11 13:19:45 -04003077 FOps << MkId(FTyID);
David Neto22f144c2017-06-12 14:26:21 -04003078
3079 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3080 EntryPoints.push_back(std::make_pair(&F, nextID));
3081 }
3082
3083 VMap[&F] = nextID;
3084
David Neto482550a2018-03-24 05:21:07 -07003085 if (clspv::Option::ShowIDs()) {
David Netob05675d2018-02-16 12:37:49 -05003086 errs() << "Function " << F.getName() << " is " << nextID << "\n";
3087 }
David Neto22f144c2017-06-12 14:26:21 -04003088 // Generate SPIRV instruction for function.
David Neto87846742018-04-11 17:36:22 -04003089 auto *FuncInst = new SPIRVInstruction(spv::OpFunction, nextID++, FOps);
David Neto22f144c2017-06-12 14:26:21 -04003090 SPIRVInstList.push_back(FuncInst);
3091
3092 //
3093 // Generate OpFunctionParameter for Normal function.
3094 //
3095
3096 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
alan-bakere9308012019-03-15 10:25:13 -04003097
3098 // Find Insert Point for OpDecorate.
3099 auto DecoInsertPoint =
3100 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
3101 [](SPIRVInstruction *Inst) -> bool {
3102 return Inst->getOpcode() != spv::OpDecorate &&
3103 Inst->getOpcode() != spv::OpMemberDecorate &&
3104 Inst->getOpcode() != spv::OpExtInstImport;
3105 });
3106
David Neto22f144c2017-06-12 14:26:21 -04003107 // Iterate Argument for name instead of param type from function type.
3108 unsigned ArgIdx = 0;
3109 for (Argument &Arg : F.args()) {
alan-bakere9308012019-03-15 10:25:13 -04003110 uint32_t param_id = nextID++;
3111 VMap[&Arg] = param_id;
3112
3113 if (CalledWithCoherentResource(Arg)) {
3114 // If the arg is passed a coherent resource ever, then decorate this
3115 // parameter with Coherent too.
3116 SPIRVOperandList decoration_ops;
3117 decoration_ops << MkId(param_id) << MkNum(spv::DecorationCoherent);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003118 SPIRVInstList.insert(
3119 DecoInsertPoint,
3120 new SPIRVInstruction(spv::OpDecorate, decoration_ops));
alan-bakere9308012019-03-15 10:25:13 -04003121 }
David Neto22f144c2017-06-12 14:26:21 -04003122
3123 // ParamOps[0] : Result Type ID
3124 SPIRVOperandList ParamOps;
3125
3126 // Find SPIRV instruction for parameter type.
3127 uint32_t ParamTyID = lookupType(Arg.getType());
3128 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
3129 if (GlobalConstFuncTyMap.count(FTy)) {
3130 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
3131 Type *EleTy = PTy->getPointerElementType();
3132 Type *ArgTy =
3133 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
3134 ParamTyID = lookupType(ArgTy);
3135 GlobalConstArgSet.insert(&Arg);
3136 }
3137 }
3138 }
David Neto257c3892018-04-11 13:19:45 -04003139 ParamOps << MkId(ParamTyID);
David Neto22f144c2017-06-12 14:26:21 -04003140
3141 // Generate SPIRV instruction for parameter.
David Neto87846742018-04-11 17:36:22 -04003142 auto *ParamInst =
alan-bakere9308012019-03-15 10:25:13 -04003143 new SPIRVInstruction(spv::OpFunctionParameter, param_id, ParamOps);
David Neto22f144c2017-06-12 14:26:21 -04003144 SPIRVInstList.push_back(ParamInst);
3145
3146 ArgIdx++;
3147 }
3148 }
3149}
3150
alan-bakerb6b09dc2018-11-08 16:59:28 -05003151void SPIRVProducerPass::GenerateModuleInfo(Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04003152 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3153 EntryPointVecType &EntryPoints = getEntryPointVec();
3154 ValueMapType &VMap = getValueMap();
3155 ValueList &EntryPointInterfaces = getEntryPointInterfacesVec();
3156 uint32_t &ExtInstImportID = getOpExtInstImportID();
3157 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
3158
3159 // Set up insert point.
3160 auto InsertPoint = SPIRVInstList.begin();
3161
3162 //
3163 // Generate OpCapability
3164 //
3165 // TODO: Which llvm information is mapped to SPIRV Capapbility?
3166
3167 // Ops[0] = Capability
3168 SPIRVOperandList Ops;
3169
David Neto87846742018-04-11 17:36:22 -04003170 auto *CapInst =
3171 new SPIRVInstruction(spv::OpCapability, {MkNum(spv::CapabilityShader)});
David Neto22f144c2017-06-12 14:26:21 -04003172 SPIRVInstList.insert(InsertPoint, CapInst);
3173
3174 for (Type *Ty : getTypeList()) {
alan-bakerb39c8262019-03-08 14:03:37 -05003175 if (clspv::Option::Int8Support() && Ty->isIntegerTy(8)) {
3176 // Generate OpCapability for i8 type.
3177 SPIRVInstList.insert(InsertPoint,
3178 new SPIRVInstruction(spv::OpCapability,
3179 {MkNum(spv::CapabilityInt8)}));
3180 } else if (Ty->isIntegerTy(16)) {
David Neto22f144c2017-06-12 14:26:21 -04003181 // Generate OpCapability for i16 type.
David Neto87846742018-04-11 17:36:22 -04003182 SPIRVInstList.insert(InsertPoint,
3183 new SPIRVInstruction(spv::OpCapability,
3184 {MkNum(spv::CapabilityInt16)}));
David Neto22f144c2017-06-12 14:26:21 -04003185 } else if (Ty->isIntegerTy(64)) {
3186 // Generate OpCapability for i64 type.
David Neto87846742018-04-11 17:36:22 -04003187 SPIRVInstList.insert(InsertPoint,
3188 new SPIRVInstruction(spv::OpCapability,
3189 {MkNum(spv::CapabilityInt64)}));
David Neto22f144c2017-06-12 14:26:21 -04003190 } else if (Ty->isHalfTy()) {
3191 // Generate OpCapability for half type.
3192 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003193 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3194 {MkNum(spv::CapabilityFloat16)}));
David Neto22f144c2017-06-12 14:26:21 -04003195 } else if (Ty->isDoubleTy()) {
3196 // Generate OpCapability for double type.
3197 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003198 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3199 {MkNum(spv::CapabilityFloat64)}));
David Neto22f144c2017-06-12 14:26:21 -04003200 } else if (auto *STy = dyn_cast<StructType>(Ty)) {
3201 if (STy->isOpaque()) {
David Neto565571c2017-08-21 12:00:05 -04003202 if (STy->getName().equals("opencl.image2d_wo_t") ||
3203 STy->getName().equals("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04003204 // Generate OpCapability for write only image type.
3205 SPIRVInstList.insert(
3206 InsertPoint,
3207 new SPIRVInstruction(
David Neto87846742018-04-11 17:36:22 -04003208 spv::OpCapability,
3209 {MkNum(spv::CapabilityStorageImageWriteWithoutFormat)}));
David Neto22f144c2017-06-12 14:26:21 -04003210 }
3211 }
3212 }
3213 }
3214
David Neto5c22a252018-03-15 16:07:41 -04003215 { // OpCapability ImageQuery
3216 bool hasImageQuery = false;
3217 for (const char *imageQuery : {
3218 "_Z15get_image_width14ocl_image2d_ro",
3219 "_Z15get_image_width14ocl_image2d_wo",
3220 "_Z16get_image_height14ocl_image2d_ro",
3221 "_Z16get_image_height14ocl_image2d_wo",
3222 }) {
3223 if (module.getFunction(imageQuery)) {
3224 hasImageQuery = true;
3225 break;
3226 }
3227 }
3228 if (hasImageQuery) {
David Neto87846742018-04-11 17:36:22 -04003229 auto *ImageQueryCapInst = new SPIRVInstruction(
3230 spv::OpCapability, {MkNum(spv::CapabilityImageQuery)});
David Neto5c22a252018-03-15 16:07:41 -04003231 SPIRVInstList.insert(InsertPoint, ImageQueryCapInst);
3232 }
3233 }
3234
David Neto22f144c2017-06-12 14:26:21 -04003235 if (hasVariablePointers()) {
3236 //
David Neto22f144c2017-06-12 14:26:21 -04003237 // Generate OpCapability.
3238 //
3239 // Ops[0] = Capability
3240 //
3241 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003242 Ops << MkNum(spv::CapabilityVariablePointers);
David Neto22f144c2017-06-12 14:26:21 -04003243
David Neto87846742018-04-11 17:36:22 -04003244 SPIRVInstList.insert(InsertPoint,
3245 new SPIRVInstruction(spv::OpCapability, Ops));
alan-baker5b86ed72019-02-15 08:26:50 -05003246 } else if (hasVariablePointersStorageBuffer()) {
3247 //
3248 // Generate OpCapability.
3249 //
3250 // Ops[0] = Capability
3251 //
3252 Ops.clear();
3253 Ops << MkNum(spv::CapabilityVariablePointersStorageBuffer);
David Neto22f144c2017-06-12 14:26:21 -04003254
alan-baker5b86ed72019-02-15 08:26:50 -05003255 SPIRVInstList.insert(InsertPoint,
3256 new SPIRVInstruction(spv::OpCapability, Ops));
3257 }
3258
3259 // Always add the storage buffer extension
3260 {
David Neto22f144c2017-06-12 14:26:21 -04003261 //
3262 // Generate OpExtension.
3263 //
3264 // Ops[0] = Name (Literal String)
3265 //
alan-baker5b86ed72019-02-15 08:26:50 -05003266 auto *ExtensionInst = new SPIRVInstruction(
3267 spv::OpExtension, {MkString("SPV_KHR_storage_buffer_storage_class")});
3268 SPIRVInstList.insert(InsertPoint, ExtensionInst);
3269 }
David Neto22f144c2017-06-12 14:26:21 -04003270
alan-baker5b86ed72019-02-15 08:26:50 -05003271 if (hasVariablePointers() || hasVariablePointersStorageBuffer()) {
3272 //
3273 // Generate OpExtension.
3274 //
3275 // Ops[0] = Name (Literal String)
3276 //
3277 auto *ExtensionInst = new SPIRVInstruction(
3278 spv::OpExtension, {MkString("SPV_KHR_variable_pointers")});
3279 SPIRVInstList.insert(InsertPoint, ExtensionInst);
David Neto22f144c2017-06-12 14:26:21 -04003280 }
3281
3282 if (ExtInstImportID) {
3283 ++InsertPoint;
3284 }
3285
3286 //
3287 // Generate OpMemoryModel
3288 //
3289 // Memory model for Vulkan will always be GLSL450.
3290
3291 // Ops[0] = Addressing Model
3292 // Ops[1] = Memory Model
3293 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003294 Ops << MkNum(spv::AddressingModelLogical) << MkNum(spv::MemoryModelGLSL450);
David Neto22f144c2017-06-12 14:26:21 -04003295
David Neto87846742018-04-11 17:36:22 -04003296 auto *MemModelInst = new SPIRVInstruction(spv::OpMemoryModel, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003297 SPIRVInstList.insert(InsertPoint, MemModelInst);
3298
3299 //
3300 // Generate OpEntryPoint
3301 //
3302 for (auto EntryPoint : EntryPoints) {
3303 // Ops[0] = Execution Model
3304 // Ops[1] = EntryPoint ID
3305 // Ops[2] = Name (Literal String)
3306 // ...
3307 //
3308 // TODO: Do we need to consider Interface ID for forward references???
3309 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003310 const StringRef &name = EntryPoint.first->getName();
David Neto257c3892018-04-11 13:19:45 -04003311 Ops << MkNum(spv::ExecutionModelGLCompute) << MkId(EntryPoint.second)
3312 << MkString(name);
David Neto22f144c2017-06-12 14:26:21 -04003313
David Neto22f144c2017-06-12 14:26:21 -04003314 for (Value *Interface : EntryPointInterfaces) {
David Neto257c3892018-04-11 13:19:45 -04003315 Ops << MkId(VMap[Interface]);
David Neto22f144c2017-06-12 14:26:21 -04003316 }
3317
David Neto87846742018-04-11 17:36:22 -04003318 auto *EntryPointInst = new SPIRVInstruction(spv::OpEntryPoint, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003319 SPIRVInstList.insert(InsertPoint, EntryPointInst);
3320 }
3321
3322 for (auto EntryPoint : EntryPoints) {
3323 if (const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
3324 ->getMetadata("reqd_work_group_size")) {
3325
3326 if (!BuiltinDimVec.empty()) {
3327 llvm_unreachable(
3328 "Kernels should have consistent work group size definition");
3329 }
3330
3331 //
3332 // Generate OpExecutionMode
3333 //
3334
3335 // Ops[0] = Entry Point ID
3336 // Ops[1] = Execution Mode
3337 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
3338 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003339 Ops << MkId(EntryPoint.second) << MkNum(spv::ExecutionModeLocalSize);
David Neto22f144c2017-06-12 14:26:21 -04003340
3341 uint32_t XDim = static_cast<uint32_t>(
3342 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3343 uint32_t YDim = static_cast<uint32_t>(
3344 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3345 uint32_t ZDim = static_cast<uint32_t>(
3346 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3347
David Neto257c3892018-04-11 13:19:45 -04003348 Ops << MkNum(XDim) << MkNum(YDim) << MkNum(ZDim);
David Neto22f144c2017-06-12 14:26:21 -04003349
David Neto87846742018-04-11 17:36:22 -04003350 auto *ExecModeInst = new SPIRVInstruction(spv::OpExecutionMode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003351 SPIRVInstList.insert(InsertPoint, ExecModeInst);
3352 }
3353 }
3354
3355 //
3356 // Generate OpSource.
3357 //
3358 // Ops[0] = SourceLanguage ID
3359 // Ops[1] = Version (LiteralNum)
3360 //
3361 Ops.clear();
Kévin Petit0fc88042019-04-09 23:25:02 +01003362 if (clspv::Option::CPlusPlus()) {
3363 Ops << MkNum(spv::SourceLanguageOpenCL_CPP) << MkNum(100);
3364 } else {
3365 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(120);
3366 }
David Neto22f144c2017-06-12 14:26:21 -04003367
David Neto87846742018-04-11 17:36:22 -04003368 auto *OpenSourceInst = new SPIRVInstruction(spv::OpSource, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003369 SPIRVInstList.insert(InsertPoint, OpenSourceInst);
3370
3371 if (!BuiltinDimVec.empty()) {
3372 //
3373 // Generate OpDecorates for x/y/z dimension.
3374 //
3375 // Ops[0] = Target ID
3376 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04003377 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04003378
3379 // X Dimension
3380 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003381 Ops << MkId(BuiltinDimVec[0]) << MkNum(spv::DecorationSpecId) << MkNum(0);
David Neto87846742018-04-11 17:36:22 -04003382 SPIRVInstList.insert(InsertPoint,
3383 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003384
3385 // Y Dimension
3386 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003387 Ops << MkId(BuiltinDimVec[1]) << MkNum(spv::DecorationSpecId) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04003388 SPIRVInstList.insert(InsertPoint,
3389 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003390
3391 // Z Dimension
3392 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003393 Ops << MkId(BuiltinDimVec[2]) << MkNum(spv::DecorationSpecId) << MkNum(2);
David Neto87846742018-04-11 17:36:22 -04003394 SPIRVInstList.insert(InsertPoint,
3395 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003396 }
3397}
3398
David Netob6e2e062018-04-25 10:32:06 -04003399void SPIRVProducerPass::GenerateEntryPointInitialStores() {
3400 // Work around a driver bug. Initializers on Private variables might not
3401 // work. So the start of the kernel should store the initializer value to the
3402 // variables. Yes, *every* entry point pays this cost if *any* entry point
3403 // uses this builtin. At this point I judge this to be an acceptable tradeoff
3404 // of complexity vs. runtime, for a broken driver.
alan-bakerb6b09dc2018-11-08 16:59:28 -05003405 // TODO(dneto): Remove this at some point once fixed drivers are widely
3406 // available.
David Netob6e2e062018-04-25 10:32:06 -04003407 if (WorkgroupSizeVarID) {
3408 assert(WorkgroupSizeValueID);
3409
3410 SPIRVOperandList Ops;
3411 Ops << MkId(WorkgroupSizeVarID) << MkId(WorkgroupSizeValueID);
3412
3413 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
3414 getSPIRVInstList().push_back(Inst);
3415 }
3416}
3417
David Neto22f144c2017-06-12 14:26:21 -04003418void SPIRVProducerPass::GenerateFuncBody(Function &F) {
3419 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3420 ValueMapType &VMap = getValueMap();
3421
David Netob6e2e062018-04-25 10:32:06 -04003422 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04003423
3424 for (BasicBlock &BB : F) {
3425 // Register BasicBlock to ValueMap.
3426 VMap[&BB] = nextID;
3427
3428 //
3429 // Generate OpLabel for Basic Block.
3430 //
3431 SPIRVOperandList Ops;
David Neto87846742018-04-11 17:36:22 -04003432 auto *Inst = new SPIRVInstruction(spv::OpLabel, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003433 SPIRVInstList.push_back(Inst);
3434
David Neto6dcd4712017-06-23 11:06:47 -04003435 // OpVariable instructions must come first.
3436 for (Instruction &I : BB) {
alan-baker5b86ed72019-02-15 08:26:50 -05003437 if (auto *alloca = dyn_cast<AllocaInst>(&I)) {
3438 // Allocating a pointer requires variable pointers.
3439 if (alloca->getAllocatedType()->isPointerTy()) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003440 setVariablePointersCapabilities(
3441 alloca->getAllocatedType()->getPointerAddressSpace());
alan-baker5b86ed72019-02-15 08:26:50 -05003442 }
David Neto6dcd4712017-06-23 11:06:47 -04003443 GenerateInstruction(I);
3444 }
3445 }
3446
David Neto22f144c2017-06-12 14:26:21 -04003447 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04003448 if (clspv::Option::HackInitializers()) {
3449 GenerateEntryPointInitialStores();
3450 }
David Neto22f144c2017-06-12 14:26:21 -04003451 }
3452
3453 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003454 if (!isa<AllocaInst>(I)) {
3455 GenerateInstruction(I);
3456 }
David Neto22f144c2017-06-12 14:26:21 -04003457 }
3458 }
3459}
3460
3461spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3462 const std::map<CmpInst::Predicate, spv::Op> Map = {
3463 {CmpInst::ICMP_EQ, spv::OpIEqual},
3464 {CmpInst::ICMP_NE, spv::OpINotEqual},
3465 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3466 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3467 {CmpInst::ICMP_ULT, spv::OpULessThan},
3468 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3469 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3470 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3471 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3472 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3473 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3474 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3475 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3476 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3477 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3478 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3479 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3480 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3481 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3482 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3483 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3484 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3485
3486 assert(0 != Map.count(I->getPredicate()));
3487
3488 return Map.at(I->getPredicate());
3489}
3490
3491spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3492 const std::map<unsigned, spv::Op> Map{
3493 {Instruction::Trunc, spv::OpUConvert},
3494 {Instruction::ZExt, spv::OpUConvert},
3495 {Instruction::SExt, spv::OpSConvert},
3496 {Instruction::FPToUI, spv::OpConvertFToU},
3497 {Instruction::FPToSI, spv::OpConvertFToS},
3498 {Instruction::UIToFP, spv::OpConvertUToF},
3499 {Instruction::SIToFP, spv::OpConvertSToF},
3500 {Instruction::FPTrunc, spv::OpFConvert},
3501 {Instruction::FPExt, spv::OpFConvert},
3502 {Instruction::BitCast, spv::OpBitcast}};
3503
3504 assert(0 != Map.count(I.getOpcode()));
3505
3506 return Map.at(I.getOpcode());
3507}
3508
3509spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
Kévin Petit24272b62018-10-18 19:16:12 +00003510 if (I.getType()->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003511 switch (I.getOpcode()) {
3512 default:
3513 break;
3514 case Instruction::Or:
3515 return spv::OpLogicalOr;
3516 case Instruction::And:
3517 return spv::OpLogicalAnd;
3518 case Instruction::Xor:
3519 return spv::OpLogicalNotEqual;
3520 }
3521 }
3522
alan-bakerb6b09dc2018-11-08 16:59:28 -05003523 const std::map<unsigned, spv::Op> Map{
David Neto22f144c2017-06-12 14:26:21 -04003524 {Instruction::Add, spv::OpIAdd},
3525 {Instruction::FAdd, spv::OpFAdd},
3526 {Instruction::Sub, spv::OpISub},
3527 {Instruction::FSub, spv::OpFSub},
3528 {Instruction::Mul, spv::OpIMul},
3529 {Instruction::FMul, spv::OpFMul},
3530 {Instruction::UDiv, spv::OpUDiv},
3531 {Instruction::SDiv, spv::OpSDiv},
3532 {Instruction::FDiv, spv::OpFDiv},
3533 {Instruction::URem, spv::OpUMod},
3534 {Instruction::SRem, spv::OpSRem},
3535 {Instruction::FRem, spv::OpFRem},
3536 {Instruction::Or, spv::OpBitwiseOr},
3537 {Instruction::Xor, spv::OpBitwiseXor},
3538 {Instruction::And, spv::OpBitwiseAnd},
3539 {Instruction::Shl, spv::OpShiftLeftLogical},
3540 {Instruction::LShr, spv::OpShiftRightLogical},
3541 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3542
3543 assert(0 != Map.count(I.getOpcode()));
3544
3545 return Map.at(I.getOpcode());
3546}
3547
3548void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
3549 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3550 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04003551 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
3552 LLVMContext &Context = I.getParent()->getParent()->getParent()->getContext();
3553
3554 // Register Instruction to ValueMap.
3555 if (0 == VMap[&I]) {
3556 VMap[&I] = nextID;
3557 }
3558
3559 switch (I.getOpcode()) {
3560 default: {
3561 if (Instruction::isCast(I.getOpcode())) {
3562 //
3563 // Generate SPIRV instructions for cast operators.
3564 //
3565
David Netod2de94a2017-08-28 17:27:47 -04003566 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003567 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003568 auto toI8 = Ty == Type::getInt8Ty(Context);
3569 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003570 // Handle zext, sext and uitofp with i1 type specially.
3571 if ((I.getOpcode() == Instruction::ZExt ||
3572 I.getOpcode() == Instruction::SExt ||
3573 I.getOpcode() == Instruction::UIToFP) &&
alan-bakerb6b09dc2018-11-08 16:59:28 -05003574 OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003575 //
3576 // Generate OpSelect.
3577 //
3578
3579 // Ops[0] = Result Type ID
3580 // Ops[1] = Condition ID
3581 // Ops[2] = True Constant ID
3582 // Ops[3] = False Constant ID
3583 SPIRVOperandList Ops;
3584
David Neto257c3892018-04-11 13:19:45 -04003585 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003586
David Neto22f144c2017-06-12 14:26:21 -04003587 uint32_t CondID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003588 Ops << MkId(CondID);
David Neto22f144c2017-06-12 14:26:21 -04003589
3590 uint32_t TrueID = 0;
3591 if (I.getOpcode() == Instruction::ZExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00003592 TrueID = VMap[ConstantInt::get(I.getType(), 1)];
David Neto22f144c2017-06-12 14:26:21 -04003593 } else if (I.getOpcode() == Instruction::SExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00003594 TrueID = VMap[ConstantInt::getSigned(I.getType(), -1)];
David Neto22f144c2017-06-12 14:26:21 -04003595 } else {
3596 TrueID = VMap[ConstantFP::get(Context, APFloat(1.0f))];
3597 }
David Neto257c3892018-04-11 13:19:45 -04003598 Ops << MkId(TrueID);
David Neto22f144c2017-06-12 14:26:21 -04003599
3600 uint32_t FalseID = 0;
3601 if (I.getOpcode() == Instruction::ZExt) {
3602 FalseID = VMap[Constant::getNullValue(I.getType())];
3603 } else if (I.getOpcode() == Instruction::SExt) {
3604 FalseID = VMap[Constant::getNullValue(I.getType())];
3605 } else {
3606 FalseID = VMap[ConstantFP::get(Context, APFloat(0.0f))];
3607 }
David Neto257c3892018-04-11 13:19:45 -04003608 Ops << MkId(FalseID);
David Neto22f144c2017-06-12 14:26:21 -04003609
David Neto87846742018-04-11 17:36:22 -04003610 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003611 SPIRVInstList.push_back(Inst);
alan-bakerb39c8262019-03-08 14:03:37 -05003612 } else if (!clspv::Option::Int8Support() &&
3613 I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
David Netod2de94a2017-08-28 17:27:47 -04003614 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3615 // 8 bits.
3616 // Before:
3617 // %result = trunc i32 %a to i8
3618 // After
3619 // %result = OpBitwiseAnd %uint %a %uint_255
3620
3621 SPIRVOperandList Ops;
3622
David Neto257c3892018-04-11 13:19:45 -04003623 Ops << MkId(lookupType(OpTy)) << MkId(VMap[I.getOperand(0)]);
David Netod2de94a2017-08-28 17:27:47 -04003624
3625 Type *UintTy = Type::getInt32Ty(Context);
3626 uint32_t MaskID = VMap[ConstantInt::get(UintTy, 255)];
David Neto257c3892018-04-11 13:19:45 -04003627 Ops << MkId(MaskID);
David Netod2de94a2017-08-28 17:27:47 -04003628
David Neto87846742018-04-11 17:36:22 -04003629 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Netod2de94a2017-08-28 17:27:47 -04003630 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003631 } else {
3632 // Ops[0] = Result Type ID
3633 // Ops[1] = Source Value ID
3634 SPIRVOperandList Ops;
3635
David Neto257c3892018-04-11 13:19:45 -04003636 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003637
David Neto87846742018-04-11 17:36:22 -04003638 auto *Inst = new SPIRVInstruction(GetSPIRVCastOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003639 SPIRVInstList.push_back(Inst);
3640 }
3641 } else if (isa<BinaryOperator>(I)) {
3642 //
3643 // Generate SPIRV instructions for binary operators.
3644 //
3645
3646 // Handle xor with i1 type specially.
3647 if (I.getOpcode() == Instruction::Xor &&
3648 I.getType() == Type::getInt1Ty(Context) &&
Kévin Petit24272b62018-10-18 19:16:12 +00003649 ((isa<ConstantInt>(I.getOperand(0)) &&
3650 !cast<ConstantInt>(I.getOperand(0))->isZero()) ||
3651 (isa<ConstantInt>(I.getOperand(1)) &&
3652 !cast<ConstantInt>(I.getOperand(1))->isZero()))) {
David Neto22f144c2017-06-12 14:26:21 -04003653 //
3654 // Generate OpLogicalNot.
3655 //
3656 // Ops[0] = Result Type ID
3657 // Ops[1] = Operand
3658 SPIRVOperandList Ops;
3659
David Neto257c3892018-04-11 13:19:45 -04003660 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003661
3662 Value *CondV = I.getOperand(0);
3663 if (isa<Constant>(I.getOperand(0))) {
3664 CondV = I.getOperand(1);
3665 }
David Neto257c3892018-04-11 13:19:45 -04003666 Ops << MkId(VMap[CondV]);
David Neto22f144c2017-06-12 14:26:21 -04003667
David Neto87846742018-04-11 17:36:22 -04003668 auto *Inst = new SPIRVInstruction(spv::OpLogicalNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003669 SPIRVInstList.push_back(Inst);
3670 } else {
3671 // Ops[0] = Result Type ID
3672 // Ops[1] = Operand 0
3673 // Ops[2] = Operand 1
3674 SPIRVOperandList Ops;
3675
David Neto257c3892018-04-11 13:19:45 -04003676 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
3677 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003678
David Neto87846742018-04-11 17:36:22 -04003679 auto *Inst =
3680 new SPIRVInstruction(GetSPIRVBinaryOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003681 SPIRVInstList.push_back(Inst);
3682 }
3683 } else {
3684 I.print(errs());
3685 llvm_unreachable("Unsupported instruction???");
3686 }
3687 break;
3688 }
3689 case Instruction::GetElementPtr: {
3690 auto &GlobalConstArgSet = getGlobalConstArgSet();
3691
3692 //
3693 // Generate OpAccessChain.
3694 //
3695 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
3696
3697 //
3698 // Generate OpAccessChain.
3699 //
3700
3701 // Ops[0] = Result Type ID
3702 // Ops[1] = Base ID
3703 // Ops[2] ... Ops[n] = Indexes ID
3704 SPIRVOperandList Ops;
3705
alan-bakerb6b09dc2018-11-08 16:59:28 -05003706 PointerType *ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04003707 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
3708 GlobalConstArgSet.count(GEP->getPointerOperand())) {
3709 // Use pointer type with private address space for global constant.
3710 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04003711 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04003712 }
David Neto257c3892018-04-11 13:19:45 -04003713
3714 Ops << MkId(lookupType(ResultType));
David Neto22f144c2017-06-12 14:26:21 -04003715
David Neto862b7d82018-06-14 18:48:37 -04003716 // Generate the base pointer.
3717 Ops << MkId(VMap[GEP->getPointerOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04003718
David Neto862b7d82018-06-14 18:48:37 -04003719 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04003720
3721 //
3722 // Follows below rules for gep.
3723 //
David Neto862b7d82018-06-14 18:48:37 -04003724 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
3725 // first index.
David Neto22f144c2017-06-12 14:26:21 -04003726 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
3727 // first index.
3728 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
3729 // use gep's first index.
3730 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
3731 // gep's first index.
3732 //
3733 spv::Op Opcode = spv::OpAccessChain;
3734 unsigned offset = 0;
3735 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04003736 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04003737 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04003738 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04003739 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04003740 }
David Neto862b7d82018-06-14 18:48:37 -04003741 } else {
David Neto22f144c2017-06-12 14:26:21 -04003742 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04003743 }
3744
3745 if (Opcode == spv::OpPtrAccessChain) {
David Neto1a1a0582017-07-07 12:01:44 -04003746 // Do we need to generate ArrayStride? Check against the GEP result type
3747 // rather than the pointer type of the base because when indexing into
3748 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
3749 // for something else in the SPIR-V.
3750 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
alan-baker5b86ed72019-02-15 08:26:50 -05003751 auto address_space = ResultType->getAddressSpace();
3752 setVariablePointersCapabilities(address_space);
3753 switch (GetStorageClass(address_space)) {
Alan Bakerfcda9482018-10-02 17:09:59 -04003754 case spv::StorageClassStorageBuffer:
3755 case spv::StorageClassUniform:
David Neto1a1a0582017-07-07 12:01:44 -04003756 // Save the need to generate an ArrayStride decoration. But defer
3757 // generation until later, so we only make one decoration.
David Neto85082642018-03-24 06:55:20 -07003758 getTypesNeedingArrayStride().insert(ResultType);
Alan Bakerfcda9482018-10-02 17:09:59 -04003759 break;
3760 default:
3761 break;
David Neto1a1a0582017-07-07 12:01:44 -04003762 }
David Neto22f144c2017-06-12 14:26:21 -04003763 }
3764
3765 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
David Neto257c3892018-04-11 13:19:45 -04003766 Ops << MkId(VMap[*II]);
David Neto22f144c2017-06-12 14:26:21 -04003767 }
3768
David Neto87846742018-04-11 17:36:22 -04003769 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003770 SPIRVInstList.push_back(Inst);
3771 break;
3772 }
3773 case Instruction::ExtractValue: {
3774 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3775 // Ops[0] = Result Type ID
3776 // Ops[1] = Composite ID
3777 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3778 SPIRVOperandList Ops;
3779
David Neto257c3892018-04-11 13:19:45 -04003780 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003781
3782 uint32_t CompositeID = VMap[EVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003783 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003784
3785 for (auto &Index : EVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003786 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003787 }
3788
David Neto87846742018-04-11 17:36:22 -04003789 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003790 SPIRVInstList.push_back(Inst);
3791 break;
3792 }
3793 case Instruction::InsertValue: {
3794 InsertValueInst *IVI = cast<InsertValueInst>(&I);
3795 // Ops[0] = Result Type ID
3796 // Ops[1] = Object ID
3797 // Ops[2] = Composite ID
3798 // Ops[3] ... Ops[n] = Indexes (Literal Number)
3799 SPIRVOperandList Ops;
3800
3801 uint32_t ResTyID = lookupType(I.getType());
David Neto257c3892018-04-11 13:19:45 -04003802 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04003803
3804 uint32_t ObjectID = VMap[IVI->getInsertedValueOperand()];
David Neto257c3892018-04-11 13:19:45 -04003805 Ops << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04003806
3807 uint32_t CompositeID = VMap[IVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003808 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003809
3810 for (auto &Index : IVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003811 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003812 }
3813
David Neto87846742018-04-11 17:36:22 -04003814 auto *Inst = new SPIRVInstruction(spv::OpCompositeInsert, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003815 SPIRVInstList.push_back(Inst);
3816 break;
3817 }
3818 case Instruction::Select: {
3819 //
3820 // Generate OpSelect.
3821 //
3822
3823 // Ops[0] = Result Type ID
3824 // Ops[1] = Condition ID
3825 // Ops[2] = True Constant ID
3826 // Ops[3] = False Constant ID
3827 SPIRVOperandList Ops;
3828
3829 // Find SPIRV instruction for parameter type.
3830 auto Ty = I.getType();
3831 if (Ty->isPointerTy()) {
3832 auto PointeeTy = Ty->getPointerElementType();
3833 if (PointeeTy->isStructTy() &&
3834 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
3835 Ty = PointeeTy;
alan-baker5b86ed72019-02-15 08:26:50 -05003836 } else {
3837 // Selecting between pointers requires variable pointers.
3838 setVariablePointersCapabilities(Ty->getPointerAddressSpace());
3839 if (!hasVariablePointers() && !selectFromSameObject(&I)) {
3840 setVariablePointers(true);
3841 }
David Neto22f144c2017-06-12 14:26:21 -04003842 }
3843 }
3844
David Neto257c3892018-04-11 13:19:45 -04003845 Ops << MkId(lookupType(Ty)) << MkId(VMap[I.getOperand(0)])
3846 << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003847
David Neto87846742018-04-11 17:36:22 -04003848 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003849 SPIRVInstList.push_back(Inst);
3850 break;
3851 }
3852 case Instruction::ExtractElement: {
3853 // Handle <4 x i8> type manually.
3854 Type *CompositeTy = I.getOperand(0)->getType();
3855 if (is4xi8vec(CompositeTy)) {
3856 //
3857 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
3858 // <4 x i8>.
3859 //
3860
3861 //
3862 // Generate OpShiftRightLogical
3863 //
3864 // Ops[0] = Result Type ID
3865 // Ops[1] = Operand 0
3866 // Ops[2] = Operand 1
3867 //
3868 SPIRVOperandList Ops;
3869
David Neto257c3892018-04-11 13:19:45 -04003870 Ops << MkId(lookupType(CompositeTy));
David Neto22f144c2017-06-12 14:26:21 -04003871
3872 uint32_t Op0ID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003873 Ops << MkId(Op0ID);
David Neto22f144c2017-06-12 14:26:21 -04003874
3875 uint32_t Op1ID = 0;
3876 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
3877 // Handle constant index.
3878 uint64_t Idx = CI->getZExtValue();
3879 Value *ShiftAmount =
3880 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3881 Op1ID = VMap[ShiftAmount];
3882 } else {
3883 // Handle variable index.
3884 SPIRVOperandList TmpOps;
3885
David Neto257c3892018-04-11 13:19:45 -04003886 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3887 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003888
3889 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003890 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003891
3892 Op1ID = nextID;
3893
David Neto87846742018-04-11 17:36:22 -04003894 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003895 SPIRVInstList.push_back(TmpInst);
3896 }
David Neto257c3892018-04-11 13:19:45 -04003897 Ops << MkId(Op1ID);
David Neto22f144c2017-06-12 14:26:21 -04003898
3899 uint32_t ShiftID = nextID;
3900
David Neto87846742018-04-11 17:36:22 -04003901 auto *Inst =
3902 new SPIRVInstruction(spv::OpShiftRightLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003903 SPIRVInstList.push_back(Inst);
3904
3905 //
3906 // Generate OpBitwiseAnd
3907 //
3908 // Ops[0] = Result Type ID
3909 // Ops[1] = Operand 0
3910 // Ops[2] = Operand 1
3911 //
3912 Ops.clear();
3913
David Neto257c3892018-04-11 13:19:45 -04003914 Ops << MkId(lookupType(CompositeTy)) << MkId(ShiftID);
David Neto22f144c2017-06-12 14:26:21 -04003915
3916 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
David Neto257c3892018-04-11 13:19:45 -04003917 Ops << MkId(VMap[CstFF]);
David Neto22f144c2017-06-12 14:26:21 -04003918
David Neto9b2d6252017-09-06 15:47:37 -04003919 // Reset mapping for this value to the result of the bitwise and.
3920 VMap[&I] = nextID;
3921
David Neto87846742018-04-11 17:36:22 -04003922 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003923 SPIRVInstList.push_back(Inst);
3924 break;
3925 }
3926
3927 // Ops[0] = Result Type ID
3928 // Ops[1] = Composite ID
3929 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3930 SPIRVOperandList Ops;
3931
David Neto257c3892018-04-11 13:19:45 -04003932 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003933
3934 spv::Op Opcode = spv::OpCompositeExtract;
3935 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
David Neto257c3892018-04-11 13:19:45 -04003936 Ops << MkNum(static_cast<uint32_t>(CI->getZExtValue()));
David Neto22f144c2017-06-12 14:26:21 -04003937 } else {
David Neto257c3892018-04-11 13:19:45 -04003938 Ops << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003939 Opcode = spv::OpVectorExtractDynamic;
3940 }
3941
David Neto87846742018-04-11 17:36:22 -04003942 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003943 SPIRVInstList.push_back(Inst);
3944 break;
3945 }
3946 case Instruction::InsertElement: {
3947 // Handle <4 x i8> type manually.
3948 Type *CompositeTy = I.getOperand(0)->getType();
3949 if (is4xi8vec(CompositeTy)) {
3950 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
3951 uint32_t CstFFID = VMap[CstFF];
3952
3953 uint32_t ShiftAmountID = 0;
3954 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
3955 // Handle constant index.
3956 uint64_t Idx = CI->getZExtValue();
3957 Value *ShiftAmount =
3958 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3959 ShiftAmountID = VMap[ShiftAmount];
3960 } else {
3961 // Handle variable index.
3962 SPIRVOperandList TmpOps;
3963
David Neto257c3892018-04-11 13:19:45 -04003964 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3965 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003966
3967 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003968 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003969
3970 ShiftAmountID = nextID;
3971
David Neto87846742018-04-11 17:36:22 -04003972 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003973 SPIRVInstList.push_back(TmpInst);
3974 }
3975
3976 //
3977 // Generate mask operations.
3978 //
3979
3980 // ShiftLeft mask according to index of insertelement.
3981 SPIRVOperandList Ops;
3982
David Neto257c3892018-04-11 13:19:45 -04003983 const uint32_t ResTyID = lookupType(CompositeTy);
3984 Ops << MkId(ResTyID) << MkId(CstFFID) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04003985
3986 uint32_t MaskID = nextID;
3987
David Neto87846742018-04-11 17:36:22 -04003988 auto *Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003989 SPIRVInstList.push_back(Inst);
3990
3991 // Inverse mask.
3992 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003993 Ops << MkId(ResTyID) << MkId(MaskID);
David Neto22f144c2017-06-12 14:26:21 -04003994
3995 uint32_t InvMaskID = nextID;
3996
David Neto87846742018-04-11 17:36:22 -04003997 Inst = new SPIRVInstruction(spv::OpNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003998 SPIRVInstList.push_back(Inst);
3999
4000 // Apply mask.
4001 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004002 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(0)]) << MkId(InvMaskID);
David Neto22f144c2017-06-12 14:26:21 -04004003
4004 uint32_t OrgValID = nextID;
4005
David Neto87846742018-04-11 17:36:22 -04004006 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004007 SPIRVInstList.push_back(Inst);
4008
4009 // Create correct value according to index of insertelement.
4010 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05004011 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(1)])
4012 << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004013
4014 uint32_t InsertValID = nextID;
4015
David Neto87846742018-04-11 17:36:22 -04004016 Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004017 SPIRVInstList.push_back(Inst);
4018
4019 // Insert value to original value.
4020 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004021 Ops << MkId(ResTyID) << MkId(OrgValID) << MkId(InsertValID);
David Neto22f144c2017-06-12 14:26:21 -04004022
David Netoa394f392017-08-26 20:45:29 -04004023 VMap[&I] = nextID;
4024
David Neto87846742018-04-11 17:36:22 -04004025 Inst = new SPIRVInstruction(spv::OpBitwiseOr, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004026 SPIRVInstList.push_back(Inst);
4027
4028 break;
4029 }
4030
David Neto22f144c2017-06-12 14:26:21 -04004031 SPIRVOperandList Ops;
4032
James Priced26efea2018-06-09 23:28:32 +01004033 // Ops[0] = Result Type ID
4034 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004035
4036 spv::Op Opcode = spv::OpCompositeInsert;
4037 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04004038 const auto value = CI->getZExtValue();
4039 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01004040 // Ops[1] = Object ID
4041 // Ops[2] = Composite ID
4042 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004043 Ops << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(0)])
James Priced26efea2018-06-09 23:28:32 +01004044 << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004045 } else {
James Priced26efea2018-06-09 23:28:32 +01004046 // Ops[1] = Composite ID
4047 // Ops[2] = Object ID
4048 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004049 Ops << MkId(VMap[I.getOperand(0)]) << MkId(VMap[I.getOperand(1)])
James Priced26efea2018-06-09 23:28:32 +01004050 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004051 Opcode = spv::OpVectorInsertDynamic;
4052 }
4053
David Neto87846742018-04-11 17:36:22 -04004054 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004055 SPIRVInstList.push_back(Inst);
4056 break;
4057 }
4058 case Instruction::ShuffleVector: {
4059 // Ops[0] = Result Type ID
4060 // Ops[1] = Vector 1 ID
4061 // Ops[2] = Vector 2 ID
4062 // Ops[3] ... Ops[n] = Components (Literal Number)
4063 SPIRVOperandList Ops;
4064
David Neto257c3892018-04-11 13:19:45 -04004065 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4066 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004067
4068 uint64_t NumElements = 0;
4069 if (Constant *Cst = dyn_cast<Constant>(I.getOperand(2))) {
4070 NumElements = cast<VectorType>(Cst->getType())->getNumElements();
4071
4072 if (Cst->isNullValue()) {
4073 for (unsigned i = 0; i < NumElements; i++) {
David Neto257c3892018-04-11 13:19:45 -04004074 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04004075 }
4076 } else if (const ConstantDataSequential *CDS =
4077 dyn_cast<ConstantDataSequential>(Cst)) {
4078 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
4079 std::vector<uint32_t> LiteralNum;
David Neto257c3892018-04-11 13:19:45 -04004080 const auto value = CDS->getElementAsInteger(i);
4081 assert(value <= UINT32_MAX);
4082 Ops << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004083 }
4084 } else if (const ConstantVector *CV = dyn_cast<ConstantVector>(Cst)) {
4085 for (unsigned i = 0; i < CV->getNumOperands(); i++) {
4086 auto Op = CV->getOperand(i);
4087
4088 uint32_t literal = 0;
4089
4090 if (auto CI = dyn_cast<ConstantInt>(Op)) {
4091 literal = static_cast<uint32_t>(CI->getZExtValue());
4092 } else if (auto UI = dyn_cast<UndefValue>(Op)) {
4093 literal = 0xFFFFFFFFu;
4094 } else {
4095 Op->print(errs());
4096 llvm_unreachable("Unsupported element in ConstantVector!");
4097 }
4098
David Neto257c3892018-04-11 13:19:45 -04004099 Ops << MkNum(literal);
David Neto22f144c2017-06-12 14:26:21 -04004100 }
4101 } else {
4102 Cst->print(errs());
4103 llvm_unreachable("Unsupported constant mask in ShuffleVector!");
4104 }
4105 }
4106
David Neto87846742018-04-11 17:36:22 -04004107 auto *Inst = new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004108 SPIRVInstList.push_back(Inst);
4109 break;
4110 }
4111 case Instruction::ICmp:
4112 case Instruction::FCmp: {
4113 CmpInst *CmpI = cast<CmpInst>(&I);
4114
David Netod4ca2e62017-07-06 18:47:35 -04004115 // Pointer equality is invalid.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004116 Type *ArgTy = CmpI->getOperand(0)->getType();
David Netod4ca2e62017-07-06 18:47:35 -04004117 if (isa<PointerType>(ArgTy)) {
4118 CmpI->print(errs());
4119 std::string name = I.getParent()->getParent()->getName();
4120 errs()
4121 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4122 << "in function " << name << "\n";
4123 llvm_unreachable("Pointer equality check is invalid");
4124 break;
4125 }
4126
David Neto257c3892018-04-11 13:19:45 -04004127 // Ops[0] = Result Type ID
4128 // Ops[1] = Operand 1 ID
4129 // Ops[2] = Operand 2 ID
4130 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004131
David Neto257c3892018-04-11 13:19:45 -04004132 Ops << MkId(lookupType(CmpI->getType())) << MkId(VMap[CmpI->getOperand(0)])
4133 << MkId(VMap[CmpI->getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004134
4135 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
David Neto87846742018-04-11 17:36:22 -04004136 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004137 SPIRVInstList.push_back(Inst);
4138 break;
4139 }
4140 case Instruction::Br: {
4141 // Branch instrucion is deferred because it needs label's ID. Record slot's
4142 // location on SPIRVInstructionList.
4143 DeferredInsts.push_back(
4144 std::make_tuple(&I, --SPIRVInstList.end(), 0 /* No id */));
4145 break;
4146 }
4147 case Instruction::Switch: {
4148 I.print(errs());
4149 llvm_unreachable("Unsupported instruction???");
4150 break;
4151 }
4152 case Instruction::IndirectBr: {
4153 I.print(errs());
4154 llvm_unreachable("Unsupported instruction???");
4155 break;
4156 }
4157 case Instruction::PHI: {
4158 // Branch instrucion is deferred because it needs label's ID. Record slot's
4159 // location on SPIRVInstructionList.
4160 DeferredInsts.push_back(
4161 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4162 break;
4163 }
4164 case Instruction::Alloca: {
4165 //
4166 // Generate OpVariable.
4167 //
4168 // Ops[0] : Result Type ID
4169 // Ops[1] : Storage Class
4170 SPIRVOperandList Ops;
4171
David Neto257c3892018-04-11 13:19:45 -04004172 Ops << MkId(lookupType(I.getType())) << MkNum(spv::StorageClassFunction);
David Neto22f144c2017-06-12 14:26:21 -04004173
David Neto87846742018-04-11 17:36:22 -04004174 auto *Inst = new SPIRVInstruction(spv::OpVariable, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004175 SPIRVInstList.push_back(Inst);
4176 break;
4177 }
4178 case Instruction::Load: {
4179 LoadInst *LD = cast<LoadInst>(&I);
4180 //
4181 // Generate OpLoad.
4182 //
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04004183
alan-baker5b86ed72019-02-15 08:26:50 -05004184 if (LD->getType()->isPointerTy()) {
4185 // Loading a pointer requires variable pointers.
4186 setVariablePointersCapabilities(LD->getType()->getPointerAddressSpace());
4187 }
David Neto22f144c2017-06-12 14:26:21 -04004188
David Neto0a2f98d2017-09-15 19:38:40 -04004189 uint32_t ResTyID = lookupType(LD->getType());
David Netoa60b00b2017-09-15 16:34:09 -04004190 uint32_t PointerID = VMap[LD->getPointerOperand()];
4191
4192 // This is a hack to work around what looks like a driver bug.
4193 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004194 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4195 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004196 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004197 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004198 // Generate a bitwise-and of the original value with itself.
4199 // We should have been able to get away with just an OpCopyObject,
4200 // but we need something more complex to get past certain driver bugs.
4201 // This is ridiculous, but necessary.
4202 // TODO(dneto): Revisit this once drivers fix their bugs.
4203
4204 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004205 Ops << MkId(ResTyID) << MkId(WorkgroupSizeValueID)
4206 << MkId(WorkgroupSizeValueID);
David Neto0a2f98d2017-09-15 19:38:40 -04004207
David Neto87846742018-04-11 17:36:22 -04004208 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto0a2f98d2017-09-15 19:38:40 -04004209 SPIRVInstList.push_back(Inst);
David Netoa60b00b2017-09-15 16:34:09 -04004210 break;
4211 }
4212
4213 // This is the normal path. Generate a load.
4214
David Neto22f144c2017-06-12 14:26:21 -04004215 // Ops[0] = Result Type ID
4216 // Ops[1] = Pointer ID
4217 // Ops[2] ... Ops[n] = Optional Memory Access
4218 //
4219 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004220
David Neto22f144c2017-06-12 14:26:21 -04004221 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004222 Ops << MkId(ResTyID) << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04004223
David Neto87846742018-04-11 17:36:22 -04004224 auto *Inst = new SPIRVInstruction(spv::OpLoad, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004225 SPIRVInstList.push_back(Inst);
4226 break;
4227 }
4228 case Instruction::Store: {
4229 StoreInst *ST = cast<StoreInst>(&I);
4230 //
4231 // Generate OpStore.
4232 //
4233
alan-baker5b86ed72019-02-15 08:26:50 -05004234 if (ST->getValueOperand()->getType()->isPointerTy()) {
4235 // Storing a pointer requires variable pointers.
4236 setVariablePointersCapabilities(
4237 ST->getValueOperand()->getType()->getPointerAddressSpace());
4238 }
4239
David Neto22f144c2017-06-12 14:26:21 -04004240 // Ops[0] = Pointer ID
4241 // Ops[1] = Object ID
4242 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4243 //
4244 // TODO: Do we need to implement Optional Memory Access???
David Neto257c3892018-04-11 13:19:45 -04004245 SPIRVOperandList Ops;
4246 Ops << MkId(VMap[ST->getPointerOperand()])
4247 << MkId(VMap[ST->getValueOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004248
David Neto87846742018-04-11 17:36:22 -04004249 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004250 SPIRVInstList.push_back(Inst);
4251 break;
4252 }
4253 case Instruction::AtomicCmpXchg: {
4254 I.print(errs());
4255 llvm_unreachable("Unsupported instruction???");
4256 break;
4257 }
4258 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004259 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4260
4261 spv::Op opcode;
4262
4263 switch (AtomicRMW->getOperation()) {
4264 default:
4265 I.print(errs());
4266 llvm_unreachable("Unsupported instruction???");
4267 case llvm::AtomicRMWInst::Add:
4268 opcode = spv::OpAtomicIAdd;
4269 break;
4270 case llvm::AtomicRMWInst::Sub:
4271 opcode = spv::OpAtomicISub;
4272 break;
4273 case llvm::AtomicRMWInst::Xchg:
4274 opcode = spv::OpAtomicExchange;
4275 break;
4276 case llvm::AtomicRMWInst::Min:
4277 opcode = spv::OpAtomicSMin;
4278 break;
4279 case llvm::AtomicRMWInst::Max:
4280 opcode = spv::OpAtomicSMax;
4281 break;
4282 case llvm::AtomicRMWInst::UMin:
4283 opcode = spv::OpAtomicUMin;
4284 break;
4285 case llvm::AtomicRMWInst::UMax:
4286 opcode = spv::OpAtomicUMax;
4287 break;
4288 case llvm::AtomicRMWInst::And:
4289 opcode = spv::OpAtomicAnd;
4290 break;
4291 case llvm::AtomicRMWInst::Or:
4292 opcode = spv::OpAtomicOr;
4293 break;
4294 case llvm::AtomicRMWInst::Xor:
4295 opcode = spv::OpAtomicXor;
4296 break;
4297 }
4298
4299 //
4300 // Generate OpAtomic*.
4301 //
4302 SPIRVOperandList Ops;
4303
David Neto257c3892018-04-11 13:19:45 -04004304 Ops << MkId(lookupType(I.getType()))
4305 << MkId(VMap[AtomicRMW->getPointerOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004306
4307 auto IntTy = Type::getInt32Ty(I.getContext());
Neil Henning39672102017-09-29 14:33:13 +01004308 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
David Neto257c3892018-04-11 13:19:45 -04004309 Ops << MkId(VMap[ConstantScopeDevice]);
Neil Henning39672102017-09-29 14:33:13 +01004310
4311 const auto ConstantMemorySemantics = ConstantInt::get(
4312 IntTy, spv::MemorySemanticsUniformMemoryMask |
4313 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto257c3892018-04-11 13:19:45 -04004314 Ops << MkId(VMap[ConstantMemorySemantics]);
Neil Henning39672102017-09-29 14:33:13 +01004315
David Neto257c3892018-04-11 13:19:45 -04004316 Ops << MkId(VMap[AtomicRMW->getValOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004317
4318 VMap[&I] = nextID;
4319
David Neto87846742018-04-11 17:36:22 -04004320 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
Neil Henning39672102017-09-29 14:33:13 +01004321 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004322 break;
4323 }
4324 case Instruction::Fence: {
4325 I.print(errs());
4326 llvm_unreachable("Unsupported instruction???");
4327 break;
4328 }
4329 case Instruction::Call: {
4330 CallInst *Call = dyn_cast<CallInst>(&I);
4331 Function *Callee = Call->getCalledFunction();
4332
Alan Baker202c8c72018-08-13 13:47:44 -04004333 if (Callee->getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004334 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
4335 // Generate an OpLoad
4336 SPIRVOperandList Ops;
4337 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004338
David Neto862b7d82018-06-14 18:48:37 -04004339 Ops << MkId(lookupType(Call->getType()->getPointerElementType()))
4340 << MkId(ResourceVarDeferredLoadCalls[Call]);
4341
4342 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
4343 SPIRVInstList.push_back(Inst);
4344 VMap[Call] = load_id;
4345 break;
4346
4347 } else {
4348 // This maps to an OpVariable we've already generated.
4349 // No code is generated for the call.
4350 }
4351 break;
alan-bakerb6b09dc2018-11-08 16:59:28 -05004352 } else if (Callee->getName().startswith(
4353 clspv::WorkgroupAccessorFunction())) {
Alan Baker202c8c72018-08-13 13:47:44 -04004354 // Don't codegen an instruction here, but instead map this call directly
4355 // to the workgroup variable id.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004356 int spec_id = static_cast<int>(
4357 cast<ConstantInt>(Call->getOperand(0))->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04004358 const auto &info = LocalSpecIdInfoMap[spec_id];
4359 VMap[Call] = info.variable_id;
4360 break;
David Neto862b7d82018-06-14 18:48:37 -04004361 }
4362
4363 // Sampler initializers become a load of the corresponding sampler.
4364
Kévin Petitdf71de32019-04-09 14:09:50 +01004365 if (Callee->getName().equals(clspv::LiteralSamplerFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004366 // Map this to a load from the variable.
4367 const auto index_into_sampler_map =
4368 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4369
4370 // Generate an OpLoad
David Neto22f144c2017-06-12 14:26:21 -04004371 SPIRVOperandList Ops;
David Neto862b7d82018-06-14 18:48:37 -04004372 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004373
David Neto257c3892018-04-11 13:19:45 -04004374 Ops << MkId(lookupType(SamplerTy->getPointerElementType()))
alan-bakerb6b09dc2018-11-08 16:59:28 -05004375 << MkId(SamplerMapIndexToIDMap[static_cast<unsigned>(
4376 index_into_sampler_map)]);
David Neto22f144c2017-06-12 14:26:21 -04004377
David Neto862b7d82018-06-14 18:48:37 -04004378 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004379 SPIRVInstList.push_back(Inst);
David Neto862b7d82018-06-14 18:48:37 -04004380 VMap[Call] = load_id;
David Neto22f144c2017-06-12 14:26:21 -04004381 break;
4382 }
4383
Kévin Petit349c9502019-03-28 17:24:14 +00004384 // Handle SPIR-V intrinsics
Kévin Petit9b340262019-06-19 18:31:11 +01004385 spv::Op opcode = StringSwitch<spv::Op>(Callee->getName())
4386 .Case("spirv.atomic_xor", spv::OpAtomicXor)
4387 .Default(spv::OpNop);
David Neto22f144c2017-06-12 14:26:21 -04004388
Kévin Petit617a76d2019-04-04 13:54:16 +01004389 // If the switch above didn't have an entry maybe the intrinsic
4390 // is using the name mangling logic.
4391 bool usesMangler = false;
4392 if (opcode == spv::OpNop) {
4393 if (Callee->getName().startswith(clspv::SPIRVOpIntrinsicFunction())) {
4394 auto OpCst = cast<ConstantInt>(Call->getOperand(0));
4395 opcode = static_cast<spv::Op>(OpCst->getZExtValue());
4396 usesMangler = true;
4397 }
4398 }
4399
Kévin Petit349c9502019-03-28 17:24:14 +00004400 if (opcode != spv::OpNop) {
4401
David Neto22f144c2017-06-12 14:26:21 -04004402 SPIRVOperandList Ops;
4403
Kévin Petit349c9502019-03-28 17:24:14 +00004404 if (!I.getType()->isVoidTy()) {
4405 Ops << MkId(lookupType(I.getType()));
4406 }
David Neto22f144c2017-06-12 14:26:21 -04004407
Kévin Petit617a76d2019-04-04 13:54:16 +01004408 unsigned firstOperand = usesMangler ? 1 : 0;
4409 for (unsigned i = firstOperand; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004410 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004411 }
4412
Kévin Petit349c9502019-03-28 17:24:14 +00004413 if (!I.getType()->isVoidTy()) {
4414 VMap[&I] = nextID;
Kévin Petit8a560882019-03-21 15:24:34 +00004415 }
4416
Kévin Petit349c9502019-03-28 17:24:14 +00004417 SPIRVInstruction *Inst;
4418 if (!I.getType()->isVoidTy()) {
4419 Inst = new SPIRVInstruction(opcode, nextID++, Ops);
4420 } else {
4421 Inst = new SPIRVInstruction(opcode, Ops);
4422 }
Kévin Petit8a560882019-03-21 15:24:34 +00004423 SPIRVInstList.push_back(Inst);
4424 break;
4425 }
4426
David Neto22f144c2017-06-12 14:26:21 -04004427 // spirv.copy_memory.* intrinsics become OpMemoryMemory's.
4428 if (Callee->getName().startswith("spirv.copy_memory")) {
4429 //
4430 // Generate OpCopyMemory.
4431 //
4432
4433 // Ops[0] = Dst ID
4434 // Ops[1] = Src ID
4435 // Ops[2] = Memory Access
4436 // Ops[3] = Alignment
4437
4438 auto IsVolatile =
4439 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
4440
4441 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
4442 : spv::MemoryAccessMaskNone;
4443
4444 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
4445
4446 auto Alignment =
4447 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4448
David Neto257c3892018-04-11 13:19:45 -04004449 SPIRVOperandList Ops;
4450 Ops << MkId(VMap[Call->getArgOperand(0)])
4451 << MkId(VMap[Call->getArgOperand(1)]) << MkNum(MemoryAccess)
4452 << MkNum(static_cast<uint32_t>(Alignment));
David Neto22f144c2017-06-12 14:26:21 -04004453
David Neto87846742018-04-11 17:36:22 -04004454 auto *Inst = new SPIRVInstruction(spv::OpCopyMemory, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004455
4456 SPIRVInstList.push_back(Inst);
4457
4458 break;
4459 }
4460
David Neto22f144c2017-06-12 14:26:21 -04004461 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
4462 // Additionally, OpTypeSampledImage is generated.
4463 if (Callee->getName().equals(
4464 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
4465 Callee->getName().equals(
4466 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
4467 //
4468 // Generate OpSampledImage.
4469 //
4470 // Ops[0] = Result Type ID
4471 // Ops[1] = Image ID
4472 // Ops[2] = Sampler ID
4473 //
4474 SPIRVOperandList Ops;
4475
4476 Value *Image = Call->getArgOperand(0);
4477 Value *Sampler = Call->getArgOperand(1);
4478 Value *Coordinate = Call->getArgOperand(2);
4479
4480 TypeMapType &OpImageTypeMap = getImageTypeMap();
4481 Type *ImageTy = Image->getType()->getPointerElementType();
4482 uint32_t ImageTyID = OpImageTypeMap[ImageTy];
David Neto22f144c2017-06-12 14:26:21 -04004483 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004484 uint32_t SamplerID = VMap[Sampler];
David Neto257c3892018-04-11 13:19:45 -04004485
4486 Ops << MkId(ImageTyID) << MkId(ImageID) << MkId(SamplerID);
David Neto22f144c2017-06-12 14:26:21 -04004487
4488 uint32_t SampledImageID = nextID;
4489
David Neto87846742018-04-11 17:36:22 -04004490 auto *Inst = new SPIRVInstruction(spv::OpSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004491 SPIRVInstList.push_back(Inst);
4492
4493 //
4494 // Generate OpImageSampleExplicitLod.
4495 //
4496 // Ops[0] = Result Type ID
4497 // Ops[1] = Sampled Image ID
4498 // Ops[2] = Coordinate ID
4499 // Ops[3] = Image Operands Type ID
4500 // Ops[4] ... Ops[n] = Operands ID
4501 //
4502 Ops.clear();
4503
David Neto257c3892018-04-11 13:19:45 -04004504 Ops << MkId(lookupType(Call->getType())) << MkId(SampledImageID)
4505 << MkId(VMap[Coordinate]) << MkNum(spv::ImageOperandsLodMask);
David Neto22f144c2017-06-12 14:26:21 -04004506
4507 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
David Neto257c3892018-04-11 13:19:45 -04004508 Ops << MkId(VMap[CstFP0]);
David Neto22f144c2017-06-12 14:26:21 -04004509
4510 VMap[&I] = nextID;
4511
David Neto87846742018-04-11 17:36:22 -04004512 Inst = new SPIRVInstruction(spv::OpImageSampleExplicitLod, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004513 SPIRVInstList.push_back(Inst);
4514 break;
4515 }
4516
4517 // write_imagef is mapped to OpImageWrite.
4518 if (Callee->getName().equals(
4519 "_Z12write_imagef14ocl_image2d_woDv2_iDv4_f") ||
4520 Callee->getName().equals(
4521 "_Z12write_imagef14ocl_image3d_woDv4_iDv4_f")) {
4522 //
4523 // Generate OpImageWrite.
4524 //
4525 // Ops[0] = Image ID
4526 // Ops[1] = Coordinate ID
4527 // Ops[2] = Texel ID
4528 // Ops[3] = (Optional) Image Operands Type (Literal Number)
4529 // Ops[4] ... Ops[n] = (Optional) Operands ID
4530 //
4531 SPIRVOperandList Ops;
4532
4533 Value *Image = Call->getArgOperand(0);
4534 Value *Coordinate = Call->getArgOperand(1);
4535 Value *Texel = Call->getArgOperand(2);
4536
4537 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004538 uint32_t CoordinateID = VMap[Coordinate];
David Neto22f144c2017-06-12 14:26:21 -04004539 uint32_t TexelID = VMap[Texel];
David Neto257c3892018-04-11 13:19:45 -04004540 Ops << MkId(ImageID) << MkId(CoordinateID) << MkId(TexelID);
David Neto22f144c2017-06-12 14:26:21 -04004541
David Neto87846742018-04-11 17:36:22 -04004542 auto *Inst = new SPIRVInstruction(spv::OpImageWrite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004543 SPIRVInstList.push_back(Inst);
4544 break;
4545 }
4546
David Neto5c22a252018-03-15 16:07:41 -04004547 // get_image_width is mapped to OpImageQuerySize
4548 if (Callee->getName().equals("_Z15get_image_width14ocl_image2d_ro") ||
4549 Callee->getName().equals("_Z15get_image_width14ocl_image2d_wo") ||
4550 Callee->getName().equals("_Z16get_image_height14ocl_image2d_ro") ||
4551 Callee->getName().equals("_Z16get_image_height14ocl_image2d_wo")) {
4552 //
4553 // Generate OpImageQuerySize, then pull out the right component.
4554 // Assume 2D image for now.
4555 //
4556 // Ops[0] = Image ID
4557 //
4558 // %sizes = OpImageQuerySizes %uint2 %im
4559 // %result = OpCompositeExtract %uint %sizes 0-or-1
4560 SPIRVOperandList Ops;
4561
4562 // Implement:
4563 // %sizes = OpImageQuerySizes %uint2 %im
4564 uint32_t SizesTypeID =
4565 TypeMap[VectorType::get(Type::getInt32Ty(Context), 2)];
David Neto5c22a252018-03-15 16:07:41 -04004566 Value *Image = Call->getArgOperand(0);
4567 uint32_t ImageID = VMap[Image];
David Neto257c3892018-04-11 13:19:45 -04004568 Ops << MkId(SizesTypeID) << MkId(ImageID);
David Neto5c22a252018-03-15 16:07:41 -04004569
4570 uint32_t SizesID = nextID++;
David Neto87846742018-04-11 17:36:22 -04004571 auto *QueryInst =
4572 new SPIRVInstruction(spv::OpImageQuerySize, SizesID, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004573 SPIRVInstList.push_back(QueryInst);
4574
4575 // Reset value map entry since we generated an intermediate instruction.
4576 VMap[&I] = nextID;
4577
4578 // Implement:
4579 // %result = OpCompositeExtract %uint %sizes 0-or-1
4580 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004581 Ops << MkId(TypeMap[I.getType()]) << MkId(SizesID);
David Neto5c22a252018-03-15 16:07:41 -04004582
4583 uint32_t component = Callee->getName().contains("height") ? 1 : 0;
David Neto257c3892018-04-11 13:19:45 -04004584 Ops << MkNum(component);
David Neto5c22a252018-03-15 16:07:41 -04004585
David Neto87846742018-04-11 17:36:22 -04004586 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004587 SPIRVInstList.push_back(Inst);
4588 break;
4589 }
4590
David Neto22f144c2017-06-12 14:26:21 -04004591 // Call instrucion is deferred because it needs function's ID. Record
4592 // slot's location on SPIRVInstructionList.
4593 DeferredInsts.push_back(
4594 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4595
David Neto3fbb4072017-10-16 11:28:14 -04004596 // Check whether the implementation of this call uses an extended
4597 // instruction plus one more value-producing instruction. If so, then
4598 // reserve the id for the extra value-producing slot.
4599 glsl::ExtInst EInst = getIndirectExtInstEnum(Callee->getName());
4600 if (EInst != kGlslExtInstBad) {
4601 // Reserve a spot for the extra value.
David Neto4d02a532017-09-17 12:57:44 -04004602 // Increase nextID.
David Neto22f144c2017-06-12 14:26:21 -04004603 VMap[&I] = nextID;
4604 nextID++;
4605 }
4606 break;
4607 }
4608 case Instruction::Ret: {
4609 unsigned NumOps = I.getNumOperands();
4610 if (NumOps == 0) {
4611 //
4612 // Generate OpReturn.
4613 //
David Neto87846742018-04-11 17:36:22 -04004614 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpReturn, {}));
David Neto22f144c2017-06-12 14:26:21 -04004615 } else {
4616 //
4617 // Generate OpReturnValue.
4618 //
4619
4620 // Ops[0] = Return Value ID
4621 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004622
4623 Ops << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004624
David Neto87846742018-04-11 17:36:22 -04004625 auto *Inst = new SPIRVInstruction(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004626 SPIRVInstList.push_back(Inst);
4627 break;
4628 }
4629 break;
4630 }
4631 }
4632}
4633
4634void SPIRVProducerPass::GenerateFuncEpilogue() {
4635 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4636
4637 //
4638 // Generate OpFunctionEnd
4639 //
4640
David Neto87846742018-04-11 17:36:22 -04004641 auto *Inst = new SPIRVInstruction(spv::OpFunctionEnd, {});
David Neto22f144c2017-06-12 14:26:21 -04004642 SPIRVInstList.push_back(Inst);
4643}
4644
4645bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
alan-bakerb39c8262019-03-08 14:03:37 -05004646 // Don't specialize <4 x i8> if i8 is generally supported.
4647 if (clspv::Option::Int8Support())
4648 return false;
4649
David Neto22f144c2017-06-12 14:26:21 -04004650 LLVMContext &Context = Ty->getContext();
4651 if (Ty->isVectorTy()) {
4652 if (Ty->getVectorElementType() == Type::getInt8Ty(Context) &&
4653 Ty->getVectorNumElements() == 4) {
4654 return true;
4655 }
4656 }
4657
4658 return false;
4659}
4660
4661void SPIRVProducerPass::HandleDeferredInstruction() {
4662 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4663 ValueMapType &VMap = getValueMap();
4664 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4665
4666 for (auto DeferredInst = DeferredInsts.rbegin();
4667 DeferredInst != DeferredInsts.rend(); ++DeferredInst) {
4668 Value *Inst = std::get<0>(*DeferredInst);
4669 SPIRVInstructionList::iterator InsertPoint = ++std::get<1>(*DeferredInst);
4670 if (InsertPoint != SPIRVInstList.end()) {
4671 while ((*InsertPoint)->getOpcode() == spv::OpPhi) {
4672 ++InsertPoint;
4673 }
4674 }
4675
4676 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
4677 // Check whether basic block, which has this branch instruction, is loop
4678 // header or not. If it is loop header, generate OpLoopMerge and
4679 // OpBranchConditional.
4680 Function *Func = Br->getParent()->getParent();
4681 DominatorTree &DT =
4682 getAnalysis<DominatorTreeWrapperPass>(*Func).getDomTree();
4683 const LoopInfo &LI =
4684 getAnalysis<LoopInfoWrapperPass>(*Func).getLoopInfo();
4685
4686 BasicBlock *BrBB = Br->getParent();
alan-baker49531082019-06-05 17:30:56 -04004687 Loop *L = LI.getLoopFor(BrBB);
David Neto22f144c2017-06-12 14:26:21 -04004688 if (LI.isLoopHeader(BrBB)) {
4689 Value *ContinueBB = nullptr;
4690 Value *MergeBB = nullptr;
4691
David Neto22f144c2017-06-12 14:26:21 -04004692 MergeBB = L->getExitBlock();
4693 if (!MergeBB) {
4694 // StructurizeCFG pass converts CFG into triangle shape and the cfg
4695 // has regions with single entry/exit. As a result, loop should not
4696 // have multiple exits.
4697 llvm_unreachable("Loop has multiple exits???");
4698 }
4699
4700 if (L->isLoopLatch(BrBB)) {
4701 ContinueBB = BrBB;
4702 } else {
4703 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
4704 // block.
4705 BasicBlock *Header = L->getHeader();
4706 BasicBlock *Latch = L->getLoopLatch();
4707 for (BasicBlock *BB : L->blocks()) {
4708 if (BB == Header) {
4709 continue;
4710 }
4711
4712 // Check whether block dominates block with back-edge.
4713 if (DT.dominates(BB, Latch)) {
4714 ContinueBB = BB;
4715 }
4716 }
4717
4718 if (!ContinueBB) {
4719 llvm_unreachable("Wrong continue block from loop");
4720 }
4721 }
4722
4723 //
4724 // Generate OpLoopMerge.
4725 //
4726 // Ops[0] = Merge Block ID
4727 // Ops[1] = Continue Target ID
4728 // Ops[2] = Selection Control
4729 SPIRVOperandList Ops;
4730
4731 // StructurizeCFG pass already manipulated CFG. Just use false block of
4732 // branch instruction as merge block.
4733 uint32_t MergeBBID = VMap[MergeBB];
David Neto22f144c2017-06-12 14:26:21 -04004734 uint32_t ContinueBBID = VMap[ContinueBB];
David Neto257c3892018-04-11 13:19:45 -04004735 Ops << MkId(MergeBBID) << MkId(ContinueBBID)
4736 << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004737
David Neto87846742018-04-11 17:36:22 -04004738 auto *MergeInst = new SPIRVInstruction(spv::OpLoopMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004739 SPIRVInstList.insert(InsertPoint, MergeInst);
4740
4741 } else if (Br->isConditional()) {
alan-baker49531082019-06-05 17:30:56 -04004742 // Generate a selection merge unless this is a back-edge block.
4743 bool HasBackedge = false;
4744 while (L && !HasBackedge) {
4745 if (L->isLoopLatch(BrBB)) {
4746 HasBackedge = true;
David Neto22f144c2017-06-12 14:26:21 -04004747 }
alan-baker49531082019-06-05 17:30:56 -04004748 L = L->getParentLoop();
David Neto22f144c2017-06-12 14:26:21 -04004749 }
alan-baker49531082019-06-05 17:30:56 -04004750 if (!HasBackedge) {
David Neto22f144c2017-06-12 14:26:21 -04004751 //
4752 // Generate OpSelectionMerge.
4753 //
4754 // Ops[0] = Merge Block ID
4755 // Ops[1] = Selection Control
4756 SPIRVOperandList Ops;
4757
4758 // StructurizeCFG pass already manipulated CFG. Just use false block
4759 // of branch instruction as merge block.
4760 uint32_t MergeBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004761 Ops << MkId(MergeBBID) << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004762
David Neto87846742018-04-11 17:36:22 -04004763 auto *MergeInst = new SPIRVInstruction(spv::OpSelectionMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004764 SPIRVInstList.insert(InsertPoint, MergeInst);
4765 }
4766 }
4767
4768 if (Br->isConditional()) {
4769 //
4770 // Generate OpBranchConditional.
4771 //
4772 // Ops[0] = Condition ID
4773 // Ops[1] = True Label ID
4774 // Ops[2] = False Label ID
4775 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
4776 SPIRVOperandList Ops;
4777
4778 uint32_t CondID = VMap[Br->getCondition()];
David Neto22f144c2017-06-12 14:26:21 -04004779 uint32_t TrueBBID = VMap[Br->getSuccessor(0)];
David Neto22f144c2017-06-12 14:26:21 -04004780 uint32_t FalseBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004781
4782 Ops << MkId(CondID) << MkId(TrueBBID) << MkId(FalseBBID);
David Neto22f144c2017-06-12 14:26:21 -04004783
David Neto87846742018-04-11 17:36:22 -04004784 auto *BrInst = new SPIRVInstruction(spv::OpBranchConditional, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004785 SPIRVInstList.insert(InsertPoint, BrInst);
4786 } else {
4787 //
4788 // Generate OpBranch.
4789 //
4790 // Ops[0] = Target Label ID
4791 SPIRVOperandList Ops;
4792
4793 uint32_t TargetID = VMap[Br->getSuccessor(0)];
David Neto257c3892018-04-11 13:19:45 -04004794 Ops << MkId(TargetID);
David Neto22f144c2017-06-12 14:26:21 -04004795
David Neto87846742018-04-11 17:36:22 -04004796 SPIRVInstList.insert(InsertPoint,
4797 new SPIRVInstruction(spv::OpBranch, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004798 }
4799 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
alan-baker5b86ed72019-02-15 08:26:50 -05004800 if (PHI->getType()->isPointerTy()) {
4801 // OpPhi on pointers requires variable pointers.
4802 setVariablePointersCapabilities(
4803 PHI->getType()->getPointerAddressSpace());
4804 if (!hasVariablePointers() && !selectFromSameObject(PHI)) {
4805 setVariablePointers(true);
4806 }
4807 }
4808
David Neto22f144c2017-06-12 14:26:21 -04004809 //
4810 // Generate OpPhi.
4811 //
4812 // Ops[0] = Result Type ID
4813 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
4814 SPIRVOperandList Ops;
4815
David Neto257c3892018-04-11 13:19:45 -04004816 Ops << MkId(lookupType(PHI->getType()));
David Neto22f144c2017-06-12 14:26:21 -04004817
David Neto22f144c2017-06-12 14:26:21 -04004818 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
4819 uint32_t VarID = VMap[PHI->getIncomingValue(i)];
David Neto22f144c2017-06-12 14:26:21 -04004820 uint32_t ParentID = VMap[PHI->getIncomingBlock(i)];
David Neto257c3892018-04-11 13:19:45 -04004821 Ops << MkId(VarID) << MkId(ParentID);
David Neto22f144c2017-06-12 14:26:21 -04004822 }
4823
4824 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04004825 InsertPoint,
4826 new SPIRVInstruction(spv::OpPhi, std::get<2>(*DeferredInst), Ops));
David Neto22f144c2017-06-12 14:26:21 -04004827 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
4828 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04004829 auto callee_name = Callee->getName();
4830 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04004831
4832 if (EInst) {
4833 uint32_t &ExtInstImportID = getOpExtInstImportID();
4834
4835 //
4836 // Generate OpExtInst.
4837 //
4838
4839 // Ops[0] = Result Type ID
4840 // Ops[1] = Set ID (OpExtInstImport ID)
4841 // Ops[2] = Instruction Number (Literal Number)
4842 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
4843 SPIRVOperandList Ops;
4844
David Neto862b7d82018-06-14 18:48:37 -04004845 Ops << MkId(lookupType(Call->getType())) << MkId(ExtInstImportID)
4846 << MkNum(EInst);
David Neto22f144c2017-06-12 14:26:21 -04004847
David Neto22f144c2017-06-12 14:26:21 -04004848 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
4849 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004850 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004851 }
4852
David Neto87846742018-04-11 17:36:22 -04004853 auto *ExtInst = new SPIRVInstruction(spv::OpExtInst,
4854 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04004855 SPIRVInstList.insert(InsertPoint, ExtInst);
4856
David Neto3fbb4072017-10-16 11:28:14 -04004857 const auto IndirectExtInst = getIndirectExtInstEnum(callee_name);
4858 if (IndirectExtInst != kGlslExtInstBad) {
4859 // Generate one more instruction that uses the result of the extended
4860 // instruction. Its result id is one more than the id of the
4861 // extended instruction.
David Neto22f144c2017-06-12 14:26:21 -04004862 LLVMContext &Context =
4863 Call->getParent()->getParent()->getParent()->getContext();
David Neto22f144c2017-06-12 14:26:21 -04004864
David Neto3fbb4072017-10-16 11:28:14 -04004865 auto generate_extra_inst = [this, &Context, &Call, &DeferredInst,
4866 &VMap, &SPIRVInstList, &InsertPoint](
4867 spv::Op opcode, Constant *constant) {
4868 //
4869 // Generate instruction like:
4870 // result = opcode constant <extinst-result>
4871 //
4872 // Ops[0] = Result Type ID
4873 // Ops[1] = Operand 0 ;; the constant, suitably splatted
4874 // Ops[2] = Operand 1 ;; the result of the extended instruction
4875 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004876
David Neto3fbb4072017-10-16 11:28:14 -04004877 Type *resultTy = Call->getType();
David Neto257c3892018-04-11 13:19:45 -04004878 Ops << MkId(lookupType(resultTy));
David Neto3fbb4072017-10-16 11:28:14 -04004879
4880 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
4881 constant = ConstantVector::getSplat(
4882 static_cast<unsigned>(vectorTy->getNumElements()), constant);
4883 }
David Neto257c3892018-04-11 13:19:45 -04004884 Ops << MkId(VMap[constant]) << MkId(std::get<2>(*DeferredInst));
David Neto3fbb4072017-10-16 11:28:14 -04004885
4886 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04004887 InsertPoint, new SPIRVInstruction(
4888 opcode, std::get<2>(*DeferredInst) + 1, Ops));
David Neto3fbb4072017-10-16 11:28:14 -04004889 };
4890
4891 switch (IndirectExtInst) {
4892 case glsl::ExtInstFindUMsb: // Implementing clz
4893 generate_extra_inst(
4894 spv::OpISub, ConstantInt::get(Type::getInt32Ty(Context), 31));
4895 break;
4896 case glsl::ExtInstAcos: // Implementing acospi
4897 case glsl::ExtInstAsin: // Implementing asinpi
Kévin Petiteb9f90a2018-09-29 12:29:34 +01004898 case glsl::ExtInstAtan: // Implementing atanpi
David Neto3fbb4072017-10-16 11:28:14 -04004899 case glsl::ExtInstAtan2: // Implementing atan2pi
4900 generate_extra_inst(
4901 spv::OpFMul,
4902 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
4903 break;
4904
4905 default:
4906 assert(false && "internally inconsistent");
David Neto4d02a532017-09-17 12:57:44 -04004907 }
David Neto22f144c2017-06-12 14:26:21 -04004908 }
David Neto3fbb4072017-10-16 11:28:14 -04004909
alan-bakerb39c8262019-03-08 14:03:37 -05004910 } else if (callee_name.startswith("_Z8popcount")) {
David Neto22f144c2017-06-12 14:26:21 -04004911 //
4912 // Generate OpBitCount
4913 //
4914 // Ops[0] = Result Type ID
4915 // Ops[1] = Base ID
David Neto257c3892018-04-11 13:19:45 -04004916 SPIRVOperandList Ops;
4917 Ops << MkId(lookupType(Call->getType()))
4918 << MkId(VMap[Call->getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004919
4920 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04004921 InsertPoint, new SPIRVInstruction(spv::OpBitCount,
David Neto22f144c2017-06-12 14:26:21 -04004922 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04004923
David Neto862b7d82018-06-14 18:48:37 -04004924 } else if (callee_name.startswith(kCompositeConstructFunctionPrefix)) {
David Netoab03f432017-11-03 17:00:44 -04004925
4926 // Generate an OpCompositeConstruct
4927 SPIRVOperandList Ops;
4928
4929 // The result type.
David Neto257c3892018-04-11 13:19:45 -04004930 Ops << MkId(lookupType(Call->getType()));
David Netoab03f432017-11-03 17:00:44 -04004931
4932 for (Use &use : Call->arg_operands()) {
David Neto257c3892018-04-11 13:19:45 -04004933 Ops << MkId(VMap[use.get()]);
David Netoab03f432017-11-03 17:00:44 -04004934 }
4935
4936 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04004937 InsertPoint, new SPIRVInstruction(spv::OpCompositeConstruct,
4938 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04004939
Alan Baker202c8c72018-08-13 13:47:44 -04004940 } else if (callee_name.startswith(clspv::ResourceAccessorFunction())) {
4941
4942 // We have already mapped the call's result value to an ID.
4943 // Don't generate any code now.
4944
4945 } else if (callee_name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004946
4947 // We have already mapped the call's result value to an ID.
4948 // Don't generate any code now.
4949
David Neto22f144c2017-06-12 14:26:21 -04004950 } else {
alan-baker5b86ed72019-02-15 08:26:50 -05004951 if (Call->getType()->isPointerTy()) {
4952 // Functions returning pointers require variable pointers.
4953 setVariablePointersCapabilities(
4954 Call->getType()->getPointerAddressSpace());
4955 }
4956
David Neto22f144c2017-06-12 14:26:21 -04004957 //
4958 // Generate OpFunctionCall.
4959 //
4960
4961 // Ops[0] = Result Type ID
4962 // Ops[1] = Callee Function ID
4963 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
4964 SPIRVOperandList Ops;
4965
David Neto862b7d82018-06-14 18:48:37 -04004966 Ops << MkId(lookupType(Call->getType()));
David Neto22f144c2017-06-12 14:26:21 -04004967
4968 uint32_t CalleeID = VMap[Callee];
David Neto43568eb2017-10-13 18:25:25 -04004969 if (CalleeID == 0) {
4970 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04004971 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04004972 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
4973 // causes an infinite loop. Instead, go ahead and generate
4974 // the bad function call. A validator will catch the 0-Id.
4975 // llvm_unreachable("Can't translate function call");
4976 }
David Neto22f144c2017-06-12 14:26:21 -04004977
David Neto257c3892018-04-11 13:19:45 -04004978 Ops << MkId(CalleeID);
David Neto22f144c2017-06-12 14:26:21 -04004979
David Neto22f144c2017-06-12 14:26:21 -04004980 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
4981 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
alan-baker5b86ed72019-02-15 08:26:50 -05004982 auto *operand = Call->getOperand(i);
4983 if (operand->getType()->isPointerTy()) {
4984 auto sc =
4985 GetStorageClass(operand->getType()->getPointerAddressSpace());
4986 if (sc == spv::StorageClassStorageBuffer) {
4987 // Passing SSBO by reference requires variable pointers storage
4988 // buffer.
4989 setVariablePointersStorageBuffer(true);
4990 } else if (sc == spv::StorageClassWorkgroup) {
4991 // Workgroup references require variable pointers if they are not
4992 // memory object declarations.
4993 if (auto *operand_call = dyn_cast<CallInst>(operand)) {
4994 // Workgroup accessor represents a variable reference.
4995 if (!operand_call->getCalledFunction()->getName().startswith(
4996 clspv::WorkgroupAccessorFunction()))
4997 setVariablePointers(true);
4998 } else {
4999 // Arguments are function parameters.
5000 if (!isa<Argument>(operand))
5001 setVariablePointers(true);
5002 }
5003 }
5004 }
5005 Ops << MkId(VMap[operand]);
David Neto22f144c2017-06-12 14:26:21 -04005006 }
5007
David Neto87846742018-04-11 17:36:22 -04005008 auto *CallInst = new SPIRVInstruction(spv::OpFunctionCall,
5009 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005010 SPIRVInstList.insert(InsertPoint, CallInst);
5011 }
5012 }
5013 }
5014}
5015
David Neto1a1a0582017-07-07 12:01:44 -04005016void SPIRVProducerPass::HandleDeferredDecorations(const DataLayout &DL) {
Alan Baker202c8c72018-08-13 13:47:44 -04005017 if (getTypesNeedingArrayStride().empty() && LocalArgSpecIds.empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04005018 return;
David Netoc6f3ab22018-04-06 18:02:31 -04005019 }
David Neto1a1a0582017-07-07 12:01:44 -04005020
5021 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto1a1a0582017-07-07 12:01:44 -04005022
5023 // Find an iterator pointing just past the last decoration.
5024 bool seen_decorations = false;
5025 auto DecoInsertPoint =
5026 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
5027 [&seen_decorations](SPIRVInstruction *Inst) -> bool {
5028 const bool is_decoration =
5029 Inst->getOpcode() == spv::OpDecorate ||
5030 Inst->getOpcode() == spv::OpMemberDecorate;
5031 if (is_decoration) {
5032 seen_decorations = true;
5033 return false;
5034 } else {
5035 return seen_decorations;
5036 }
5037 });
5038
David Netoc6f3ab22018-04-06 18:02:31 -04005039 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
5040 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07005041 for (auto *type : getTypesNeedingArrayStride()) {
5042 Type *elemTy = nullptr;
5043 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
5044 elemTy = ptrTy->getElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005045 } else if (auto *arrayTy = dyn_cast<ArrayType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005046 elemTy = arrayTy->getArrayElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005047 } else if (auto *seqTy = dyn_cast<SequentialType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005048 elemTy = seqTy->getSequentialElementType();
5049 } else {
5050 errs() << "Unhandled strided type " << *type << "\n";
5051 llvm_unreachable("Unhandled strided type");
5052 }
David Neto1a1a0582017-07-07 12:01:44 -04005053
5054 // Ops[0] = Target ID
5055 // Ops[1] = Decoration (ArrayStride)
5056 // Ops[2] = Stride number (Literal Number)
5057 SPIRVOperandList Ops;
5058
David Neto85082642018-03-24 06:55:20 -07005059 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Alan Bakerfcda9482018-10-02 17:09:59 -04005060 const uint32_t stride = static_cast<uint32_t>(GetTypeAllocSize(elemTy, DL));
David Neto257c3892018-04-11 13:19:45 -04005061
5062 Ops << MkId(lookupType(type)) << MkNum(spv::DecorationArrayStride)
5063 << MkNum(stride);
David Neto1a1a0582017-07-07 12:01:44 -04005064
David Neto87846742018-04-11 17:36:22 -04005065 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto1a1a0582017-07-07 12:01:44 -04005066 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
5067 }
David Netoc6f3ab22018-04-06 18:02:31 -04005068
5069 // Emit SpecId decorations targeting the array size value.
Alan Baker202c8c72018-08-13 13:47:44 -04005070 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
5071 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005072 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04005073 SPIRVOperandList Ops;
5074 Ops << MkId(arg_info.array_size_id) << MkNum(spv::DecorationSpecId)
5075 << MkNum(arg_info.spec_id);
5076 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04005077 new SPIRVInstruction(spv::OpDecorate, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04005078 }
David Neto1a1a0582017-07-07 12:01:44 -04005079}
5080
David Neto22f144c2017-06-12 14:26:21 -04005081glsl::ExtInst SPIRVProducerPass::getExtInstEnum(StringRef Name) {
5082 return StringSwitch<glsl::ExtInst>(Name)
alan-bakerb39c8262019-03-08 14:03:37 -05005083 .Case("_Z3absc", glsl::ExtInst::ExtInstSAbs)
5084 .Case("_Z3absDv2_c", glsl::ExtInst::ExtInstSAbs)
5085 .Case("_Z3absDv3_c", glsl::ExtInst::ExtInstSAbs)
5086 .Case("_Z3absDv4_c", glsl::ExtInst::ExtInstSAbs)
Kévin Petit2444e9b2018-11-09 14:14:37 +00005087 .Case("_Z3abss", glsl::ExtInst::ExtInstSAbs)
5088 .Case("_Z3absDv2_s", glsl::ExtInst::ExtInstSAbs)
5089 .Case("_Z3absDv3_s", glsl::ExtInst::ExtInstSAbs)
5090 .Case("_Z3absDv4_s", glsl::ExtInst::ExtInstSAbs)
David Neto22f144c2017-06-12 14:26:21 -04005091 .Case("_Z3absi", glsl::ExtInst::ExtInstSAbs)
5092 .Case("_Z3absDv2_i", glsl::ExtInst::ExtInstSAbs)
5093 .Case("_Z3absDv3_i", glsl::ExtInst::ExtInstSAbs)
5094 .Case("_Z3absDv4_i", glsl::ExtInst::ExtInstSAbs)
Kévin Petit2444e9b2018-11-09 14:14:37 +00005095 .Case("_Z3absl", glsl::ExtInst::ExtInstSAbs)
5096 .Case("_Z3absDv2_l", glsl::ExtInst::ExtInstSAbs)
5097 .Case("_Z3absDv3_l", glsl::ExtInst::ExtInstSAbs)
5098 .Case("_Z3absDv4_l", glsl::ExtInst::ExtInstSAbs)
alan-bakerb39c8262019-03-08 14:03:37 -05005099 .Case("_Z5clampccc", glsl::ExtInst::ExtInstSClamp)
5100 .Case("_Z5clampDv2_cS_S_", glsl::ExtInst::ExtInstSClamp)
5101 .Case("_Z5clampDv3_cS_S_", glsl::ExtInst::ExtInstSClamp)
5102 .Case("_Z5clampDv4_cS_S_", glsl::ExtInst::ExtInstSClamp)
5103 .Case("_Z5clamphhh", glsl::ExtInst::ExtInstUClamp)
5104 .Case("_Z5clampDv2_hS_S_", glsl::ExtInst::ExtInstUClamp)
5105 .Case("_Z5clampDv3_hS_S_", glsl::ExtInst::ExtInstUClamp)
5106 .Case("_Z5clampDv4_hS_S_", glsl::ExtInst::ExtInstUClamp)
Kévin Petit495255d2019-03-06 13:56:48 +00005107 .Case("_Z5clampsss", glsl::ExtInst::ExtInstSClamp)
5108 .Case("_Z5clampDv2_sS_S_", glsl::ExtInst::ExtInstSClamp)
5109 .Case("_Z5clampDv3_sS_S_", glsl::ExtInst::ExtInstSClamp)
5110 .Case("_Z5clampDv4_sS_S_", glsl::ExtInst::ExtInstSClamp)
5111 .Case("_Z5clampttt", glsl::ExtInst::ExtInstUClamp)
5112 .Case("_Z5clampDv2_tS_S_", glsl::ExtInst::ExtInstUClamp)
5113 .Case("_Z5clampDv3_tS_S_", glsl::ExtInst::ExtInstUClamp)
5114 .Case("_Z5clampDv4_tS_S_", glsl::ExtInst::ExtInstUClamp)
David Neto22f144c2017-06-12 14:26:21 -04005115 .Case("_Z5clampiii", glsl::ExtInst::ExtInstSClamp)
5116 .Case("_Z5clampDv2_iS_S_", glsl::ExtInst::ExtInstSClamp)
5117 .Case("_Z5clampDv3_iS_S_", glsl::ExtInst::ExtInstSClamp)
5118 .Case("_Z5clampDv4_iS_S_", glsl::ExtInst::ExtInstSClamp)
5119 .Case("_Z5clampjjj", glsl::ExtInst::ExtInstUClamp)
5120 .Case("_Z5clampDv2_jS_S_", glsl::ExtInst::ExtInstUClamp)
5121 .Case("_Z5clampDv3_jS_S_", glsl::ExtInst::ExtInstUClamp)
5122 .Case("_Z5clampDv4_jS_S_", glsl::ExtInst::ExtInstUClamp)
Kévin Petit495255d2019-03-06 13:56:48 +00005123 .Case("_Z5clamplll", glsl::ExtInst::ExtInstSClamp)
5124 .Case("_Z5clampDv2_lS_S_", glsl::ExtInst::ExtInstSClamp)
5125 .Case("_Z5clampDv3_lS_S_", glsl::ExtInst::ExtInstSClamp)
5126 .Case("_Z5clampDv4_lS_S_", glsl::ExtInst::ExtInstSClamp)
5127 .Case("_Z5clampmmm", glsl::ExtInst::ExtInstUClamp)
5128 .Case("_Z5clampDv2_mS_S_", glsl::ExtInst::ExtInstUClamp)
5129 .Case("_Z5clampDv3_mS_S_", glsl::ExtInst::ExtInstUClamp)
5130 .Case("_Z5clampDv4_mS_S_", glsl::ExtInst::ExtInstUClamp)
David Neto22f144c2017-06-12 14:26:21 -04005131 .Case("_Z5clampfff", glsl::ExtInst::ExtInstFClamp)
5132 .Case("_Z5clampDv2_fS_S_", glsl::ExtInst::ExtInstFClamp)
5133 .Case("_Z5clampDv3_fS_S_", glsl::ExtInst::ExtInstFClamp)
5134 .Case("_Z5clampDv4_fS_S_", glsl::ExtInst::ExtInstFClamp)
alan-bakerb39c8262019-03-08 14:03:37 -05005135 .Case("_Z3maxcc", glsl::ExtInst::ExtInstSMax)
5136 .Case("_Z3maxDv2_cS_", glsl::ExtInst::ExtInstSMax)
5137 .Case("_Z3maxDv3_cS_", glsl::ExtInst::ExtInstSMax)
5138 .Case("_Z3maxDv4_cS_", glsl::ExtInst::ExtInstSMax)
5139 .Case("_Z3maxhh", glsl::ExtInst::ExtInstUMax)
5140 .Case("_Z3maxDv2_hS_", glsl::ExtInst::ExtInstUMax)
5141 .Case("_Z3maxDv3_hS_", glsl::ExtInst::ExtInstUMax)
5142 .Case("_Z3maxDv4_hS_", glsl::ExtInst::ExtInstUMax)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005143 .Case("_Z3maxss", glsl::ExtInst::ExtInstSMax)
5144 .Case("_Z3maxDv2_sS_", glsl::ExtInst::ExtInstSMax)
5145 .Case("_Z3maxDv3_sS_", glsl::ExtInst::ExtInstSMax)
5146 .Case("_Z3maxDv4_sS_", glsl::ExtInst::ExtInstSMax)
5147 .Case("_Z3maxtt", glsl::ExtInst::ExtInstUMax)
5148 .Case("_Z3maxDv2_tS_", glsl::ExtInst::ExtInstUMax)
5149 .Case("_Z3maxDv3_tS_", glsl::ExtInst::ExtInstUMax)
5150 .Case("_Z3maxDv4_tS_", glsl::ExtInst::ExtInstUMax)
David Neto22f144c2017-06-12 14:26:21 -04005151 .Case("_Z3maxii", glsl::ExtInst::ExtInstSMax)
5152 .Case("_Z3maxDv2_iS_", glsl::ExtInst::ExtInstSMax)
5153 .Case("_Z3maxDv3_iS_", glsl::ExtInst::ExtInstSMax)
5154 .Case("_Z3maxDv4_iS_", glsl::ExtInst::ExtInstSMax)
5155 .Case("_Z3maxjj", glsl::ExtInst::ExtInstUMax)
5156 .Case("_Z3maxDv2_jS_", glsl::ExtInst::ExtInstUMax)
5157 .Case("_Z3maxDv3_jS_", glsl::ExtInst::ExtInstUMax)
5158 .Case("_Z3maxDv4_jS_", glsl::ExtInst::ExtInstUMax)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005159 .Case("_Z3maxll", glsl::ExtInst::ExtInstSMax)
5160 .Case("_Z3maxDv2_lS_", glsl::ExtInst::ExtInstSMax)
5161 .Case("_Z3maxDv3_lS_", glsl::ExtInst::ExtInstSMax)
5162 .Case("_Z3maxDv4_lS_", glsl::ExtInst::ExtInstSMax)
5163 .Case("_Z3maxmm", glsl::ExtInst::ExtInstUMax)
5164 .Case("_Z3maxDv2_mS_", glsl::ExtInst::ExtInstUMax)
5165 .Case("_Z3maxDv3_mS_", glsl::ExtInst::ExtInstUMax)
5166 .Case("_Z3maxDv4_mS_", glsl::ExtInst::ExtInstUMax)
David Neto22f144c2017-06-12 14:26:21 -04005167 .Case("_Z3maxff", glsl::ExtInst::ExtInstFMax)
5168 .Case("_Z3maxDv2_fS_", glsl::ExtInst::ExtInstFMax)
5169 .Case("_Z3maxDv3_fS_", glsl::ExtInst::ExtInstFMax)
5170 .Case("_Z3maxDv4_fS_", glsl::ExtInst::ExtInstFMax)
5171 .StartsWith("_Z4fmax", glsl::ExtInst::ExtInstFMax)
alan-bakerb39c8262019-03-08 14:03:37 -05005172 .Case("_Z3mincc", glsl::ExtInst::ExtInstSMin)
5173 .Case("_Z3minDv2_cS_", glsl::ExtInst::ExtInstSMin)
5174 .Case("_Z3minDv3_cS_", glsl::ExtInst::ExtInstSMin)
5175 .Case("_Z3minDv4_cS_", glsl::ExtInst::ExtInstSMin)
5176 .Case("_Z3minhh", glsl::ExtInst::ExtInstUMin)
5177 .Case("_Z3minDv2_hS_", glsl::ExtInst::ExtInstUMin)
5178 .Case("_Z3minDv3_hS_", glsl::ExtInst::ExtInstUMin)
5179 .Case("_Z3minDv4_hS_", glsl::ExtInst::ExtInstUMin)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005180 .Case("_Z3minss", glsl::ExtInst::ExtInstSMin)
5181 .Case("_Z3minDv2_sS_", glsl::ExtInst::ExtInstSMin)
5182 .Case("_Z3minDv3_sS_", glsl::ExtInst::ExtInstSMin)
5183 .Case("_Z3minDv4_sS_", glsl::ExtInst::ExtInstSMin)
5184 .Case("_Z3mintt", glsl::ExtInst::ExtInstUMin)
5185 .Case("_Z3minDv2_tS_", glsl::ExtInst::ExtInstUMin)
5186 .Case("_Z3minDv3_tS_", glsl::ExtInst::ExtInstUMin)
5187 .Case("_Z3minDv4_tS_", glsl::ExtInst::ExtInstUMin)
David Neto22f144c2017-06-12 14:26:21 -04005188 .Case("_Z3minii", glsl::ExtInst::ExtInstSMin)
5189 .Case("_Z3minDv2_iS_", glsl::ExtInst::ExtInstSMin)
5190 .Case("_Z3minDv3_iS_", glsl::ExtInst::ExtInstSMin)
5191 .Case("_Z3minDv4_iS_", glsl::ExtInst::ExtInstSMin)
5192 .Case("_Z3minjj", glsl::ExtInst::ExtInstUMin)
5193 .Case("_Z3minDv2_jS_", glsl::ExtInst::ExtInstUMin)
5194 .Case("_Z3minDv3_jS_", glsl::ExtInst::ExtInstUMin)
5195 .Case("_Z3minDv4_jS_", glsl::ExtInst::ExtInstUMin)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005196 .Case("_Z3minll", glsl::ExtInst::ExtInstSMin)
5197 .Case("_Z3minDv2_lS_", glsl::ExtInst::ExtInstSMin)
5198 .Case("_Z3minDv3_lS_", glsl::ExtInst::ExtInstSMin)
5199 .Case("_Z3minDv4_lS_", glsl::ExtInst::ExtInstSMin)
5200 .Case("_Z3minmm", glsl::ExtInst::ExtInstUMin)
5201 .Case("_Z3minDv2_mS_", glsl::ExtInst::ExtInstUMin)
5202 .Case("_Z3minDv3_mS_", glsl::ExtInst::ExtInstUMin)
5203 .Case("_Z3minDv4_mS_", glsl::ExtInst::ExtInstUMin)
David Neto22f144c2017-06-12 14:26:21 -04005204 .Case("_Z3minff", glsl::ExtInst::ExtInstFMin)
5205 .Case("_Z3minDv2_fS_", glsl::ExtInst::ExtInstFMin)
5206 .Case("_Z3minDv3_fS_", glsl::ExtInst::ExtInstFMin)
5207 .Case("_Z3minDv4_fS_", glsl::ExtInst::ExtInstFMin)
5208 .StartsWith("_Z4fmin", glsl::ExtInst::ExtInstFMin)
5209 .StartsWith("_Z7degrees", glsl::ExtInst::ExtInstDegrees)
5210 .StartsWith("_Z7radians", glsl::ExtInst::ExtInstRadians)
5211 .StartsWith("_Z3mix", glsl::ExtInst::ExtInstFMix)
5212 .StartsWith("_Z4acos", glsl::ExtInst::ExtInstAcos)
5213 .StartsWith("_Z5acosh", glsl::ExtInst::ExtInstAcosh)
5214 .StartsWith("_Z4asin", glsl::ExtInst::ExtInstAsin)
5215 .StartsWith("_Z5asinh", glsl::ExtInst::ExtInstAsinh)
5216 .StartsWith("_Z4atan", glsl::ExtInst::ExtInstAtan)
5217 .StartsWith("_Z5atan2", glsl::ExtInst::ExtInstAtan2)
5218 .StartsWith("_Z5atanh", glsl::ExtInst::ExtInstAtanh)
5219 .StartsWith("_Z4ceil", glsl::ExtInst::ExtInstCeil)
5220 .StartsWith("_Z3sin", glsl::ExtInst::ExtInstSin)
5221 .StartsWith("_Z4sinh", glsl::ExtInst::ExtInstSinh)
5222 .StartsWith("_Z8half_sin", glsl::ExtInst::ExtInstSin)
5223 .StartsWith("_Z10native_sin", glsl::ExtInst::ExtInstSin)
5224 .StartsWith("_Z3cos", glsl::ExtInst::ExtInstCos)
5225 .StartsWith("_Z4cosh", glsl::ExtInst::ExtInstCosh)
5226 .StartsWith("_Z8half_cos", glsl::ExtInst::ExtInstCos)
5227 .StartsWith("_Z10native_cos", glsl::ExtInst::ExtInstCos)
5228 .StartsWith("_Z3tan", glsl::ExtInst::ExtInstTan)
5229 .StartsWith("_Z4tanh", glsl::ExtInst::ExtInstTanh)
5230 .StartsWith("_Z8half_tan", glsl::ExtInst::ExtInstTan)
5231 .StartsWith("_Z10native_tan", glsl::ExtInst::ExtInstTan)
5232 .StartsWith("_Z3exp", glsl::ExtInst::ExtInstExp)
5233 .StartsWith("_Z8half_exp", glsl::ExtInst::ExtInstExp)
5234 .StartsWith("_Z10native_exp", glsl::ExtInst::ExtInstExp)
5235 .StartsWith("_Z4exp2", glsl::ExtInst::ExtInstExp2)
5236 .StartsWith("_Z9half_exp2", glsl::ExtInst::ExtInstExp2)
5237 .StartsWith("_Z11native_exp2", glsl::ExtInst::ExtInstExp2)
5238 .StartsWith("_Z3log", glsl::ExtInst::ExtInstLog)
5239 .StartsWith("_Z8half_log", glsl::ExtInst::ExtInstLog)
5240 .StartsWith("_Z10native_log", glsl::ExtInst::ExtInstLog)
5241 .StartsWith("_Z4log2", glsl::ExtInst::ExtInstLog2)
5242 .StartsWith("_Z9half_log2", glsl::ExtInst::ExtInstLog2)
5243 .StartsWith("_Z11native_log2", glsl::ExtInst::ExtInstLog2)
5244 .StartsWith("_Z4fabs", glsl::ExtInst::ExtInstFAbs)
kpet3458e942018-10-03 14:35:21 +01005245 .StartsWith("_Z3fma", glsl::ExtInst::ExtInstFma)
David Neto22f144c2017-06-12 14:26:21 -04005246 .StartsWith("_Z5floor", glsl::ExtInst::ExtInstFloor)
5247 .StartsWith("_Z5ldexp", glsl::ExtInst::ExtInstLdexp)
5248 .StartsWith("_Z3pow", glsl::ExtInst::ExtInstPow)
5249 .StartsWith("_Z4powr", glsl::ExtInst::ExtInstPow)
5250 .StartsWith("_Z9half_powr", glsl::ExtInst::ExtInstPow)
5251 .StartsWith("_Z11native_powr", glsl::ExtInst::ExtInstPow)
5252 .StartsWith("_Z5round", glsl::ExtInst::ExtInstRound)
5253 .StartsWith("_Z4sqrt", glsl::ExtInst::ExtInstSqrt)
5254 .StartsWith("_Z9half_sqrt", glsl::ExtInst::ExtInstSqrt)
5255 .StartsWith("_Z11native_sqrt", glsl::ExtInst::ExtInstSqrt)
5256 .StartsWith("_Z5rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5257 .StartsWith("_Z10half_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5258 .StartsWith("_Z12native_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5259 .StartsWith("_Z5trunc", glsl::ExtInst::ExtInstTrunc)
5260 .StartsWith("_Z5frexp", glsl::ExtInst::ExtInstFrexp)
5261 .StartsWith("_Z4sign", glsl::ExtInst::ExtInstFSign)
5262 .StartsWith("_Z6length", glsl::ExtInst::ExtInstLength)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005263 .StartsWith("_Z11fast_length", glsl::ExtInst::ExtInstLength)
David Neto22f144c2017-06-12 14:26:21 -04005264 .StartsWith("_Z8distance", glsl::ExtInst::ExtInstDistance)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005265 .StartsWith("_Z13fast_distance", glsl::ExtInst::ExtInstDistance)
David Netoe9a03512017-10-16 10:08:27 -04005266 .StartsWith("_Z4step", glsl::ExtInst::ExtInstStep)
kpet6fd2a262018-10-03 14:48:01 +01005267 .StartsWith("_Z10smoothstep", glsl::ExtInst::ExtInstSmoothStep)
David Neto22f144c2017-06-12 14:26:21 -04005268 .Case("_Z5crossDv3_fS_", glsl::ExtInst::ExtInstCross)
5269 .StartsWith("_Z9normalize", glsl::ExtInst::ExtInstNormalize)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005270 .StartsWith("_Z14fast_normalize", glsl::ExtInst::ExtInstNormalize)
David Neto22f144c2017-06-12 14:26:21 -04005271 .StartsWith("llvm.fmuladd.", glsl::ExtInst::ExtInstFma)
5272 .Case("spirv.unpack.v2f16", glsl::ExtInst::ExtInstUnpackHalf2x16)
5273 .Case("spirv.pack.v2f16", glsl::ExtInst::ExtInstPackHalf2x16)
David Neto62653202017-10-16 19:05:18 -04005274 .Case("clspv.fract.f", glsl::ExtInst::ExtInstFract)
5275 .Case("clspv.fract.v2f", glsl::ExtInst::ExtInstFract)
5276 .Case("clspv.fract.v3f", glsl::ExtInst::ExtInstFract)
5277 .Case("clspv.fract.v4f", glsl::ExtInst::ExtInstFract)
David Neto3fbb4072017-10-16 11:28:14 -04005278 .Default(kGlslExtInstBad);
5279}
5280
5281glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(StringRef Name) {
5282 // Check indirect cases.
5283 return StringSwitch<glsl::ExtInst>(Name)
5284 .StartsWith("_Z3clz", glsl::ExtInst::ExtInstFindUMsb)
5285 // Use exact match on float arg because these need a multiply
5286 // of a constant of the right floating point type.
5287 .Case("_Z6acospif", glsl::ExtInst::ExtInstAcos)
5288 .Case("_Z6acospiDv2_f", glsl::ExtInst::ExtInstAcos)
5289 .Case("_Z6acospiDv3_f", glsl::ExtInst::ExtInstAcos)
5290 .Case("_Z6acospiDv4_f", glsl::ExtInst::ExtInstAcos)
5291 .Case("_Z6asinpif", glsl::ExtInst::ExtInstAsin)
5292 .Case("_Z6asinpiDv2_f", glsl::ExtInst::ExtInstAsin)
5293 .Case("_Z6asinpiDv3_f", glsl::ExtInst::ExtInstAsin)
5294 .Case("_Z6asinpiDv4_f", glsl::ExtInst::ExtInstAsin)
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005295 .Case("_Z6atanpif", glsl::ExtInst::ExtInstAtan)
5296 .Case("_Z6atanpiDv2_f", glsl::ExtInst::ExtInstAtan)
5297 .Case("_Z6atanpiDv3_f", glsl::ExtInst::ExtInstAtan)
5298 .Case("_Z6atanpiDv4_f", glsl::ExtInst::ExtInstAtan)
David Neto3fbb4072017-10-16 11:28:14 -04005299 .Case("_Z7atan2piff", glsl::ExtInst::ExtInstAtan2)
5300 .Case("_Z7atan2piDv2_fS_", glsl::ExtInst::ExtInstAtan2)
5301 .Case("_Z7atan2piDv3_fS_", glsl::ExtInst::ExtInstAtan2)
5302 .Case("_Z7atan2piDv4_fS_", glsl::ExtInst::ExtInstAtan2)
5303 .Default(kGlslExtInstBad);
5304}
5305
alan-bakerb6b09dc2018-11-08 16:59:28 -05005306glsl::ExtInst
5307SPIRVProducerPass::getDirectOrIndirectExtInstEnum(StringRef Name) {
David Neto3fbb4072017-10-16 11:28:14 -04005308 auto direct = getExtInstEnum(Name);
5309 if (direct != kGlslExtInstBad)
5310 return direct;
5311 return getIndirectExtInstEnum(Name);
David Neto22f144c2017-06-12 14:26:21 -04005312}
5313
David Neto22f144c2017-06-12 14:26:21 -04005314void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04005315 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04005316}
5317
5318void SPIRVProducerPass::WriteResultID(SPIRVInstruction *Inst) {
5319 WriteOneWord(Inst->getResultID());
5320}
5321
5322void SPIRVProducerPass::WriteWordCountAndOpcode(SPIRVInstruction *Inst) {
5323 // High 16 bit : Word Count
5324 // Low 16 bit : Opcode
5325 uint32_t Word = Inst->getOpcode();
David Netoee2660d2018-06-28 16:31:29 -04005326 const uint32_t count = Inst->getWordCount();
5327 if (count > 65535) {
5328 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
5329 llvm_unreachable("Word count too high");
5330 }
David Neto22f144c2017-06-12 14:26:21 -04005331 Word |= Inst->getWordCount() << 16;
5332 WriteOneWord(Word);
5333}
5334
5335void SPIRVProducerPass::WriteOperand(SPIRVOperand *Op) {
5336 SPIRVOperandType OpTy = Op->getType();
5337 switch (OpTy) {
5338 default: {
5339 llvm_unreachable("Unsupported SPIRV Operand Type???");
5340 break;
5341 }
5342 case SPIRVOperandType::NUMBERID: {
5343 WriteOneWord(Op->getNumID());
5344 break;
5345 }
5346 case SPIRVOperandType::LITERAL_STRING: {
5347 std::string Str = Op->getLiteralStr();
5348 const char *Data = Str.c_str();
5349 size_t WordSize = Str.size() / 4;
5350 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
5351 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
5352 }
5353
5354 uint32_t Remainder = Str.size() % 4;
5355 uint32_t LastWord = 0;
5356 if (Remainder) {
5357 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
5358 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
5359 }
5360 }
5361
5362 WriteOneWord(LastWord);
5363 break;
5364 }
5365 case SPIRVOperandType::LITERAL_INTEGER:
5366 case SPIRVOperandType::LITERAL_FLOAT: {
5367 auto LiteralNum = Op->getLiteralNum();
5368 // TODO: Handle LiteranNum carefully.
5369 for (auto Word : LiteralNum) {
5370 WriteOneWord(Word);
5371 }
5372 break;
5373 }
5374 }
5375}
5376
5377void SPIRVProducerPass::WriteSPIRVBinary() {
5378 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5379
5380 for (auto Inst : SPIRVInstList) {
David Netoc6f3ab22018-04-06 18:02:31 -04005381 SPIRVOperandList Ops{Inst->getOperands()};
David Neto22f144c2017-06-12 14:26:21 -04005382 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5383
5384 switch (Opcode) {
5385 default: {
David Neto5c22a252018-03-15 16:07:41 -04005386 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04005387 llvm_unreachable("Unsupported SPIRV instruction");
5388 break;
5389 }
5390 case spv::OpCapability:
5391 case spv::OpExtension:
5392 case spv::OpMemoryModel:
5393 case spv::OpEntryPoint:
5394 case spv::OpExecutionMode:
5395 case spv::OpSource:
5396 case spv::OpDecorate:
5397 case spv::OpMemberDecorate:
5398 case spv::OpBranch:
5399 case spv::OpBranchConditional:
5400 case spv::OpSelectionMerge:
5401 case spv::OpLoopMerge:
5402 case spv::OpStore:
5403 case spv::OpImageWrite:
5404 case spv::OpReturnValue:
5405 case spv::OpControlBarrier:
5406 case spv::OpMemoryBarrier:
5407 case spv::OpReturn:
5408 case spv::OpFunctionEnd:
5409 case spv::OpCopyMemory: {
5410 WriteWordCountAndOpcode(Inst);
5411 for (uint32_t i = 0; i < Ops.size(); i++) {
5412 WriteOperand(Ops[i]);
5413 }
5414 break;
5415 }
5416 case spv::OpTypeBool:
5417 case spv::OpTypeVoid:
5418 case spv::OpTypeSampler:
5419 case spv::OpLabel:
5420 case spv::OpExtInstImport:
5421 case spv::OpTypePointer:
5422 case spv::OpTypeRuntimeArray:
5423 case spv::OpTypeStruct:
5424 case spv::OpTypeImage:
5425 case spv::OpTypeSampledImage:
5426 case spv::OpTypeInt:
5427 case spv::OpTypeFloat:
5428 case spv::OpTypeArray:
5429 case spv::OpTypeVector:
5430 case spv::OpTypeFunction: {
5431 WriteWordCountAndOpcode(Inst);
5432 WriteResultID(Inst);
5433 for (uint32_t i = 0; i < Ops.size(); i++) {
5434 WriteOperand(Ops[i]);
5435 }
5436 break;
5437 }
5438 case spv::OpFunction:
5439 case spv::OpFunctionParameter:
5440 case spv::OpAccessChain:
5441 case spv::OpPtrAccessChain:
5442 case spv::OpInBoundsAccessChain:
5443 case spv::OpUConvert:
5444 case spv::OpSConvert:
5445 case spv::OpConvertFToU:
5446 case spv::OpConvertFToS:
5447 case spv::OpConvertUToF:
5448 case spv::OpConvertSToF:
5449 case spv::OpFConvert:
5450 case spv::OpConvertPtrToU:
5451 case spv::OpConvertUToPtr:
5452 case spv::OpBitcast:
5453 case spv::OpIAdd:
5454 case spv::OpFAdd:
5455 case spv::OpISub:
5456 case spv::OpFSub:
5457 case spv::OpIMul:
5458 case spv::OpFMul:
5459 case spv::OpUDiv:
5460 case spv::OpSDiv:
5461 case spv::OpFDiv:
5462 case spv::OpUMod:
5463 case spv::OpSRem:
5464 case spv::OpFRem:
Kévin Petit8a560882019-03-21 15:24:34 +00005465 case spv::OpUMulExtended:
5466 case spv::OpSMulExtended:
David Neto22f144c2017-06-12 14:26:21 -04005467 case spv::OpBitwiseOr:
5468 case spv::OpBitwiseXor:
5469 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005470 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005471 case spv::OpShiftLeftLogical:
5472 case spv::OpShiftRightLogical:
5473 case spv::OpShiftRightArithmetic:
5474 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04005475 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04005476 case spv::OpCompositeExtract:
5477 case spv::OpVectorExtractDynamic:
5478 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04005479 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04005480 case spv::OpVectorInsertDynamic:
5481 case spv::OpVectorShuffle:
5482 case spv::OpIEqual:
5483 case spv::OpINotEqual:
5484 case spv::OpUGreaterThan:
5485 case spv::OpUGreaterThanEqual:
5486 case spv::OpULessThan:
5487 case spv::OpULessThanEqual:
5488 case spv::OpSGreaterThan:
5489 case spv::OpSGreaterThanEqual:
5490 case spv::OpSLessThan:
5491 case spv::OpSLessThanEqual:
5492 case spv::OpFOrdEqual:
5493 case spv::OpFOrdGreaterThan:
5494 case spv::OpFOrdGreaterThanEqual:
5495 case spv::OpFOrdLessThan:
5496 case spv::OpFOrdLessThanEqual:
5497 case spv::OpFOrdNotEqual:
5498 case spv::OpFUnordEqual:
5499 case spv::OpFUnordGreaterThan:
5500 case spv::OpFUnordGreaterThanEqual:
5501 case spv::OpFUnordLessThan:
5502 case spv::OpFUnordLessThanEqual:
5503 case spv::OpFUnordNotEqual:
5504 case spv::OpExtInst:
5505 case spv::OpIsInf:
5506 case spv::OpIsNan:
5507 case spv::OpAny:
5508 case spv::OpAll:
5509 case spv::OpUndef:
5510 case spv::OpConstantNull:
5511 case spv::OpLogicalOr:
5512 case spv::OpLogicalAnd:
5513 case spv::OpLogicalNot:
5514 case spv::OpLogicalNotEqual:
5515 case spv::OpConstantComposite:
5516 case spv::OpSpecConstantComposite:
5517 case spv::OpConstantTrue:
5518 case spv::OpConstantFalse:
5519 case spv::OpConstant:
5520 case spv::OpSpecConstant:
5521 case spv::OpVariable:
5522 case spv::OpFunctionCall:
5523 case spv::OpSampledImage:
5524 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04005525 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04005526 case spv::OpSelect:
5527 case spv::OpPhi:
5528 case spv::OpLoad:
5529 case spv::OpAtomicIAdd:
5530 case spv::OpAtomicISub:
5531 case spv::OpAtomicExchange:
5532 case spv::OpAtomicIIncrement:
5533 case spv::OpAtomicIDecrement:
5534 case spv::OpAtomicCompareExchange:
5535 case spv::OpAtomicUMin:
5536 case spv::OpAtomicSMin:
5537 case spv::OpAtomicUMax:
5538 case spv::OpAtomicSMax:
5539 case spv::OpAtomicAnd:
5540 case spv::OpAtomicOr:
5541 case spv::OpAtomicXor:
5542 case spv::OpDot: {
5543 WriteWordCountAndOpcode(Inst);
5544 WriteOperand(Ops[0]);
5545 WriteResultID(Inst);
5546 for (uint32_t i = 1; i < Ops.size(); i++) {
5547 WriteOperand(Ops[i]);
5548 }
5549 break;
5550 }
5551 }
5552 }
5553}
Alan Baker9bf93fb2018-08-28 16:59:26 -04005554
alan-bakerb6b09dc2018-11-08 16:59:28 -05005555bool SPIRVProducerPass::IsTypeNullable(const Type *type) const {
Alan Baker9bf93fb2018-08-28 16:59:26 -04005556 switch (type->getTypeID()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005557 case Type::HalfTyID:
5558 case Type::FloatTyID:
5559 case Type::DoubleTyID:
5560 case Type::IntegerTyID:
5561 case Type::VectorTyID:
5562 return true;
5563 case Type::PointerTyID: {
5564 const PointerType *pointer_type = cast<PointerType>(type);
5565 if (pointer_type->getPointerAddressSpace() !=
5566 AddressSpace::UniformConstant) {
5567 auto pointee_type = pointer_type->getPointerElementType();
5568 if (pointee_type->isStructTy() &&
5569 cast<StructType>(pointee_type)->isOpaque()) {
5570 // Images and samplers are not nullable.
5571 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04005572 }
Alan Baker9bf93fb2018-08-28 16:59:26 -04005573 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05005574 return true;
5575 }
5576 case Type::ArrayTyID:
5577 return IsTypeNullable(cast<CompositeType>(type)->getTypeAtIndex(0u));
5578 case Type::StructTyID: {
5579 const StructType *struct_type = cast<StructType>(type);
5580 // Images and samplers are not nullable.
5581 if (struct_type->isOpaque())
Alan Baker9bf93fb2018-08-28 16:59:26 -04005582 return false;
alan-bakerb6b09dc2018-11-08 16:59:28 -05005583 for (const auto element : struct_type->elements()) {
5584 if (!IsTypeNullable(element))
5585 return false;
5586 }
5587 return true;
5588 }
5589 default:
5590 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04005591 }
5592}
Alan Bakerfcda9482018-10-02 17:09:59 -04005593
5594void SPIRVProducerPass::PopulateUBOTypeMaps(Module &module) {
5595 if (auto *offsets_md =
5596 module.getNamedMetadata(clspv::RemappedTypeOffsetMetadataName())) {
5597 // Metdata is stored as key-value pair operands. The first element of each
5598 // operand is the type and the second is a vector of offsets.
5599 for (const auto *operand : offsets_md->operands()) {
5600 const auto *pair = cast<MDTuple>(operand);
5601 auto *type =
5602 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
5603 const auto *offset_vector = cast<MDTuple>(pair->getOperand(1));
5604 std::vector<uint32_t> offsets;
5605 for (const Metadata *offset_md : offset_vector->operands()) {
5606 const auto *constant_md = cast<ConstantAsMetadata>(offset_md);
alan-bakerb6b09dc2018-11-08 16:59:28 -05005607 offsets.push_back(static_cast<uint32_t>(
5608 cast<ConstantInt>(constant_md->getValue())->getZExtValue()));
Alan Bakerfcda9482018-10-02 17:09:59 -04005609 }
5610 RemappedUBOTypeOffsets.insert(std::make_pair(type, offsets));
5611 }
5612 }
5613
5614 if (auto *sizes_md =
5615 module.getNamedMetadata(clspv::RemappedTypeSizesMetadataName())) {
5616 // Metadata is stored as key-value pair operands. The first element of each
5617 // operand is the type and the second is a triple of sizes: type size in
5618 // bits, store size and alloc size.
5619 for (const auto *operand : sizes_md->operands()) {
5620 const auto *pair = cast<MDTuple>(operand);
5621 auto *type =
5622 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
5623 const auto *size_triple = cast<MDTuple>(pair->getOperand(1));
5624 uint64_t type_size_in_bits =
5625 cast<ConstantInt>(
5626 cast<ConstantAsMetadata>(size_triple->getOperand(0))->getValue())
5627 ->getZExtValue();
5628 uint64_t type_store_size =
5629 cast<ConstantInt>(
5630 cast<ConstantAsMetadata>(size_triple->getOperand(1))->getValue())
5631 ->getZExtValue();
5632 uint64_t type_alloc_size =
5633 cast<ConstantInt>(
5634 cast<ConstantAsMetadata>(size_triple->getOperand(2))->getValue())
5635 ->getZExtValue();
5636 RemappedUBOTypeSizes.insert(std::make_pair(
5637 type, std::make_tuple(type_size_in_bits, type_store_size,
5638 type_alloc_size)));
5639 }
5640 }
5641}
5642
5643uint64_t SPIRVProducerPass::GetTypeSizeInBits(Type *type,
5644 const DataLayout &DL) {
5645 auto iter = RemappedUBOTypeSizes.find(type);
5646 if (iter != RemappedUBOTypeSizes.end()) {
5647 return std::get<0>(iter->second);
5648 }
5649
5650 return DL.getTypeSizeInBits(type);
5651}
5652
5653uint64_t SPIRVProducerPass::GetTypeStoreSize(Type *type, const DataLayout &DL) {
5654 auto iter = RemappedUBOTypeSizes.find(type);
5655 if (iter != RemappedUBOTypeSizes.end()) {
5656 return std::get<1>(iter->second);
5657 }
5658
5659 return DL.getTypeStoreSize(type);
5660}
5661
5662uint64_t SPIRVProducerPass::GetTypeAllocSize(Type *type, const DataLayout &DL) {
5663 auto iter = RemappedUBOTypeSizes.find(type);
5664 if (iter != RemappedUBOTypeSizes.end()) {
5665 return std::get<2>(iter->second);
5666 }
5667
5668 return DL.getTypeAllocSize(type);
5669}
alan-baker5b86ed72019-02-15 08:26:50 -05005670
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04005671void SPIRVProducerPass::setVariablePointersCapabilities(
5672 unsigned address_space) {
alan-baker5b86ed72019-02-15 08:26:50 -05005673 if (GetStorageClass(address_space) == spv::StorageClassStorageBuffer) {
5674 setVariablePointersStorageBuffer(true);
5675 } else {
5676 setVariablePointers(true);
5677 }
5678}
5679
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04005680Value *SPIRVProducerPass::GetBasePointer(Value *v) {
alan-baker5b86ed72019-02-15 08:26:50 -05005681 if (auto *gep = dyn_cast<GetElementPtrInst>(v)) {
5682 return GetBasePointer(gep->getPointerOperand());
5683 }
5684
5685 // Conservatively return |v|.
5686 return v;
5687}
5688
5689bool SPIRVProducerPass::sameResource(Value *lhs, Value *rhs) const {
5690 if (auto *lhs_call = dyn_cast<CallInst>(lhs)) {
5691 if (auto *rhs_call = dyn_cast<CallInst>(rhs)) {
5692 if (lhs_call->getCalledFunction()->getName().startswith(
5693 clspv::ResourceAccessorFunction()) &&
5694 rhs_call->getCalledFunction()->getName().startswith(
5695 clspv::ResourceAccessorFunction())) {
5696 // For resource accessors, match descriptor set and binding.
5697 if (lhs_call->getOperand(0) == rhs_call->getOperand(0) &&
5698 lhs_call->getOperand(1) == rhs_call->getOperand(1))
5699 return true;
5700 } else if (lhs_call->getCalledFunction()->getName().startswith(
5701 clspv::WorkgroupAccessorFunction()) &&
5702 rhs_call->getCalledFunction()->getName().startswith(
5703 clspv::WorkgroupAccessorFunction())) {
5704 // For workgroup resources, match spec id.
5705 if (lhs_call->getOperand(0) == rhs_call->getOperand(0))
5706 return true;
5707 }
5708 }
5709 }
5710
5711 return false;
5712}
5713
5714bool SPIRVProducerPass::selectFromSameObject(Instruction *inst) {
5715 assert(inst->getType()->isPointerTy());
5716 assert(GetStorageClass(inst->getType()->getPointerAddressSpace()) ==
5717 spv::StorageClassStorageBuffer);
5718 const bool hack_undef = clspv::Option::HackUndef();
5719 if (auto *select = dyn_cast<SelectInst>(inst)) {
5720 auto *true_base = GetBasePointer(select->getTrueValue());
5721 auto *false_base = GetBasePointer(select->getFalseValue());
5722
5723 if (true_base == false_base)
5724 return true;
5725
5726 // If either the true or false operand is a null, then we satisfy the same
5727 // object constraint.
5728 if (auto *true_cst = dyn_cast<Constant>(true_base)) {
5729 if (true_cst->isNullValue() || (hack_undef && isa<UndefValue>(true_base)))
5730 return true;
5731 }
5732
5733 if (auto *false_cst = dyn_cast<Constant>(false_base)) {
5734 if (false_cst->isNullValue() ||
5735 (hack_undef && isa<UndefValue>(false_base)))
5736 return true;
5737 }
5738
5739 if (sameResource(true_base, false_base))
5740 return true;
5741 } else if (auto *phi = dyn_cast<PHINode>(inst)) {
5742 Value *value = nullptr;
5743 bool ok = true;
5744 for (unsigned i = 0; ok && i != phi->getNumIncomingValues(); ++i) {
5745 auto *base = GetBasePointer(phi->getIncomingValue(i));
5746 // Null values satisfy the constraint of selecting of selecting from the
5747 // same object.
5748 if (!value) {
5749 if (auto *cst = dyn_cast<Constant>(base)) {
5750 if (!cst->isNullValue() && !(hack_undef && isa<UndefValue>(base)))
5751 value = base;
5752 } else {
5753 value = base;
5754 }
5755 } else if (base != value) {
5756 if (auto *base_cst = dyn_cast<Constant>(base)) {
5757 if (base_cst->isNullValue() || (hack_undef && isa<UndefValue>(base)))
5758 continue;
5759 }
5760
5761 if (sameResource(value, base))
5762 continue;
5763
5764 // Values don't represent the same base.
5765 ok = false;
5766 }
5767 }
5768
5769 return ok;
5770 }
5771
5772 // Conservatively return false.
5773 return false;
5774}
alan-bakere9308012019-03-15 10:25:13 -04005775
5776bool SPIRVProducerPass::CalledWithCoherentResource(Argument &Arg) {
5777 if (!Arg.getType()->isPointerTy() ||
5778 Arg.getType()->getPointerAddressSpace() != clspv::AddressSpace::Global) {
5779 // Only SSBOs need to be annotated as coherent.
5780 return false;
5781 }
5782
5783 DenseSet<Value *> visited;
5784 std::vector<Value *> stack;
5785 for (auto *U : Arg.getParent()->users()) {
5786 if (auto *call = dyn_cast<CallInst>(U)) {
5787 stack.push_back(call->getOperand(Arg.getArgNo()));
5788 }
5789 }
5790
5791 while (!stack.empty()) {
5792 Value *v = stack.back();
5793 stack.pop_back();
5794
5795 if (!visited.insert(v).second)
5796 continue;
5797
5798 auto *resource_call = dyn_cast<CallInst>(v);
5799 if (resource_call &&
5800 resource_call->getCalledFunction()->getName().startswith(
5801 clspv::ResourceAccessorFunction())) {
5802 // If this is a resource accessor function, check if the coherent operand
5803 // is set.
5804 const auto coherent =
5805 unsigned(dyn_cast<ConstantInt>(resource_call->getArgOperand(5))
5806 ->getZExtValue());
5807 if (coherent == 1)
5808 return true;
5809 } else if (auto *arg = dyn_cast<Argument>(v)) {
5810 // If this is a function argument, trace through its callers.
alan-bakere98f3f92019-04-08 15:06:36 -04005811 for (auto U : arg->getParent()->users()) {
alan-bakere9308012019-03-15 10:25:13 -04005812 if (auto *call = dyn_cast<CallInst>(U)) {
5813 stack.push_back(call->getOperand(arg->getArgNo()));
5814 }
5815 }
5816 } else if (auto *user = dyn_cast<User>(v)) {
5817 // If this is a user, traverse all operands that could lead to resource
5818 // variables.
5819 for (unsigned i = 0; i != user->getNumOperands(); ++i) {
5820 Value *operand = user->getOperand(i);
5821 if (operand->getType()->isPointerTy() &&
5822 operand->getType()->getPointerAddressSpace() ==
5823 clspv::AddressSpace::Global) {
5824 stack.push_back(operand);
5825 }
5826 }
5827 }
5828 }
5829
5830 // No coherent resource variables encountered.
5831 return false;
5832}