blob: 9382242d5e2ba11b02d726e7c0c96c547a51a86d [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 Neto22f144c2017-06-12 14:26:21 -040031
David Neto118188e2018-08-24 11:27:54 -040032#include "llvm/ADT/StringSwitch.h"
33#include "llvm/ADT/UniqueVector.h"
34#include "llvm/Analysis/LoopInfo.h"
35#include "llvm/IR/Constants.h"
36#include "llvm/IR/Dominators.h"
37#include "llvm/IR/Instructions.h"
38#include "llvm/IR/Metadata.h"
39#include "llvm/IR/Module.h"
40#include "llvm/Pass.h"
41#include "llvm/Support/CommandLine.h"
42#include "llvm/Support/raw_ostream.h"
43#include "llvm/Transforms/Utils/Cloning.h"
David Neto22f144c2017-06-12 14:26:21 -040044
David Neto85082642018-03-24 06:55:20 -070045#include "spirv/1.0/spirv.hpp"
David Neto118188e2018-08-24 11:27:54 -040046
David Neto85082642018-03-24 06:55:20 -070047#include "clspv/AddressSpace.h"
David Neto118188e2018-08-24 11:27:54 -040048#include "clspv/Option.h"
49#include "clspv/Passes.h"
David Neto85082642018-03-24 06:55:20 -070050#include "clspv/spirv_c_strings.hpp"
51#include "clspv/spirv_glsl.hpp"
David Neto22f144c2017-06-12 14:26:21 -040052
David Neto4feb7a42017-10-06 17:29:42 -040053#include "ArgKind.h"
David Neto85082642018-03-24 06:55:20 -070054#include "ConstantEmitter.h"
Alan Baker202c8c72018-08-13 13:47:44 -040055#include "Constants.h"
David Neto78383442018-06-15 20:31:56 -040056#include "DescriptorCounter.h"
David Neto48f56a42017-10-06 16:44:25 -040057
David Neto22f144c2017-06-12 14:26:21 -040058#if defined(_MSC_VER)
59#pragma warning(pop)
60#endif
61
62using namespace llvm;
63using namespace clspv;
David Neto156783e2017-07-05 15:39:41 -040064using namespace mdconst;
David Neto22f144c2017-06-12 14:26:21 -040065
66namespace {
David Netocd8ca5f2017-10-02 23:34:11 -040067
David Neto862b7d82018-06-14 18:48:37 -040068cl::opt<bool> ShowResourceVars("show-rv", cl::init(false), cl::Hidden,
69 cl::desc("Show resource variable creation"));
70
71// These hacks exist to help transition code generation algorithms
72// without making huge noise in detailed test output.
73const bool Hack_generate_runtime_array_stride_early = true;
74
David Neto3fbb4072017-10-16 11:28:14 -040075// The value of 1/pi. This value is from MSDN
76// https://msdn.microsoft.com/en-us/library/4hwaceh6.aspx
77const double kOneOverPi = 0.318309886183790671538;
78const glsl::ExtInst kGlslExtInstBad = static_cast<glsl::ExtInst>(0);
79
David Netoab03f432017-11-03 17:00:44 -040080const char* kCompositeConstructFunctionPrefix = "clspv.composite_construct.";
81
David Neto22f144c2017-06-12 14:26:21 -040082enum SPIRVOperandType {
83 NUMBERID,
84 LITERAL_INTEGER,
85 LITERAL_STRING,
86 LITERAL_FLOAT
87};
88
89struct SPIRVOperand {
90 explicit SPIRVOperand(SPIRVOperandType Ty, uint32_t Num)
91 : Type(Ty), LiteralNum(1, Num) {}
92 explicit SPIRVOperand(SPIRVOperandType Ty, const char *Str)
93 : Type(Ty), LiteralStr(Str) {}
94 explicit SPIRVOperand(SPIRVOperandType Ty, StringRef Str)
95 : Type(Ty), LiteralStr(Str) {}
96 explicit SPIRVOperand(SPIRVOperandType Ty, ArrayRef<uint32_t> NumVec)
97 : Type(Ty), LiteralNum(NumVec.begin(), NumVec.end()) {}
98
99 SPIRVOperandType getType() { return Type; };
100 uint32_t getNumID() { return LiteralNum[0]; };
101 std::string getLiteralStr() { return LiteralStr; };
102 ArrayRef<uint32_t> getLiteralNum() { return LiteralNum; };
103
David Neto87846742018-04-11 17:36:22 -0400104 uint32_t GetNumWords() const {
105 switch (Type) {
106 case NUMBERID:
107 return 1;
108 case LITERAL_INTEGER:
109 case LITERAL_FLOAT:
David Netoee2660d2018-06-28 16:31:29 -0400110 return uint32_t(LiteralNum.size());
David Neto87846742018-04-11 17:36:22 -0400111 case LITERAL_STRING:
112 // Account for the terminating null character.
David Netoee2660d2018-06-28 16:31:29 -0400113 return uint32_t((LiteralStr.size() + 4) / 4);
David Neto87846742018-04-11 17:36:22 -0400114 }
115 llvm_unreachable("Unhandled case in SPIRVOperand::GetNumWords()");
116 }
117
David Neto22f144c2017-06-12 14:26:21 -0400118private:
119 SPIRVOperandType Type;
120 std::string LiteralStr;
121 SmallVector<uint32_t, 4> LiteralNum;
122};
123
David Netoc6f3ab22018-04-06 18:02:31 -0400124class SPIRVOperandList {
125public:
126 SPIRVOperandList() {}
127 SPIRVOperandList(const SPIRVOperandList& other) = delete;
128 SPIRVOperandList(SPIRVOperandList&& other) {
129 contents_ = std::move(other.contents_);
130 other.contents_.clear();
131 }
132 SPIRVOperandList(ArrayRef<SPIRVOperand *> init)
133 : contents_(init.begin(), init.end()) {}
134 operator ArrayRef<SPIRVOperand *>() { return contents_; }
135 void push_back(SPIRVOperand *op) { contents_.push_back(op); }
136 void clear() { contents_.clear();}
137 size_t size() const { return contents_.size(); }
138 SPIRVOperand *&operator[](size_t i) { return contents_[i]; }
139
David Neto87846742018-04-11 17:36:22 -0400140 const SmallVector<SPIRVOperand *, 8> &getOperands() const {
141 return contents_;
142 }
143
David Netoc6f3ab22018-04-06 18:02:31 -0400144private:
145 SmallVector<SPIRVOperand *,8> contents_;
146};
147
148SPIRVOperandList &operator<<(SPIRVOperandList &list, SPIRVOperand *elem) {
149 list.push_back(elem);
150 return list;
151}
152
153SPIRVOperand* MkNum(uint32_t num) {
154 return new SPIRVOperand(LITERAL_INTEGER, num);
155}
David Neto257c3892018-04-11 13:19:45 -0400156SPIRVOperand* MkInteger(ArrayRef<uint32_t> num_vec) {
157 return new SPIRVOperand(LITERAL_INTEGER, num_vec);
158}
159SPIRVOperand* MkFloat(ArrayRef<uint32_t> num_vec) {
160 return new SPIRVOperand(LITERAL_FLOAT, num_vec);
161}
David Netoc6f3ab22018-04-06 18:02:31 -0400162SPIRVOperand* MkId(uint32_t id) {
163 return new SPIRVOperand(NUMBERID, id);
164}
David Neto257c3892018-04-11 13:19:45 -0400165SPIRVOperand* MkString(StringRef str) {
166 return new SPIRVOperand(LITERAL_STRING, str);
167}
David Netoc6f3ab22018-04-06 18:02:31 -0400168
David Neto22f144c2017-06-12 14:26:21 -0400169struct SPIRVInstruction {
David Neto87846742018-04-11 17:36:22 -0400170 // Create an instruction with an opcode and no result ID, and with the given
171 // operands. This computes its own word count.
172 explicit SPIRVInstruction(spv::Op Opc, ArrayRef<SPIRVOperand *> Ops)
173 : WordCount(1), Opcode(static_cast<uint16_t>(Opc)), ResultID(0),
174 Operands(Ops.begin(), Ops.end()) {
175 for (auto *operand : Ops) {
David Netoee2660d2018-06-28 16:31:29 -0400176 WordCount += uint16_t(operand->GetNumWords());
David Neto87846742018-04-11 17:36:22 -0400177 }
178 }
179 // Create an instruction with an opcode and a no-zero result ID, and
180 // with the given operands. This computes its own word count.
181 explicit SPIRVInstruction(spv::Op Opc, uint32_t ResID,
David Neto22f144c2017-06-12 14:26:21 -0400182 ArrayRef<SPIRVOperand *> Ops)
David Neto87846742018-04-11 17:36:22 -0400183 : WordCount(2), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID),
184 Operands(Ops.begin(), Ops.end()) {
185 if (ResID == 0) {
186 llvm_unreachable("Result ID of 0 was provided");
187 }
188 for (auto *operand : Ops) {
189 WordCount += operand->GetNumWords();
190 }
191 }
David Neto22f144c2017-06-12 14:26:21 -0400192
David Netoee2660d2018-06-28 16:31:29 -0400193 uint32_t getWordCount() const { return WordCount; }
David Neto22f144c2017-06-12 14:26:21 -0400194 uint16_t getOpcode() const { return Opcode; }
195 uint32_t getResultID() const { return ResultID; }
196 ArrayRef<SPIRVOperand *> getOperands() const { return Operands; }
197
198private:
David Netoee2660d2018-06-28 16:31:29 -0400199 uint32_t WordCount; // Check the 16-bit bound at code generation time.
David Neto22f144c2017-06-12 14:26:21 -0400200 uint16_t Opcode;
201 uint32_t ResultID;
202 SmallVector<SPIRVOperand *, 4> Operands;
203};
204
205struct SPIRVProducerPass final : public ModulePass {
David Neto22f144c2017-06-12 14:26:21 -0400206 typedef DenseMap<Type *, uint32_t> TypeMapType;
207 typedef UniqueVector<Type *> TypeList;
208 typedef DenseMap<Value *, uint32_t> ValueMapType;
David Netofb9a7972017-08-25 17:08:24 -0400209 typedef UniqueVector<Value *> ValueList;
David Neto22f144c2017-06-12 14:26:21 -0400210 typedef std::vector<std::pair<Value *, uint32_t>> EntryPointVecType;
211 typedef std::list<SPIRVInstruction *> SPIRVInstructionList;
David Neto87846742018-04-11 17:36:22 -0400212 // A vector of tuples, each of which is:
213 // - the LLVM instruction that we will later generate SPIR-V code for
214 // - where the SPIR-V instruction should be inserted
215 // - the result ID of the SPIR-V instruction
David Neto22f144c2017-06-12 14:26:21 -0400216 typedef std::vector<
217 std::tuple<Value *, SPIRVInstructionList::iterator, uint32_t>>
218 DeferredInstVecType;
219 typedef DenseMap<FunctionType *, std::pair<FunctionType *, uint32_t>>
220 GlobalConstFuncMapType;
221
David Neto44795152017-07-13 15:45:28 -0400222 explicit SPIRVProducerPass(
223 raw_pwrite_stream &out, raw_ostream &descriptor_map_out,
224 ArrayRef<std::pair<unsigned, std::string>> samplerMap, bool outputAsm,
225 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),
David Netoc2c368d2017-06-30 16:50:17 -0400228 descriptorMapOut(descriptor_map_out), outputAsm(outputAsm),
David Neto0676e6f2017-07-11 18:47:44 -0400229 outputCInitList(outputCInitList), patchBoundOffset(0), nextID(1),
David Netoa60b00b2017-09-15 16:34:09 -0400230 OpExtInstImportID(0), HasVariablePointers(false), SamplerTy(nullptr),
David Neto85082642018-03-24 06:55:20 -0700231 WorkgroupSizeValueID(0), WorkgroupSizeVarID(0),
Alan Baker202c8c72018-08-13 13:47:44 -0400232 max_local_spec_id_(0), constant_i32_zero_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; };
280 bool hasVariablePointers() { return true; /* We use StorageBuffer everywhere */ };
281 void setVariablePointers(bool Val) { HasVariablePointers = Val; };
David Neto44795152017-07-13 15:45:28 -0400282 ArrayRef<std::pair<unsigned, std::string>> &getSamplerMap() { return samplerMap; }
David Neto22f144c2017-06-12 14:26:21 -0400283 GlobalConstFuncMapType &getGlobalConstFuncTypeMap() {
284 return GlobalConstFuncTypeMap;
285 }
286 SmallPtrSet<Value *, 16> &getGlobalConstArgSet() {
287 return GlobalConstArgumentSet;
288 }
David Neto85082642018-03-24 06:55:20 -0700289 TypeList &getTypesNeedingArrayStride() {
290 return TypesNeedingArrayStride;
David Neto1a1a0582017-07-07 12:01:44 -0400291 }
David Neto22f144c2017-06-12 14:26:21 -0400292
David Netoc6f3ab22018-04-06 18:02:31 -0400293 void GenerateLLVMIRInfo(Module &M, const DataLayout &DL);
David Neto862b7d82018-06-14 18:48:37 -0400294 // Populate GlobalConstFuncTypeMap. Also, if module-scope __constant will *not*
295 // be converted to a storage buffer, replace each such global variable with
296 // one in the storage class expecgted by SPIR-V.
297 void FindGlobalConstVars(Module &M, const DataLayout &DL);
298 // Populate ResourceVarInfoList, FunctionToResourceVarsMap, and
299 // ModuleOrderedResourceVars.
300 void FindResourceVars(Module &M, const DataLayout &DL);
Alan Baker202c8c72018-08-13 13:47:44 -0400301 void FindWorkgroupVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400302 bool FindExtInst(Module &M);
303 void FindTypePerGlobalVar(GlobalVariable &GV);
304 void FindTypePerFunc(Function &F);
David Neto862b7d82018-06-14 18:48:37 -0400305 void FindTypesForSamplerMap(Module &M);
306 void FindTypesForResourceVars(Module &M);
David Neto19a1bad2017-08-25 15:01:41 -0400307 // Inserts |Ty| and relevant sub-types into the |Types| member, indicating that
308 // |Ty| and its subtypes will need a corresponding SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400309 void FindType(Type *Ty);
310 void FindConstantPerGlobalVar(GlobalVariable &GV);
311 void FindConstantPerFunc(Function &F);
312 void FindConstant(Value *V);
313 void GenerateExtInstImport();
David Neto19a1bad2017-08-25 15:01:41 -0400314 // Generates instructions for SPIR-V types corresponding to the LLVM types
315 // saved in the |Types| member. A type follows its subtypes. IDs are
316 // allocated sequentially starting with the current value of nextID, and
317 // with a type following its subtypes. Also updates nextID to just beyond
318 // the last generated ID.
David Netoc6f3ab22018-04-06 18:02:31 -0400319 void GenerateSPIRVTypes(LLVMContext& context, const DataLayout &DL);
David Neto22f144c2017-06-12 14:26:21 -0400320 void GenerateSPIRVConstants();
David Neto5c22a252018-03-15 16:07:41 -0400321 void GenerateModuleInfo(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400322 void GenerateGlobalVar(GlobalVariable &GV);
David Netoc6f3ab22018-04-06 18:02:31 -0400323 void GenerateWorkgroupVars();
David Neto862b7d82018-06-14 18:48:37 -0400324 // Generate descriptor map entries for resource variables associated with
325 // arguments to F.
326 void GenerateDescriptorMapInfo(const DataLayout& DL, Function& F);
David Neto22f144c2017-06-12 14:26:21 -0400327 void GenerateSamplers(Module &M);
David Neto862b7d82018-06-14 18:48:37 -0400328 // Generate OpVariables for %clspv.resource.var.* calls.
329 void GenerateResourceVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400330 void GenerateFuncPrologue(Function &F);
331 void GenerateFuncBody(Function &F);
David Netob6e2e062018-04-25 10:32:06 -0400332 void GenerateEntryPointInitialStores();
David Neto22f144c2017-06-12 14:26:21 -0400333 spv::Op GetSPIRVCmpOpcode(CmpInst *CmpI);
334 spv::Op GetSPIRVCastOpcode(Instruction &I);
335 spv::Op GetSPIRVBinaryOpcode(Instruction &I);
336 void GenerateInstruction(Instruction &I);
337 void GenerateFuncEpilogue();
338 void HandleDeferredInstruction();
David Neto1a1a0582017-07-07 12:01:44 -0400339 void HandleDeferredDecorations(const DataLayout& DL);
David Neto22f144c2017-06-12 14:26:21 -0400340 bool is4xi8vec(Type *Ty) const;
David Neto257c3892018-04-11 13:19:45 -0400341 // Return the SPIR-V Id for 32-bit constant zero. The constant must already
342 // have been created.
343 uint32_t GetI32Zero();
David Neto22f144c2017-06-12 14:26:21 -0400344 spv::StorageClass GetStorageClass(unsigned AddrSpace) const;
David Neto862b7d82018-06-14 18:48:37 -0400345 spv::StorageClass GetStorageClassForArgKind(clspv::ArgKind arg_kind) const;
David Neto22f144c2017-06-12 14:26:21 -0400346 spv::BuiltIn GetBuiltin(StringRef globalVarName) const;
David Neto3fbb4072017-10-16 11:28:14 -0400347 // Returns the GLSL extended instruction enum that the given function
348 // call maps to. If none, then returns the 0 value, i.e. GLSLstd4580Bad.
David Neto22f144c2017-06-12 14:26:21 -0400349 glsl::ExtInst getExtInstEnum(StringRef Name);
David Neto3fbb4072017-10-16 11:28:14 -0400350 // Returns the GLSL extended instruction enum indirectly used by the given
351 // function. That is, to implement the given function, we use an extended
352 // instruction plus one more instruction. If none, then returns the 0 value,
353 // i.e. GLSLstd4580Bad.
354 glsl::ExtInst getIndirectExtInstEnum(StringRef Name);
355 // Returns the single GLSL extended instruction used directly or
356 // indirectly by the given function call.
357 glsl::ExtInst getDirectOrIndirectExtInstEnum(StringRef Name);
David Neto22f144c2017-06-12 14:26:21 -0400358 void PrintResID(SPIRVInstruction *Inst);
359 void PrintOpcode(SPIRVInstruction *Inst);
360 void PrintOperand(SPIRVOperand *Op);
361 void PrintCapability(SPIRVOperand *Op);
362 void PrintExtInst(SPIRVOperand *Op);
363 void PrintAddrModel(SPIRVOperand *Op);
364 void PrintMemModel(SPIRVOperand *Op);
365 void PrintExecModel(SPIRVOperand *Op);
366 void PrintExecMode(SPIRVOperand *Op);
367 void PrintSourceLanguage(SPIRVOperand *Op);
368 void PrintFuncCtrl(SPIRVOperand *Op);
369 void PrintStorageClass(SPIRVOperand *Op);
370 void PrintDecoration(SPIRVOperand *Op);
371 void PrintBuiltIn(SPIRVOperand *Op);
372 void PrintSelectionControl(SPIRVOperand *Op);
373 void PrintLoopControl(SPIRVOperand *Op);
374 void PrintDimensionality(SPIRVOperand *Op);
375 void PrintImageFormat(SPIRVOperand *Op);
376 void PrintMemoryAccess(SPIRVOperand *Op);
377 void PrintImageOperandsType(SPIRVOperand *Op);
378 void WriteSPIRVAssembly();
379 void WriteOneWord(uint32_t Word);
380 void WriteResultID(SPIRVInstruction *Inst);
381 void WriteWordCountAndOpcode(SPIRVInstruction *Inst);
382 void WriteOperand(SPIRVOperand *Op);
383 void WriteSPIRVBinary();
384
Alan Baker9bf93fb2018-08-28 16:59:26 -0400385 // Returns true if |type| is compatible with OpConstantNull.
386 bool IsTypeNullable(const Type* type) const;
387
David Neto22f144c2017-06-12 14:26:21 -0400388private:
389 static char ID;
David Neto44795152017-07-13 15:45:28 -0400390 ArrayRef<std::pair<unsigned, std::string>> samplerMap;
David Neto22f144c2017-06-12 14:26:21 -0400391 raw_pwrite_stream &out;
David Neto0676e6f2017-07-11 18:47:44 -0400392
393 // TODO(dneto): Wouldn't it be better to always just emit a binary, and then
394 // convert to other formats on demand?
395
396 // When emitting a C initialization list, the WriteSPIRVBinary method
397 // will actually write its words to this vector via binaryTempOut.
398 SmallVector<char, 100> binaryTempUnderlyingVector;
399 raw_svector_ostream binaryTempOut;
400
401 // Binary output writes to this stream, which might be |out| or
402 // |binaryTempOut|. It's the latter when we really want to write a C
403 // initializer list.
404 raw_pwrite_stream* binaryOut;
David Netoc2c368d2017-06-30 16:50:17 -0400405 raw_ostream &descriptorMapOut;
David Neto22f144c2017-06-12 14:26:21 -0400406 const bool outputAsm;
David Neto0676e6f2017-07-11 18:47:44 -0400407 const bool outputCInitList; // If true, output look like {0x7023, ... , 5}
David Neto22f144c2017-06-12 14:26:21 -0400408 uint64_t patchBoundOffset;
409 uint32_t nextID;
410
David Neto19a1bad2017-08-25 15:01:41 -0400411 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400412 TypeMapType TypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400413 // Maps an LLVM image type to its SPIR-V ID.
David Neto22f144c2017-06-12 14:26:21 -0400414 TypeMapType ImageTypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400415 // A unique-vector of LLVM types that map to a SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400416 TypeList Types;
417 ValueList Constants;
David Neto19a1bad2017-08-25 15:01:41 -0400418 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400419 ValueMapType ValueMap;
420 ValueMapType AllocatedValueMap;
421 SPIRVInstructionList SPIRVInsts;
David Neto862b7d82018-06-14 18:48:37 -0400422
David Neto22f144c2017-06-12 14:26:21 -0400423 EntryPointVecType EntryPointVec;
424 DeferredInstVecType DeferredInstVec;
425 ValueList EntryPointInterfacesVec;
426 uint32_t OpExtInstImportID;
427 std::vector<uint32_t> BuiltinDimensionVec;
428 bool HasVariablePointers;
429 Type *SamplerTy;
David Neto862b7d82018-06-14 18:48:37 -0400430 DenseMap<unsigned,uint32_t> SamplerMapIndexToIDMap;
David Netoc77d9e22018-03-24 06:30:28 -0700431
432 // If a function F has a pointer-to-__constant parameter, then this variable
David Neto9ed8e2f2018-03-24 06:47:24 -0700433 // will map F's type to (G, index of the parameter), where in a first phase
434 // G is F's type. During FindTypePerFunc, G will be changed to F's type
435 // but replacing the pointer-to-constant parameter with
436 // pointer-to-ModuleScopePrivate.
David Netoc77d9e22018-03-24 06:30:28 -0700437 // TODO(dneto): This doesn't seem general enough? A function might have
438 // more than one such parameter.
David Neto22f144c2017-06-12 14:26:21 -0400439 GlobalConstFuncMapType GlobalConstFuncTypeMap;
440 SmallPtrSet<Value *, 16> GlobalConstArgumentSet;
David Neto1a1a0582017-07-07 12:01:44 -0400441 // An ordered set of pointer types of Base arguments to OpPtrAccessChain,
David Neto85082642018-03-24 06:55:20 -0700442 // or array types, and which point into transparent memory (StorageBuffer
443 // storage class). These will require an ArrayStride decoration.
David Neto1a1a0582017-07-07 12:01:44 -0400444 // See SPV_KHR_variable_pointers rev 13.
David Neto85082642018-03-24 06:55:20 -0700445 TypeList TypesNeedingArrayStride;
David Netoa60b00b2017-09-15 16:34:09 -0400446
447 // This is truly ugly, but works around what look like driver bugs.
448 // For get_local_size, an earlier part of the flow has created a module-scope
449 // variable in Private address space to hold the value for the workgroup
450 // size. Its intializer is a uint3 value marked as builtin WorkgroupSize.
451 // When this is present, save the IDs of the initializer value and variable
452 // in these two variables. We only ever do a vector load from it, and
453 // when we see one of those, substitute just the value of the intializer.
454 // This mimics what Glslang does, and that's what drivers are used to.
David Neto66cfe642018-03-24 06:13:56 -0700455 // TODO(dneto): Remove this once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -0400456 uint32_t WorkgroupSizeValueID;
457 uint32_t WorkgroupSizeVarID;
David Neto26aaf622017-10-23 18:11:53 -0400458
David Neto862b7d82018-06-14 18:48:37 -0400459 // Bookkeeping for mapping kernel arguments to resource variables.
460 struct ResourceVarInfo {
461 ResourceVarInfo(int index_arg, unsigned set_arg, unsigned binding_arg,
462 Function *fn, clspv::ArgKind arg_kind_arg)
463 : index(index_arg), descriptor_set(set_arg), binding(binding_arg),
464 var_fn(fn), arg_kind(arg_kind_arg),
465 addr_space(fn->getReturnType()->getPointerAddressSpace()) {}
466 const int index; // Index into ResourceVarInfoList
467 const unsigned descriptor_set;
468 const unsigned binding;
469 Function *const var_fn; // The @clspv.resource.var.* function.
470 const clspv::ArgKind arg_kind;
471 const unsigned addr_space; // The LLVM address space
472 // The SPIR-V ID of the OpVariable. Not populated at construction time.
473 uint32_t var_id = 0;
474 };
475 // A list of resource var info. Each one correponds to a module-scope
476 // resource variable we will have to create. Resource var indices are
477 // indices into this vector.
478 SmallVector<std::unique_ptr<ResourceVarInfo>, 8> ResourceVarInfoList;
479 // This is a vector of pointers of all the resource vars, but ordered by
480 // kernel function, and then by argument.
481 UniqueVector<ResourceVarInfo*> ModuleOrderedResourceVars;
482 // Map a function to the ordered list of resource variables it uses, one for
483 // each argument. If an argument does not use a resource variable, it
484 // will have a null pointer entry.
485 using FunctionToResourceVarsMapType =
486 DenseMap<Function *, SmallVector<ResourceVarInfo *, 8>>;
487 FunctionToResourceVarsMapType FunctionToResourceVarsMap;
488
489 // What LLVM types map to SPIR-V types needing layout? These are the
490 // arrays and structures supporting storage buffers and uniform buffers.
491 TypeList TypesNeedingLayout;
492 // What LLVM struct types map to a SPIR-V struct type with Block decoration?
493 UniqueVector<StructType *> StructTypesNeedingBlock;
494 // For a call that represents a load from an opaque type (samplers, images),
495 // map it to the variable id it should load from.
496 DenseMap<CallInst *, uint32_t> ResourceVarDeferredLoadCalls;
David Neto85082642018-03-24 06:55:20 -0700497
Alan Baker202c8c72018-08-13 13:47:44 -0400498 // One larger than the maximum used SpecId for pointer-to-local arguments.
499 int max_local_spec_id_;
David Netoc6f3ab22018-04-06 18:02:31 -0400500 // An ordered list of the kernel arguments of type pointer-to-local.
Alan Baker202c8c72018-08-13 13:47:44 -0400501 using LocalArgList = SmallVector<Argument*, 8>;
David Netoc6f3ab22018-04-06 18:02:31 -0400502 LocalArgList LocalArgs;
503 // Information about a pointer-to-local argument.
504 struct LocalArgInfo {
505 // The SPIR-V ID of the array variable.
506 uint32_t variable_id;
507 // The element type of the
508 Type* elem_type;
509 // The ID of the array type.
510 uint32_t array_size_id;
511 // The ID of the array type.
512 uint32_t array_type_id;
513 // The ID of the pointer to the array type.
514 uint32_t ptr_array_type_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400515 // The specialization constant ID of the array size.
516 int spec_id;
517 };
Alan Baker202c8c72018-08-13 13:47:44 -0400518 // A mapping from Argument to its assigned SpecId.
519 DenseMap<const Argument*, int> LocalArgSpecIds;
520 // A mapping from SpecId to its LocalArgInfo.
521 DenseMap<int, LocalArgInfo> LocalSpecIdInfoMap;
David Neto257c3892018-04-11 13:19:45 -0400522
523 // The ID of 32-bit integer zero constant. This is only valid after
524 // GenerateSPIRVConstants has run.
525 uint32_t constant_i32_zero_id_;
David Neto22f144c2017-06-12 14:26:21 -0400526};
527
528char SPIRVProducerPass::ID;
David Netoc6f3ab22018-04-06 18:02:31 -0400529
David Neto22f144c2017-06-12 14:26:21 -0400530}
531
532namespace clspv {
David Neto44795152017-07-13 15:45:28 -0400533ModulePass *
534createSPIRVProducerPass(raw_pwrite_stream &out, raw_ostream &descriptor_map_out,
535 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
536 bool outputAsm, bool outputCInitList) {
537 return new SPIRVProducerPass(out, descriptor_map_out, samplerMap, outputAsm,
538 outputCInitList);
David Neto22f144c2017-06-12 14:26:21 -0400539}
David Netoc2c368d2017-06-30 16:50:17 -0400540} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400541
542bool SPIRVProducerPass::runOnModule(Module &module) {
David Neto0676e6f2017-07-11 18:47:44 -0400543 binaryOut = outputCInitList ? &binaryTempOut : &out;
544
David Neto257c3892018-04-11 13:19:45 -0400545 constant_i32_zero_id_ = 0; // Reset, for the benefit of validity checks.
546
David Neto22f144c2017-06-12 14:26:21 -0400547 // SPIR-V always begins with its header information
548 outputHeader();
549
David Netoc6f3ab22018-04-06 18:02:31 -0400550 const DataLayout &DL = module.getDataLayout();
551
David Neto22f144c2017-06-12 14:26:21 -0400552 // Gather information from the LLVM IR that we require.
David Netoc6f3ab22018-04-06 18:02:31 -0400553 GenerateLLVMIRInfo(module, DL);
David Neto22f144c2017-06-12 14:26:21 -0400554
David Neto22f144c2017-06-12 14:26:21 -0400555 // Collect information on global variables too.
556 for (GlobalVariable &GV : module.globals()) {
557 // If the GV is one of our special __spirv_* variables, remove the
558 // initializer as it was only placed there to force LLVM to not throw the
559 // value away.
560 if (GV.getName().startswith("__spirv_")) {
561 GV.setInitializer(nullptr);
562 }
563
564 // Collect types' information from global variable.
565 FindTypePerGlobalVar(GV);
566
567 // Collect constant information from global variable.
568 FindConstantPerGlobalVar(GV);
569
570 // If the variable is an input, entry points need to know about it.
571 if (AddressSpace::Input == GV.getType()->getPointerAddressSpace()) {
David Netofb9a7972017-08-25 17:08:24 -0400572 getEntryPointInterfacesVec().insert(&GV);
David Neto22f144c2017-06-12 14:26:21 -0400573 }
574 }
575
576 // If there are extended instructions, generate OpExtInstImport.
577 if (FindExtInst(module)) {
578 GenerateExtInstImport();
579 }
580
581 // Generate SPIRV instructions for types.
David Netoc6f3ab22018-04-06 18:02:31 -0400582 GenerateSPIRVTypes(module.getContext(), DL);
David Neto22f144c2017-06-12 14:26:21 -0400583
584 // Generate SPIRV constants.
585 GenerateSPIRVConstants();
586
587 // If we have a sampler map, we might have literal samplers to generate.
588 if (0 < getSamplerMap().size()) {
589 GenerateSamplers(module);
590 }
591
592 // Generate SPIRV variables.
593 for (GlobalVariable &GV : module.globals()) {
594 GenerateGlobalVar(GV);
595 }
David Neto862b7d82018-06-14 18:48:37 -0400596 GenerateResourceVars(module);
David Netoc6f3ab22018-04-06 18:02:31 -0400597 GenerateWorkgroupVars();
David Neto22f144c2017-06-12 14:26:21 -0400598
599 // Generate SPIRV instructions for each function.
600 for (Function &F : module) {
601 if (F.isDeclaration()) {
602 continue;
603 }
604
David Neto862b7d82018-06-14 18:48:37 -0400605 GenerateDescriptorMapInfo(DL, F);
606
David Neto22f144c2017-06-12 14:26:21 -0400607 // Generate Function Prologue.
608 GenerateFuncPrologue(F);
609
610 // Generate SPIRV instructions for function body.
611 GenerateFuncBody(F);
612
613 // Generate Function Epilogue.
614 GenerateFuncEpilogue();
615 }
616
617 HandleDeferredInstruction();
David Neto1a1a0582017-07-07 12:01:44 -0400618 HandleDeferredDecorations(DL);
David Neto22f144c2017-06-12 14:26:21 -0400619
620 // Generate SPIRV module information.
David Neto5c22a252018-03-15 16:07:41 -0400621 GenerateModuleInfo(module);
David Neto22f144c2017-06-12 14:26:21 -0400622
623 if (outputAsm) {
624 WriteSPIRVAssembly();
625 } else {
626 WriteSPIRVBinary();
627 }
628
629 // We need to patch the SPIR-V header to set bound correctly.
630 patchHeader();
David Neto0676e6f2017-07-11 18:47:44 -0400631
632 if (outputCInitList) {
633 bool first = true;
David Neto0676e6f2017-07-11 18:47:44 -0400634 std::ostringstream os;
635
David Neto57fb0b92017-08-04 15:35:09 -0400636 auto emit_word = [&os, &first](uint32_t word) {
David Neto0676e6f2017-07-11 18:47:44 -0400637 if (!first)
David Neto57fb0b92017-08-04 15:35:09 -0400638 os << ",\n";
639 os << word;
David Neto0676e6f2017-07-11 18:47:44 -0400640 first = false;
641 };
642
643 os << "{";
David Neto57fb0b92017-08-04 15:35:09 -0400644 const std::string str(binaryTempOut.str());
645 for (unsigned i = 0; i < str.size(); i += 4) {
646 const uint32_t a = static_cast<unsigned char>(str[i]);
647 const uint32_t b = static_cast<unsigned char>(str[i + 1]);
648 const uint32_t c = static_cast<unsigned char>(str[i + 2]);
649 const uint32_t d = static_cast<unsigned char>(str[i + 3]);
650 emit_word(a | (b << 8) | (c << 16) | (d << 24));
David Neto0676e6f2017-07-11 18:47:44 -0400651 }
652 os << "}\n";
653 out << os.str();
654 }
655
David Neto22f144c2017-06-12 14:26:21 -0400656 return false;
657}
658
659void SPIRVProducerPass::outputHeader() {
660 if (outputAsm) {
661 // for ASM output the header goes into 5 comments at the beginning of the
662 // file
663 out << "; SPIR-V\n";
664
665 // the major version number is in the 2nd highest byte
666 const uint32_t major = (spv::Version >> 16) & 0xFF;
667
668 // the minor version number is in the 2nd lowest byte
669 const uint32_t minor = (spv::Version >> 8) & 0xFF;
670 out << "; Version: " << major << "." << minor << "\n";
671
672 // use Codeplay's vendor ID
673 out << "; Generator: Codeplay; 0\n";
674
675 out << "; Bound: ";
676
677 // we record where we need to come back to and patch in the bound value
678 patchBoundOffset = out.tell();
679
680 // output one space per digit for the max size of a 32 bit unsigned integer
681 // (which is the maximum ID we could possibly be using)
682 for (uint32_t i = std::numeric_limits<uint32_t>::max(); 0 != i; i /= 10) {
683 out << " ";
684 }
685
686 out << "\n";
687
688 out << "; Schema: 0\n";
689 } else {
David Neto0676e6f2017-07-11 18:47:44 -0400690 binaryOut->write(reinterpret_cast<const char *>(&spv::MagicNumber),
David Neto22f144c2017-06-12 14:26:21 -0400691 sizeof(spv::MagicNumber));
David Neto0676e6f2017-07-11 18:47:44 -0400692 binaryOut->write(reinterpret_cast<const char *>(&spv::Version),
David Neto22f144c2017-06-12 14:26:21 -0400693 sizeof(spv::Version));
694
695 // use Codeplay's vendor ID
696 const uint32_t vendor = 3 << 16;
David Neto0676e6f2017-07-11 18:47:44 -0400697 binaryOut->write(reinterpret_cast<const char *>(&vendor), sizeof(vendor));
David Neto22f144c2017-06-12 14:26:21 -0400698
699 // we record where we need to come back to and patch in the bound value
David Neto0676e6f2017-07-11 18:47:44 -0400700 patchBoundOffset = binaryOut->tell();
David Neto22f144c2017-06-12 14:26:21 -0400701
702 // output a bad bound for now
David Neto0676e6f2017-07-11 18:47:44 -0400703 binaryOut->write(reinterpret_cast<const char *>(&nextID), sizeof(nextID));
David Neto22f144c2017-06-12 14:26:21 -0400704
705 // output the schema (reserved for use and must be 0)
706 const uint32_t schema = 0;
David Neto0676e6f2017-07-11 18:47:44 -0400707 binaryOut->write(reinterpret_cast<const char *>(&schema), sizeof(schema));
David Neto22f144c2017-06-12 14:26:21 -0400708 }
709}
710
711void SPIRVProducerPass::patchHeader() {
712 if (outputAsm) {
713 // get the string representation of the max bound used (nextID will be the
714 // max ID used)
715 auto asString = std::to_string(nextID);
716 out.pwrite(asString.c_str(), asString.size(), patchBoundOffset);
717 } else {
718 // for a binary we just write the value of nextID over bound
David Neto0676e6f2017-07-11 18:47:44 -0400719 binaryOut->pwrite(reinterpret_cast<char *>(&nextID), sizeof(nextID),
720 patchBoundOffset);
David Neto22f144c2017-06-12 14:26:21 -0400721 }
722}
723
David Netoc6f3ab22018-04-06 18:02:31 -0400724void SPIRVProducerPass::GenerateLLVMIRInfo(Module &M, const DataLayout &DL) {
David Neto22f144c2017-06-12 14:26:21 -0400725 // This function generates LLVM IR for function such as global variable for
726 // argument, constant and pointer type for argument access. These information
727 // is artificial one because we need Vulkan SPIR-V output. This function is
728 // executed ahead of FindType and FindConstant.
David Neto22f144c2017-06-12 14:26:21 -0400729 LLVMContext &Context = M.getContext();
730
David Neto862b7d82018-06-14 18:48:37 -0400731 FindGlobalConstVars(M, DL);
David Neto5c22a252018-03-15 16:07:41 -0400732
David Neto862b7d82018-06-14 18:48:37 -0400733 FindResourceVars(M, DL);
David Neto22f144c2017-06-12 14:26:21 -0400734
735 bool HasWorkGroupBuiltin = false;
736 for (GlobalVariable &GV : M.globals()) {
737 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
738 if (spv::BuiltInWorkgroupSize == BuiltinType) {
739 HasWorkGroupBuiltin = true;
740 }
741 }
742
David Neto862b7d82018-06-14 18:48:37 -0400743 FindTypesForSamplerMap(M);
744 FindTypesForResourceVars(M);
Alan Baker202c8c72018-08-13 13:47:44 -0400745 FindWorkgroupVars(M);
David Neto22f144c2017-06-12 14:26:21 -0400746
David Neto862b7d82018-06-14 18:48:37 -0400747 // TODO(dneto): Delete the next 3 vars.
748
749 //#error "remove arg handling from this code"
David Neto26aaf622017-10-23 18:11:53 -0400750 // Map kernel functions to their ordinal number in the compilation unit.
751 UniqueVector<Function*> KernelOrdinal;
752
753 // Map the global variables created for kernel args to their creation
754 // order.
755 UniqueVector<GlobalVariable*> KernelArgVarOrdinal;
756
David Neto862b7d82018-06-14 18:48:37 -0400757 // For each kernel argument type, record the kernel arg global resource
758 // variables generated for that type, the function in which that variable
759 // was most recently used, and the binding number it took. For
760 // reproducibility, we track things by ordinal number (rather than pointer),
761 // and we use a std::set rather than DenseSet since std::set maintains an
762 // ordering. Each tuple is the ordinals of the kernel function, the binding
763 // number, and the ordinal of the kernal-arg-var.
David Neto26aaf622017-10-23 18:11:53 -0400764 //
765 // This table lets us reuse module-scope StorageBuffer variables between
766 // different kernels.
767 DenseMap<Type *, std::set<std::tuple<unsigned, unsigned, unsigned>>>
768 GVarsForType;
769
David Neto862b7d82018-06-14 18:48:37 -0400770 // These function calls need a <2 x i32> as an intermediate result but not
771 // the final result.
772 std::unordered_set<std::string> NeedsIVec2{
773 "_Z15get_image_width14ocl_image2d_ro",
774 "_Z15get_image_width14ocl_image2d_wo",
775 "_Z16get_image_height14ocl_image2d_ro",
776 "_Z16get_image_height14ocl_image2d_wo",
777 };
778
David Neto22f144c2017-06-12 14:26:21 -0400779 for (Function &F : M) {
780 // Handle kernel function first.
781 if (F.isDeclaration() || F.getCallingConv() != CallingConv::SPIR_KERNEL) {
782 continue;
783 }
David Neto26aaf622017-10-23 18:11:53 -0400784 KernelOrdinal.insert(&F);
David Neto22f144c2017-06-12 14:26:21 -0400785
786 for (BasicBlock &BB : F) {
787 for (Instruction &I : BB) {
788 if (I.getOpcode() == Instruction::ZExt ||
789 I.getOpcode() == Instruction::SExt ||
790 I.getOpcode() == Instruction::UIToFP) {
791 // If there is zext with i1 type, it will be changed to OpSelect. The
792 // OpSelect needs constant 0 and 1 so the constants are added here.
793
794 auto OpTy = I.getOperand(0)->getType();
795
796 if (OpTy->isIntegerTy(1) ||
797 (OpTy->isVectorTy() &&
798 OpTy->getVectorElementType()->isIntegerTy(1))) {
799 if (I.getOpcode() == Instruction::ZExt) {
800 APInt One(32, 1);
801 FindConstant(Constant::getNullValue(I.getType()));
802 FindConstant(Constant::getIntegerValue(I.getType(), One));
803 } else if (I.getOpcode() == Instruction::SExt) {
804 APInt MinusOne(32, UINT64_MAX, true);
805 FindConstant(Constant::getNullValue(I.getType()));
806 FindConstant(Constant::getIntegerValue(I.getType(), MinusOne));
807 } else {
808 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
809 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
810 }
811 }
812 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
David Neto862b7d82018-06-14 18:48:37 -0400813 StringRef callee_name = Call->getCalledFunction()->getName();
David Neto22f144c2017-06-12 14:26:21 -0400814
815 // Handle image type specially.
David Neto862b7d82018-06-14 18:48:37 -0400816 if (callee_name.equals(
David Neto22f144c2017-06-12 14:26:21 -0400817 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
David Neto862b7d82018-06-14 18:48:37 -0400818 callee_name.equals(
David Neto22f144c2017-06-12 14:26:21 -0400819 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
820 TypeMapType &OpImageTypeMap = getImageTypeMap();
821 Type *ImageTy =
822 Call->getArgOperand(0)->getType()->getPointerElementType();
823 OpImageTypeMap[ImageTy] = 0;
824
825 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
826 }
David Neto5c22a252018-03-15 16:07:41 -0400827
David Neto862b7d82018-06-14 18:48:37 -0400828 if (NeedsIVec2.find(callee_name) != NeedsIVec2.end()) {
David Neto5c22a252018-03-15 16:07:41 -0400829 FindType(VectorType::get(Type::getInt32Ty(Context), 2));
830 }
David Neto22f144c2017-06-12 14:26:21 -0400831 }
832 }
833 }
834
David Neto22f144c2017-06-12 14:26:21 -0400835 if (const MDNode *MD =
836 dyn_cast<Function>(&F)->getMetadata("reqd_work_group_size")) {
837 // We generate constants if the WorkgroupSize builtin is being used.
838 if (HasWorkGroupBuiltin) {
839 // Collect constant information for work group size.
840 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(0)));
841 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(1)));
842 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(2)));
843 }
844 }
845
David Neto22f144c2017-06-12 14:26:21 -0400846 // Collect types' information from function.
847 FindTypePerFunc(F);
848
849 // Collect constant information from function.
850 FindConstantPerFunc(F);
851 }
852
853 for (Function &F : M) {
854 // Handle non-kernel functions.
855 if (F.isDeclaration() || F.getCallingConv() == CallingConv::SPIR_KERNEL) {
856 continue;
857 }
858
859 for (BasicBlock &BB : F) {
860 for (Instruction &I : BB) {
861 if (I.getOpcode() == Instruction::ZExt ||
862 I.getOpcode() == Instruction::SExt ||
863 I.getOpcode() == Instruction::UIToFP) {
864 // If there is zext with i1 type, it will be changed to OpSelect. The
865 // OpSelect needs constant 0 and 1 so the constants are added here.
866
867 auto OpTy = I.getOperand(0)->getType();
868
869 if (OpTy->isIntegerTy(1) ||
870 (OpTy->isVectorTy() &&
871 OpTy->getVectorElementType()->isIntegerTy(1))) {
872 if (I.getOpcode() == Instruction::ZExt) {
873 APInt One(32, 1);
874 FindConstant(Constant::getNullValue(I.getType()));
875 FindConstant(Constant::getIntegerValue(I.getType(), One));
876 } else if (I.getOpcode() == Instruction::SExt) {
877 APInt MinusOne(32, UINT64_MAX, true);
878 FindConstant(Constant::getNullValue(I.getType()));
879 FindConstant(Constant::getIntegerValue(I.getType(), MinusOne));
880 } else {
881 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
882 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
883 }
884 }
885 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
886 Function *Callee = Call->getCalledFunction();
887
888 // Handle image type specially.
889 if (Callee->getName().equals(
890 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
891 Callee->getName().equals(
892 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
893 TypeMapType &OpImageTypeMap = getImageTypeMap();
894 Type *ImageTy =
895 Call->getArgOperand(0)->getType()->getPointerElementType();
896 OpImageTypeMap[ImageTy] = 0;
897
898 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
899 }
900 }
901 }
902 }
903
904 if (M.getTypeByName("opencl.image2d_ro_t") ||
905 M.getTypeByName("opencl.image2d_wo_t") ||
906 M.getTypeByName("opencl.image3d_ro_t") ||
907 M.getTypeByName("opencl.image3d_wo_t")) {
908 // Assume Image type's sampled type is float type.
909 FindType(Type::getFloatTy(Context));
910 }
911
912 // Collect types' information from function.
913 FindTypePerFunc(F);
914
915 // Collect constant information from function.
916 FindConstantPerFunc(F);
917 }
918}
919
David Neto862b7d82018-06-14 18:48:37 -0400920void SPIRVProducerPass::FindGlobalConstVars(Module &M, const DataLayout &DL) {
921 SmallVector<GlobalVariable *, 8> GVList;
922 SmallVector<GlobalVariable *, 8> DeadGVList;
923 for (GlobalVariable &GV : M.globals()) {
924 if (GV.getType()->getAddressSpace() == AddressSpace::Constant) {
925 if (GV.use_empty()) {
926 DeadGVList.push_back(&GV);
927 } else {
928 GVList.push_back(&GV);
929 }
930 }
931 }
932
933 // Remove dead global __constant variables.
934 for (auto GV : DeadGVList) {
935 GV->eraseFromParent();
936 }
937 DeadGVList.clear();
938
939 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
940 // For now, we only support a single storage buffer.
941 if (GVList.size() > 0) {
942 assert(GVList.size() == 1);
943 const auto *GV = GVList[0];
944 const auto constants_byte_size =
945 (DL.getTypeSizeInBits(GV->getInitializer()->getType())) / 8;
946 const size_t kConstantMaxSize = 65536;
947 if (constants_byte_size > kConstantMaxSize) {
948 outs() << "Max __constant capacity of " << kConstantMaxSize
949 << " bytes exceeded: " << constants_byte_size << " bytes used\n";
950 llvm_unreachable("Max __constant capacity exceeded");
951 }
952 }
953 } else {
954 // Change global constant variable's address space to ModuleScopePrivate.
955 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
956 for (auto GV : GVList) {
957 // Create new gv with ModuleScopePrivate address space.
958 Type *NewGVTy = GV->getType()->getPointerElementType();
959 GlobalVariable *NewGV = new GlobalVariable(
960 M, NewGVTy, false, GV->getLinkage(), GV->getInitializer(), "",
961 nullptr, GV->getThreadLocalMode(), AddressSpace::ModuleScopePrivate);
962 NewGV->takeName(GV);
963
964 const SmallVector<User *, 8> GVUsers(GV->user_begin(), GV->user_end());
965 SmallVector<User *, 8> CandidateUsers;
966
967 auto record_called_function_type_as_user =
968 [&GlobalConstFuncTyMap](Value *gv, CallInst *call) {
969 // Find argument index.
970 unsigned index = 0;
971 for (unsigned i = 0; i < call->getNumArgOperands(); i++) {
972 if (gv == call->getOperand(i)) {
973 // TODO(dneto): Should we break here?
974 index = i;
975 }
976 }
977
978 // Record function type with global constant.
979 GlobalConstFuncTyMap[call->getFunctionType()] =
980 std::make_pair(call->getFunctionType(), index);
981 };
982
983 for (User *GVU : GVUsers) {
984 if (CallInst *Call = dyn_cast<CallInst>(GVU)) {
985 record_called_function_type_as_user(GV, Call);
986 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(GVU)) {
987 // Check GEP users.
988 for (User *GEPU : GEP->users()) {
989 if (CallInst *GEPCall = dyn_cast<CallInst>(GEPU)) {
990 record_called_function_type_as_user(GEP, GEPCall);
991 }
992 }
993 }
994
995 CandidateUsers.push_back(GVU);
996 }
997
998 for (User *U : CandidateUsers) {
999 // Update users of gv with new gv.
1000 U->replaceUsesOfWith(GV, NewGV);
1001 }
1002
1003 // Delete original gv.
1004 GV->eraseFromParent();
1005 }
1006 }
1007}
1008
1009void SPIRVProducerPass::FindResourceVars(Module &M, const DataLayout &DL) {
1010 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1011 ValueMapType &VMap = getValueMap();
1012
1013 ResourceVarInfoList.clear();
1014 FunctionToResourceVarsMap.clear();
1015 ModuleOrderedResourceVars.reset();
1016 // Normally, there is one resource variable per clspv.resource.var.*
1017 // function, since that is unique'd by arg type and index. By design,
1018 // we can share these resource variables across kernels because all
1019 // kernels use the same descriptor set.
1020 //
1021 // But if the user requested distinct descriptor sets per kernel, then
1022 // the descriptor allocator has made different (set,binding) pairs for
1023 // the same (type,arg_index) pair. Since we can decorate a resource
1024 // variable with only exactly one DescriptorSet and Binding, we are
1025 // forced in this case to make distinct resource variables whenever
1026 // the same clspv.reource.var.X function is seen with disintct
1027 // (set,binding) values.
1028 const bool always_distinct_sets =
1029 clspv::Option::DistinctKernelDescriptorSets();
1030 for (Function &F : M) {
1031 // Rely on the fact the resource var functions have a stable ordering
1032 // in the module.
Alan Baker202c8c72018-08-13 13:47:44 -04001033 if (F.getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001034 // Find all calls to this function with distinct set and binding pairs.
1035 // Save them in ResourceVarInfoList.
1036
1037 // Determine uniqueness of the (set,binding) pairs only withing this
1038 // one resource-var builtin function.
1039 using SetAndBinding = std::pair<unsigned, unsigned>;
1040 // Maps set and binding to the resource var info.
1041 DenseMap<SetAndBinding, ResourceVarInfo *> set_and_binding_map;
1042 bool first_use = true;
1043 for (auto &U : F.uses()) {
1044 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
1045 const auto set = unsigned(
1046 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
1047 const auto binding = unsigned(
1048 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
1049 const auto arg_kind = clspv::ArgKind(
1050 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
1051 const auto arg_index = unsigned(
1052 dyn_cast<ConstantInt>(call->getArgOperand(3))->getZExtValue());
1053
1054 // Find or make the resource var info for this combination.
1055 ResourceVarInfo *rv = nullptr;
1056 if (always_distinct_sets) {
1057 // Make a new resource var any time we see a different
1058 // (set,binding) pair.
1059 SetAndBinding key{set, binding};
1060 auto where = set_and_binding_map.find(key);
1061 if (where == set_and_binding_map.end()) {
1062 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
1063 binding, &F, arg_kind);
1064 ResourceVarInfoList.emplace_back(rv);
1065 set_and_binding_map[key] = rv;
1066 } else {
1067 rv = where->second;
1068 }
1069 } else {
1070 // The default is to make exactly one resource for each
1071 // clspv.resource.var.* function.
1072 if (first_use) {
1073 first_use = false;
1074 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
1075 binding, &F, arg_kind);
1076 ResourceVarInfoList.emplace_back(rv);
1077 } else {
1078 rv = ResourceVarInfoList.back().get();
1079 }
1080 }
1081
1082 // Now populate FunctionToResourceVarsMap.
1083 auto &mapping =
1084 FunctionToResourceVarsMap[call->getParent()->getParent()];
1085 while (mapping.size() <= arg_index) {
1086 mapping.push_back(nullptr);
1087 }
1088 mapping[arg_index] = rv;
1089 }
1090 }
1091 }
1092 }
1093
1094 // Populate ModuleOrderedResourceVars.
1095 for (Function &F : M) {
1096 auto where = FunctionToResourceVarsMap.find(&F);
1097 if (where != FunctionToResourceVarsMap.end()) {
1098 for (auto &rv : where->second) {
1099 if (rv != nullptr) {
1100 ModuleOrderedResourceVars.insert(rv);
1101 }
1102 }
1103 }
1104 }
1105 if (ShowResourceVars) {
1106 for (auto *info : ModuleOrderedResourceVars) {
1107 outs() << "MORV index " << info->index << " (" << info->descriptor_set
1108 << "," << info->binding << ") " << *(info->var_fn->getReturnType())
1109 << "\n";
1110 }
1111 }
1112}
1113
David Neto22f144c2017-06-12 14:26:21 -04001114bool SPIRVProducerPass::FindExtInst(Module &M) {
1115 LLVMContext &Context = M.getContext();
1116 bool HasExtInst = false;
1117
1118 for (Function &F : M) {
1119 for (BasicBlock &BB : F) {
1120 for (Instruction &I : BB) {
1121 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1122 Function *Callee = Call->getCalledFunction();
1123 // Check whether this call is for extend instructions.
David Neto3fbb4072017-10-16 11:28:14 -04001124 auto callee_name = Callee->getName();
1125 const glsl::ExtInst EInst = getExtInstEnum(callee_name);
1126 const glsl::ExtInst IndirectEInst =
1127 getIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04001128
David Neto3fbb4072017-10-16 11:28:14 -04001129 HasExtInst |=
1130 (EInst != kGlslExtInstBad) || (IndirectEInst != kGlslExtInstBad);
1131
1132 if (IndirectEInst) {
1133 // Register extra constants if needed.
1134
1135 // Registers a type and constant for computing the result of the
1136 // given instruction. If the result of the instruction is a vector,
1137 // then make a splat vector constant with the same number of
1138 // elements.
1139 auto register_constant = [this, &I](Constant *constant) {
1140 FindType(constant->getType());
1141 FindConstant(constant);
1142 if (auto *vectorTy = dyn_cast<VectorType>(I.getType())) {
1143 // Register the splat vector of the value with the same
1144 // width as the result of the instruction.
1145 auto *vec_constant = ConstantVector::getSplat(
1146 static_cast<unsigned>(vectorTy->getNumElements()),
1147 constant);
1148 FindConstant(vec_constant);
1149 FindType(vec_constant->getType());
1150 }
1151 };
1152 switch (IndirectEInst) {
1153 case glsl::ExtInstFindUMsb:
1154 // clz needs OpExtInst and OpISub with constant 31, or splat
1155 // vector of 31. Add it to the constant list here.
1156 register_constant(
1157 ConstantInt::get(Type::getInt32Ty(Context), 31));
1158 break;
1159 case glsl::ExtInstAcos:
1160 case glsl::ExtInstAsin:
1161 case glsl::ExtInstAtan2:
1162 // We need 1/pi for acospi, asinpi, atan2pi.
1163 register_constant(
1164 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
1165 break;
1166 default:
1167 assert(false && "internally inconsistent");
1168 }
David Neto22f144c2017-06-12 14:26:21 -04001169 }
1170 }
1171 }
1172 }
1173 }
1174
1175 return HasExtInst;
1176}
1177
1178void SPIRVProducerPass::FindTypePerGlobalVar(GlobalVariable &GV) {
1179 // Investigate global variable's type.
1180 FindType(GV.getType());
1181}
1182
1183void SPIRVProducerPass::FindTypePerFunc(Function &F) {
1184 // Investigate function's type.
1185 FunctionType *FTy = F.getFunctionType();
1186
1187 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
1188 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
David Neto9ed8e2f2018-03-24 06:47:24 -07001189 // Handle a regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04001190 if (GlobalConstFuncTyMap.count(FTy)) {
1191 uint32_t GVCstArgIdx = GlobalConstFuncTypeMap[FTy].second;
1192 SmallVector<Type *, 4> NewFuncParamTys;
1193 for (unsigned i = 0; i < FTy->getNumParams(); i++) {
1194 Type *ParamTy = FTy->getParamType(i);
1195 if (i == GVCstArgIdx) {
1196 Type *EleTy = ParamTy->getPointerElementType();
1197 ParamTy = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1198 }
1199
1200 NewFuncParamTys.push_back(ParamTy);
1201 }
1202
1203 FunctionType *NewFTy =
1204 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1205 GlobalConstFuncTyMap[FTy] = std::make_pair(NewFTy, GVCstArgIdx);
1206 FTy = NewFTy;
1207 }
1208
1209 FindType(FTy);
1210 } else {
1211 // As kernel functions do not have parameters, create new function type and
1212 // add it to type map.
1213 SmallVector<Type *, 4> NewFuncParamTys;
1214 FunctionType *NewFTy =
1215 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1216 FindType(NewFTy);
1217 }
1218
1219 // Investigate instructions' type in function body.
1220 for (BasicBlock &BB : F) {
1221 for (Instruction &I : BB) {
1222 if (isa<ShuffleVectorInst>(I)) {
1223 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1224 // Ignore type for mask of shuffle vector instruction.
1225 if (i == 2) {
1226 continue;
1227 }
1228
1229 Value *Op = I.getOperand(i);
1230 if (!isa<MetadataAsValue>(Op)) {
1231 FindType(Op->getType());
1232 }
1233 }
1234
1235 FindType(I.getType());
1236 continue;
1237 }
1238
David Neto862b7d82018-06-14 18:48:37 -04001239 CallInst *Call = dyn_cast<CallInst>(&I);
1240
1241 if (Call && Call->getCalledFunction()->getName().startswith(
Alan Baker202c8c72018-08-13 13:47:44 -04001242 clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001243 // This is a fake call representing access to a resource variable.
1244 // We handle that elsewhere.
1245 continue;
1246 }
1247
Alan Baker202c8c72018-08-13 13:47:44 -04001248 if (Call && Call->getCalledFunction()->getName().startswith(
1249 clspv::WorkgroupAccessorFunction())) {
1250 // This is a fake call representing access to a workgroup variable.
1251 // We handle that elsewhere.
1252 continue;
1253 }
1254
David Neto22f144c2017-06-12 14:26:21 -04001255 // Work through the operands of the instruction.
1256 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1257 Value *const Op = I.getOperand(i);
1258 // If any of the operands is a constant, find the type!
1259 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1260 FindType(Op->getType());
1261 }
1262 }
1263
1264 for (Use &Op : I.operands()) {
1265 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1266 // Avoid to check call instruction's type.
1267 break;
1268 }
Alan Baker202c8c72018-08-13 13:47:44 -04001269 if (CallInst *OpCall = dyn_cast<CallInst>(Op)) {
1270 if (OpCall && OpCall->getCalledFunction()->getName().startswith(
1271 clspv::WorkgroupAccessorFunction())) {
1272 // This is a fake call representing access to a workgroup variable.
1273 // We handle that elsewhere.
1274 continue;
1275 }
1276 }
David Neto22f144c2017-06-12 14:26:21 -04001277 if (!isa<MetadataAsValue>(&Op)) {
1278 FindType(Op->getType());
1279 continue;
1280 }
1281 }
1282
David Neto22f144c2017-06-12 14:26:21 -04001283 // We don't want to track the type of this call as we are going to replace
1284 // it.
David Neto862b7d82018-06-14 18:48:37 -04001285 if (Call && ("clspv.sampler.var.literal" ==
David Neto22f144c2017-06-12 14:26:21 -04001286 Call->getCalledFunction()->getName())) {
1287 continue;
1288 }
1289
1290 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1291 // If gep's base operand has ModuleScopePrivate address space, make gep
1292 // return ModuleScopePrivate address space.
1293 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate) {
1294 // Add pointer type with private address space for global constant to
1295 // type list.
1296 Type *EleTy = I.getType()->getPointerElementType();
1297 Type *NewPTy =
1298 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1299
1300 FindType(NewPTy);
1301 continue;
1302 }
1303 }
1304
1305 FindType(I.getType());
1306 }
1307 }
1308}
1309
David Neto862b7d82018-06-14 18:48:37 -04001310void SPIRVProducerPass::FindTypesForSamplerMap(Module &M) {
1311 // If we are using a sampler map, find the type of the sampler.
1312 if (M.getFunction("clspv.sampler.var.literal") ||
1313 0 < getSamplerMap().size()) {
1314 auto SamplerStructTy = M.getTypeByName("opencl.sampler_t");
1315 if (!SamplerStructTy) {
1316 SamplerStructTy = StructType::create(M.getContext(), "opencl.sampler_t");
1317 }
1318
1319 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
1320
1321 FindType(SamplerTy);
1322 }
1323}
1324
1325void SPIRVProducerPass::FindTypesForResourceVars(Module &M) {
1326 // Record types so they are generated.
1327 TypesNeedingLayout.reset();
1328 StructTypesNeedingBlock.reset();
1329
1330 // To match older clspv codegen, generate the float type first if required
1331 // for images.
1332 for (const auto *info : ModuleOrderedResourceVars) {
1333 if (info->arg_kind == clspv::ArgKind::ReadOnlyImage ||
1334 info->arg_kind == clspv::ArgKind::WriteOnlyImage) {
1335 // We need "float" for the sampled component type.
1336 FindType(Type::getFloatTy(M.getContext()));
1337 // We only need to find it once.
1338 break;
1339 }
1340 }
1341
1342 for (const auto *info : ModuleOrderedResourceVars) {
1343 Type *type = info->var_fn->getReturnType();
1344
1345 switch (info->arg_kind) {
1346 case clspv::ArgKind::Buffer:
1347 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1348 StructTypesNeedingBlock.insert(sty);
1349 } else {
1350 errs() << *type << "\n";
1351 llvm_unreachable("Buffer arguments must map to structures!");
1352 }
1353 break;
1354 case clspv::ArgKind::Pod:
1355 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1356 StructTypesNeedingBlock.insert(sty);
1357 } else {
1358 errs() << *type << "\n";
1359 llvm_unreachable("POD arguments must map to structures!");
1360 }
1361 break;
1362 case clspv::ArgKind::ReadOnlyImage:
1363 case clspv::ArgKind::WriteOnlyImage:
1364 case clspv::ArgKind::Sampler:
1365 // Sampler and image types map to the pointee type but
1366 // in the uniform constant address space.
1367 type = PointerType::get(type->getPointerElementType(),
1368 clspv::AddressSpace::UniformConstant);
1369 break;
1370 default:
1371 break;
1372 }
1373
1374 // The converted type is the type of the OpVariable we will generate.
1375 // If the pointee type is an array of size zero, FindType will convert it
1376 // to a runtime array.
1377 FindType(type);
1378 }
1379
1380 // Traverse the arrays and structures underneath each Block, and
1381 // mark them as needing layout.
1382 std::vector<Type *> work_list(StructTypesNeedingBlock.begin(),
1383 StructTypesNeedingBlock.end());
1384 while (!work_list.empty()) {
1385 Type *type = work_list.back();
1386 work_list.pop_back();
1387 TypesNeedingLayout.insert(type);
1388 switch (type->getTypeID()) {
1389 case Type::ArrayTyID:
1390 work_list.push_back(type->getArrayElementType());
1391 if (!Hack_generate_runtime_array_stride_early) {
1392 // Remember this array type for deferred decoration.
1393 TypesNeedingArrayStride.insert(type);
1394 }
1395 break;
1396 case Type::StructTyID:
1397 for (auto *elem_ty : cast<StructType>(type)->elements()) {
1398 work_list.push_back(elem_ty);
1399 }
1400 default:
1401 // This type and its contained types don't get layout.
1402 break;
1403 }
1404 }
1405}
1406
Alan Baker202c8c72018-08-13 13:47:44 -04001407void SPIRVProducerPass::FindWorkgroupVars(Module &M) {
1408 // The SpecId assignment for pointer-to-local arguments is recorded in
1409 // module-level metadata. Translate that information into local argument
1410 // information.
1411 NamedMDNode *nmd = M.getNamedMetadata(clspv::LocalSpecIdMetadataName());
1412 if (!nmd) return;
1413 for (auto operand : nmd->operands()) {
1414 MDTuple *tuple = cast<MDTuple>(operand);
1415 ValueAsMetadata *fn_md = cast<ValueAsMetadata>(tuple->getOperand(0));
1416 Function *func = cast<Function>(fn_md->getValue());
1417 ConstantAsMetadata *arg_index_md = cast<ConstantAsMetadata>(tuple->getOperand(1));
1418 int arg_index = cast<ConstantInt>(arg_index_md->getValue())->getSExtValue();
1419 Argument* arg = &*(func->arg_begin() + arg_index);
1420
1421 ConstantAsMetadata *spec_id_md =
1422 cast<ConstantAsMetadata>(tuple->getOperand(2));
1423 int spec_id = cast<ConstantInt>(spec_id_md->getValue())->getSExtValue();
1424
1425 max_local_spec_id_ = std::max(max_local_spec_id_, spec_id + 1);
1426 LocalArgSpecIds[arg] = spec_id;
1427 if (LocalSpecIdInfoMap.count(spec_id)) continue;
1428
1429 // We haven't seen this SpecId yet, so generate the LocalArgInfo for it.
1430 LocalArgInfo info{nextID, arg->getType()->getPointerElementType(),
1431 nextID + 1, nextID + 2,
1432 nextID + 3, spec_id};
1433 LocalSpecIdInfoMap[spec_id] = info;
1434 nextID += 4;
1435
1436 // Ensure the types necessary for this argument get generated.
1437 Type *IdxTy = Type::getInt32Ty(M.getContext());
1438 FindConstant(ConstantInt::get(IdxTy, 0));
1439 FindType(IdxTy);
1440 FindType(arg->getType());
1441 }
1442}
1443
David Neto22f144c2017-06-12 14:26:21 -04001444void SPIRVProducerPass::FindType(Type *Ty) {
1445 TypeList &TyList = getTypeList();
1446
1447 if (0 != TyList.idFor(Ty)) {
1448 return;
1449 }
1450
1451 if (Ty->isPointerTy()) {
1452 auto AddrSpace = Ty->getPointerAddressSpace();
1453 if ((AddressSpace::Constant == AddrSpace) ||
1454 (AddressSpace::Global == AddrSpace)) {
1455 auto PointeeTy = Ty->getPointerElementType();
1456
1457 if (PointeeTy->isStructTy() &&
1458 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1459 FindType(PointeeTy);
1460 auto ActualPointerTy =
1461 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1462 FindType(ActualPointerTy);
1463 return;
1464 }
1465 }
1466 }
1467
David Neto862b7d82018-06-14 18:48:37 -04001468 // By convention, LLVM array type with 0 elements will map to
1469 // OpTypeRuntimeArray. Otherwise, it will map to OpTypeArray, which
1470 // has a constant number of elements. We need to support type of the
1471 // constant.
1472 if (auto *arrayTy = dyn_cast<ArrayType>(Ty)) {
1473 if (arrayTy->getNumElements() > 0) {
1474 LLVMContext &Context = Ty->getContext();
1475 FindType(Type::getInt32Ty(Context));
1476 }
David Neto22f144c2017-06-12 14:26:21 -04001477 }
1478
1479 for (Type *SubTy : Ty->subtypes()) {
1480 FindType(SubTy);
1481 }
1482
1483 TyList.insert(Ty);
1484}
1485
1486void SPIRVProducerPass::FindConstantPerGlobalVar(GlobalVariable &GV) {
1487 // If the global variable has a (non undef) initializer.
1488 if (GV.hasInitializer() && !isa<UndefValue>(GV.getInitializer())) {
David Neto862b7d82018-06-14 18:48:37 -04001489 // Generate the constant if it's not the initializer to a module scope
1490 // constant that we will expect in a storage buffer.
1491 const bool module_scope_constant_external_init =
1492 (GV.getType()->getPointerAddressSpace() == AddressSpace::Constant) &&
1493 clspv::Option::ModuleConstantsInStorageBuffer();
1494 if (!module_scope_constant_external_init) {
1495 FindConstant(GV.getInitializer());
1496 }
David Neto22f144c2017-06-12 14:26:21 -04001497 }
1498}
1499
1500void SPIRVProducerPass::FindConstantPerFunc(Function &F) {
1501 // Investigate constants in function body.
1502 for (BasicBlock &BB : F) {
1503 for (Instruction &I : BB) {
David Neto862b7d82018-06-14 18:48:37 -04001504 if (auto *call = dyn_cast<CallInst>(&I)) {
1505 auto name = call->getCalledFunction()->getName();
1506 if (name == "clspv.sampler.var.literal") {
1507 // We've handled these constants elsewhere, so skip it.
1508 continue;
1509 }
Alan Baker202c8c72018-08-13 13:47:44 -04001510 if (name.startswith(clspv::ResourceAccessorFunction())) {
1511 continue;
1512 }
1513 if (name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001514 continue;
1515 }
David Neto22f144c2017-06-12 14:26:21 -04001516 }
1517
1518 if (isa<AllocaInst>(I)) {
1519 // Alloca instruction has constant for the number of element. Ignore it.
1520 continue;
1521 } else if (isa<ShuffleVectorInst>(I)) {
1522 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1523 // Ignore constant for mask of shuffle vector instruction.
1524 if (i == 2) {
1525 continue;
1526 }
1527
1528 if (isa<Constant>(I.getOperand(i)) &&
1529 !isa<GlobalValue>(I.getOperand(i))) {
1530 FindConstant(I.getOperand(i));
1531 }
1532 }
1533
1534 continue;
1535 } else if (isa<InsertElementInst>(I)) {
1536 // Handle InsertElement with <4 x i8> specially.
1537 Type *CompositeTy = I.getOperand(0)->getType();
1538 if (is4xi8vec(CompositeTy)) {
1539 LLVMContext &Context = CompositeTy->getContext();
1540 if (isa<Constant>(I.getOperand(0))) {
1541 FindConstant(I.getOperand(0));
1542 }
1543
1544 if (isa<Constant>(I.getOperand(1))) {
1545 FindConstant(I.getOperand(1));
1546 }
1547
1548 // Add mask constant 0xFF.
1549 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1550 FindConstant(CstFF);
1551
1552 // Add shift amount constant.
1553 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
1554 uint64_t Idx = CI->getZExtValue();
1555 Constant *CstShiftAmount =
1556 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1557 FindConstant(CstShiftAmount);
1558 }
1559
1560 continue;
1561 }
1562
1563 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1564 // Ignore constant for index of InsertElement instruction.
1565 if (i == 2) {
1566 continue;
1567 }
1568
1569 if (isa<Constant>(I.getOperand(i)) &&
1570 !isa<GlobalValue>(I.getOperand(i))) {
1571 FindConstant(I.getOperand(i));
1572 }
1573 }
1574
1575 continue;
1576 } else if (isa<ExtractElementInst>(I)) {
1577 // Handle ExtractElement with <4 x i8> specially.
1578 Type *CompositeTy = I.getOperand(0)->getType();
1579 if (is4xi8vec(CompositeTy)) {
1580 LLVMContext &Context = CompositeTy->getContext();
1581 if (isa<Constant>(I.getOperand(0))) {
1582 FindConstant(I.getOperand(0));
1583 }
1584
1585 // Add mask constant 0xFF.
1586 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1587 FindConstant(CstFF);
1588
1589 // Add shift amount constant.
1590 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1591 uint64_t Idx = CI->getZExtValue();
1592 Constant *CstShiftAmount =
1593 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1594 FindConstant(CstShiftAmount);
1595 } else {
1596 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
1597 FindConstant(Cst8);
1598 }
1599
1600 continue;
1601 }
1602
1603 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1604 // Ignore constant for index of ExtractElement instruction.
1605 if (i == 1) {
1606 continue;
1607 }
1608
1609 if (isa<Constant>(I.getOperand(i)) &&
1610 !isa<GlobalValue>(I.getOperand(i))) {
1611 FindConstant(I.getOperand(i));
1612 }
1613 }
1614
1615 continue;
1616 } else if ((Instruction::Xor == I.getOpcode()) && I.getType()->isIntegerTy(1)) {
1617 // We special case for Xor where the type is i1 and one of the arguments is a constant 1 (true), this is an OpLogicalNot in SPIR-V, and we don't need the constant
1618 bool foundConstantTrue = false;
1619 for (Use &Op : I.operands()) {
1620 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1621 auto CI = cast<ConstantInt>(Op);
1622
1623 if (CI->isZero() || foundConstantTrue) {
1624 // If we already found the true constant, we might (probably only on -O0) have an OpLogicalNot which is taking a constant argument, so discover it anyway.
1625 FindConstant(Op);
1626 } else {
1627 foundConstantTrue = true;
1628 }
1629 }
1630 }
1631
1632 continue;
David Netod2de94a2017-08-28 17:27:47 -04001633 } else if (isa<TruncInst>(I)) {
1634 // For truncation to i8 we mask against 255.
1635 Type *ToTy = I.getType();
1636 if (8u == ToTy->getPrimitiveSizeInBits()) {
1637 LLVMContext &Context = ToTy->getContext();
1638 Constant *Cst255 = ConstantInt::get(Type::getInt32Ty(Context), 0xff);
1639 FindConstant(Cst255);
1640 }
1641 // Fall through.
Neil Henning39672102017-09-29 14:33:13 +01001642 } else if (isa<AtomicRMWInst>(I)) {
1643 LLVMContext &Context = I.getContext();
1644
1645 FindConstant(
1646 ConstantInt::get(Type::getInt32Ty(Context), spv::ScopeDevice));
1647 FindConstant(ConstantInt::get(
1648 Type::getInt32Ty(Context),
1649 spv::MemorySemanticsUniformMemoryMask |
1650 spv::MemorySemanticsSequentiallyConsistentMask));
David Neto22f144c2017-06-12 14:26:21 -04001651 }
1652
1653 for (Use &Op : I.operands()) {
1654 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1655 FindConstant(Op);
1656 }
1657 }
1658 }
1659 }
1660}
1661
1662void SPIRVProducerPass::FindConstant(Value *V) {
David Neto22f144c2017-06-12 14:26:21 -04001663 ValueList &CstList = getConstantList();
1664
David Netofb9a7972017-08-25 17:08:24 -04001665 // If V is already tracked, ignore it.
1666 if (0 != CstList.idFor(V)) {
David Neto22f144c2017-06-12 14:26:21 -04001667 return;
1668 }
1669
David Neto862b7d82018-06-14 18:48:37 -04001670 if (isa<GlobalValue>(V) && clspv::Option::ModuleConstantsInStorageBuffer()) {
1671 return;
1672 }
1673
David Neto22f144c2017-06-12 14:26:21 -04001674 Constant *Cst = cast<Constant>(V);
David Neto862b7d82018-06-14 18:48:37 -04001675 Type *CstTy = Cst->getType();
David Neto22f144c2017-06-12 14:26:21 -04001676
1677 // Handle constant with <4 x i8> type specially.
David Neto22f144c2017-06-12 14:26:21 -04001678 if (is4xi8vec(CstTy)) {
1679 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001680 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001681 }
1682 }
1683
1684 if (Cst->getNumOperands()) {
1685 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end(); I != E;
1686 ++I) {
1687 FindConstant(*I);
1688 }
1689
David Netofb9a7972017-08-25 17:08:24 -04001690 CstList.insert(Cst);
David Neto22f144c2017-06-12 14:26:21 -04001691 return;
1692 } else if (const ConstantDataSequential *CDS =
1693 dyn_cast<ConstantDataSequential>(Cst)) {
1694 // Add constants for each element to constant list.
1695 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
1696 Constant *EleCst = CDS->getElementAsConstant(i);
1697 FindConstant(EleCst);
1698 }
1699 }
1700
1701 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001702 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001703 }
1704}
1705
1706spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1707 switch (AddrSpace) {
1708 default:
1709 llvm_unreachable("Unsupported OpenCL address space");
1710 case AddressSpace::Private:
1711 return spv::StorageClassFunction;
1712 case AddressSpace::Global:
1713 case AddressSpace::Constant:
1714 return spv::StorageClassStorageBuffer;
1715 case AddressSpace::Input:
1716 return spv::StorageClassInput;
1717 case AddressSpace::Local:
1718 return spv::StorageClassWorkgroup;
1719 case AddressSpace::UniformConstant:
1720 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001721 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001722 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001723 case AddressSpace::ModuleScopePrivate:
1724 return spv::StorageClassPrivate;
1725 }
1726}
1727
David Neto862b7d82018-06-14 18:48:37 -04001728spv::StorageClass
1729SPIRVProducerPass::GetStorageClassForArgKind(clspv::ArgKind arg_kind) const {
1730 switch (arg_kind) {
1731 case clspv::ArgKind::Buffer:
1732 return spv::StorageClassStorageBuffer;
1733 case clspv::ArgKind::Pod:
1734 return clspv::Option::PodArgsInUniformBuffer()
1735 ? spv::StorageClassUniform
1736 : spv::StorageClassStorageBuffer;
1737 case clspv::ArgKind::Local:
1738 return spv::StorageClassWorkgroup;
1739 case clspv::ArgKind::ReadOnlyImage:
1740 case clspv::ArgKind::WriteOnlyImage:
1741 case clspv::ArgKind::Sampler:
1742 return spv::StorageClassUniformConstant;
1743 }
1744}
1745
David Neto22f144c2017-06-12 14:26:21 -04001746spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1747 return StringSwitch<spv::BuiltIn>(Name)
1748 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1749 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1750 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1751 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1752 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
1753 .Default(spv::BuiltInMax);
1754}
1755
1756void SPIRVProducerPass::GenerateExtInstImport() {
1757 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1758 uint32_t &ExtInstImportID = getOpExtInstImportID();
1759
1760 //
1761 // Generate OpExtInstImport.
1762 //
1763 // Ops[0] ... Ops[n] = Name (Literal String)
David Neto22f144c2017-06-12 14:26:21 -04001764 ExtInstImportID = nextID;
David Neto87846742018-04-11 17:36:22 -04001765 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpExtInstImport, nextID++,
1766 MkString("GLSL.std.450")));
David Neto22f144c2017-06-12 14:26:21 -04001767}
1768
David Netoc6f3ab22018-04-06 18:02:31 -04001769void SPIRVProducerPass::GenerateSPIRVTypes(LLVMContext& Context, const DataLayout &DL) {
David Neto22f144c2017-06-12 14:26:21 -04001770 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1771 ValueMapType &VMap = getValueMap();
1772 ValueMapType &AllocatedVMap = getAllocatedValueMap();
David Neto22f144c2017-06-12 14:26:21 -04001773
1774 // Map for OpTypeRuntimeArray. If argument has pointer type, 2 spirv type
1775 // instructions are generated. They are OpTypePointer and OpTypeRuntimeArray.
1776 DenseMap<Type *, uint32_t> OpRuntimeTyMap;
1777
1778 for (Type *Ty : getTypeList()) {
1779 // Update TypeMap with nextID for reference later.
1780 TypeMap[Ty] = nextID;
1781
1782 switch (Ty->getTypeID()) {
1783 default: {
1784 Ty->print(errs());
1785 llvm_unreachable("Unsupported type???");
1786 break;
1787 }
1788 case Type::MetadataTyID:
1789 case Type::LabelTyID: {
1790 // Ignore these types.
1791 break;
1792 }
1793 case Type::PointerTyID: {
1794 PointerType *PTy = cast<PointerType>(Ty);
1795 unsigned AddrSpace = PTy->getAddressSpace();
1796
1797 // For the purposes of our Vulkan SPIR-V type system, constant and global
1798 // are conflated.
1799 bool UseExistingOpTypePointer = false;
1800 if (AddressSpace::Constant == AddrSpace) {
1801 AddrSpace = AddressSpace::Global;
1802
1803 // Check to see if we already created this type (for instance, if we had
1804 // a constant <type>* and a global <type>*, the type would be created by
1805 // one of these types, and shared by both).
1806 auto GlobalTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1807 if (0 < TypeMap.count(GlobalTy)) {
1808 TypeMap[PTy] = TypeMap[GlobalTy];
David Netoe439d702018-03-23 13:14:08 -07001809 UseExistingOpTypePointer = true;
David Neto22f144c2017-06-12 14:26:21 -04001810 break;
1811 }
1812 } else if (AddressSpace::Global == AddrSpace) {
1813 AddrSpace = AddressSpace::Constant;
1814
1815 // Check to see if we already created this type (for instance, if we had
1816 // a constant <type>* and a global <type>*, the type would be created by
1817 // one of these types, and shared by both).
1818 auto ConstantTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1819 if (0 < TypeMap.count(ConstantTy)) {
1820 TypeMap[PTy] = TypeMap[ConstantTy];
1821 UseExistingOpTypePointer = true;
1822 }
1823 }
1824
David Neto862b7d82018-06-14 18:48:37 -04001825 const bool HasArgUser = true;
David Neto22f144c2017-06-12 14:26:21 -04001826
David Neto862b7d82018-06-14 18:48:37 -04001827 if (HasArgUser && !UseExistingOpTypePointer) {
David Neto22f144c2017-06-12 14:26:21 -04001828 //
1829 // Generate OpTypePointer.
1830 //
1831
1832 // OpTypePointer
1833 // Ops[0] = Storage Class
1834 // Ops[1] = Element Type ID
1835 SPIRVOperandList Ops;
1836
David Neto257c3892018-04-11 13:19:45 -04001837 Ops << MkNum(GetStorageClass(AddrSpace))
1838 << MkId(lookupType(PTy->getElementType()));
David Neto22f144c2017-06-12 14:26:21 -04001839
David Neto87846742018-04-11 17:36:22 -04001840 auto *Inst = new SPIRVInstruction(spv::OpTypePointer, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001841 SPIRVInstList.push_back(Inst);
1842 }
David Neto22f144c2017-06-12 14:26:21 -04001843 break;
1844 }
1845 case Type::StructTyID: {
David Neto22f144c2017-06-12 14:26:21 -04001846 StructType *STy = cast<StructType>(Ty);
1847
1848 // Handle sampler type.
1849 if (STy->isOpaque()) {
1850 if (STy->getName().equals("opencl.sampler_t")) {
1851 //
1852 // Generate OpTypeSampler
1853 //
1854 // Empty Ops.
1855 SPIRVOperandList Ops;
1856
David Neto87846742018-04-11 17:36:22 -04001857 auto *Inst = new SPIRVInstruction(spv::OpTypeSampler, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001858 SPIRVInstList.push_back(Inst);
1859 break;
1860 } else if (STy->getName().equals("opencl.image2d_ro_t") ||
1861 STy->getName().equals("opencl.image2d_wo_t") ||
1862 STy->getName().equals("opencl.image3d_ro_t") ||
1863 STy->getName().equals("opencl.image3d_wo_t")) {
1864 //
1865 // Generate OpTypeImage
1866 //
1867 // Ops[0] = Sampled Type ID
1868 // Ops[1] = Dim ID
1869 // Ops[2] = Depth (Literal Number)
1870 // Ops[3] = Arrayed (Literal Number)
1871 // Ops[4] = MS (Literal Number)
1872 // Ops[5] = Sampled (Literal Number)
1873 // Ops[6] = Image Format ID
1874 //
1875 SPIRVOperandList Ops;
1876
1877 // TODO: Changed Sampled Type according to situations.
1878 uint32_t SampledTyID = lookupType(Type::getFloatTy(Context));
David Neto257c3892018-04-11 13:19:45 -04001879 Ops << MkId(SampledTyID);
David Neto22f144c2017-06-12 14:26:21 -04001880
1881 spv::Dim DimID = spv::Dim2D;
1882 if (STy->getName().equals("opencl.image3d_ro_t") ||
1883 STy->getName().equals("opencl.image3d_wo_t")) {
1884 DimID = spv::Dim3D;
1885 }
David Neto257c3892018-04-11 13:19:45 -04001886 Ops << MkNum(DimID);
David Neto22f144c2017-06-12 14:26:21 -04001887
1888 // TODO: Set up Depth.
David Neto257c3892018-04-11 13:19:45 -04001889 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001890
1891 // TODO: Set up Arrayed.
David Neto257c3892018-04-11 13:19:45 -04001892 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001893
1894 // TODO: Set up MS.
David Neto257c3892018-04-11 13:19:45 -04001895 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001896
1897 // TODO: Set up Sampled.
1898 //
1899 // From Spec
1900 //
1901 // 0 indicates this is only known at run time, not at compile time
1902 // 1 indicates will be used with sampler
1903 // 2 indicates will be used without a sampler (a storage image)
1904 uint32_t Sampled = 1;
1905 if (STy->getName().equals("opencl.image2d_wo_t") ||
1906 STy->getName().equals("opencl.image3d_wo_t")) {
1907 Sampled = 2;
1908 }
David Neto257c3892018-04-11 13:19:45 -04001909 Ops << MkNum(Sampled);
David Neto22f144c2017-06-12 14:26:21 -04001910
1911 // TODO: Set up Image Format.
David Neto257c3892018-04-11 13:19:45 -04001912 Ops << MkNum(spv::ImageFormatUnknown);
David Neto22f144c2017-06-12 14:26:21 -04001913
David Neto87846742018-04-11 17:36:22 -04001914 auto *Inst = new SPIRVInstruction(spv::OpTypeImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001915 SPIRVInstList.push_back(Inst);
1916 break;
1917 }
1918 }
1919
1920 //
1921 // Generate OpTypeStruct
1922 //
1923 // Ops[0] ... Ops[n] = Member IDs
1924 SPIRVOperandList Ops;
1925
1926 for (auto *EleTy : STy->elements()) {
David Neto862b7d82018-06-14 18:48:37 -04001927 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04001928 }
1929
David Neto22f144c2017-06-12 14:26:21 -04001930 uint32_t STyID = nextID;
1931
David Neto87846742018-04-11 17:36:22 -04001932 auto *Inst =
1933 new SPIRVInstruction(spv::OpTypeStruct, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001934 SPIRVInstList.push_back(Inst);
1935
1936 // Generate OpMemberDecorate.
1937 auto DecoInsertPoint =
1938 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
1939 [](SPIRVInstruction *Inst) -> bool {
1940 return Inst->getOpcode() != spv::OpDecorate &&
1941 Inst->getOpcode() != spv::OpMemberDecorate &&
1942 Inst->getOpcode() != spv::OpExtInstImport;
1943 });
1944
David Netoc463b372017-08-10 15:32:21 -04001945 const auto StructLayout = DL.getStructLayout(STy);
1946
David Neto862b7d82018-06-14 18:48:37 -04001947 // #error TODO(dneto): Only do this if in TypesNeedingLayout.
David Neto22f144c2017-06-12 14:26:21 -04001948 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
1949 MemberIdx++) {
1950 // Ops[0] = Structure Type ID
1951 // Ops[1] = Member Index(Literal Number)
1952 // Ops[2] = Decoration (Offset)
1953 // Ops[3] = Byte Offset (Literal Number)
1954 Ops.clear();
1955
David Neto257c3892018-04-11 13:19:45 -04001956 Ops << MkId(STyID) << MkNum(MemberIdx) << MkNum(spv::DecorationOffset);
David Neto22f144c2017-06-12 14:26:21 -04001957
David Netoc463b372017-08-10 15:32:21 -04001958 const auto ByteOffset =
1959 uint32_t(StructLayout->getElementOffset(MemberIdx));
David Neto257c3892018-04-11 13:19:45 -04001960 Ops << MkNum(ByteOffset);
David Neto22f144c2017-06-12 14:26:21 -04001961
David Neto87846742018-04-11 17:36:22 -04001962 auto *DecoInst = new SPIRVInstruction(spv::OpMemberDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001963 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04001964 }
1965
1966 // Generate OpDecorate.
David Neto862b7d82018-06-14 18:48:37 -04001967 if (StructTypesNeedingBlock.idFor(STy)) {
1968 Ops.clear();
1969 // Use Block decorations with StorageBuffer storage class.
1970 Ops << MkId(STyID) << MkNum(spv::DecorationBlock);
David Neto22f144c2017-06-12 14:26:21 -04001971
David Neto862b7d82018-06-14 18:48:37 -04001972 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
1973 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04001974 }
1975 break;
1976 }
1977 case Type::IntegerTyID: {
1978 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
1979
1980 if (BitWidth == 1) {
David Neto87846742018-04-11 17:36:22 -04001981 auto *Inst = new SPIRVInstruction(spv::OpTypeBool, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04001982 SPIRVInstList.push_back(Inst);
1983 } else {
1984 // i8 is added to TypeMap as i32.
David Neto391aeb12017-08-26 15:51:58 -04001985 // No matter what LLVM type is requested first, always alias the
1986 // second one's SPIR-V type to be the same as the one we generated
1987 // first.
Neil Henning39672102017-09-29 14:33:13 +01001988 unsigned aliasToWidth = 0;
David Neto22f144c2017-06-12 14:26:21 -04001989 if (BitWidth == 8) {
David Neto391aeb12017-08-26 15:51:58 -04001990 aliasToWidth = 32;
David Neto22f144c2017-06-12 14:26:21 -04001991 BitWidth = 32;
David Neto391aeb12017-08-26 15:51:58 -04001992 } else if (BitWidth == 32) {
1993 aliasToWidth = 8;
1994 }
1995 if (aliasToWidth) {
1996 Type* otherType = Type::getIntNTy(Ty->getContext(), aliasToWidth);
1997 auto where = TypeMap.find(otherType);
1998 if (where == TypeMap.end()) {
1999 // Go ahead and make it, but also map the other type to it.
2000 TypeMap[otherType] = nextID;
2001 } else {
2002 // Alias this SPIR-V type the existing type.
2003 TypeMap[Ty] = where->second;
2004 break;
2005 }
David Neto22f144c2017-06-12 14:26:21 -04002006 }
2007
David Neto257c3892018-04-11 13:19:45 -04002008 SPIRVOperandList Ops;
2009 Ops << MkNum(BitWidth) << MkNum(0 /* not signed */);
David Neto22f144c2017-06-12 14:26:21 -04002010
2011 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002012 new SPIRVInstruction(spv::OpTypeInt, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002013 }
2014 break;
2015 }
2016 case Type::HalfTyID:
2017 case Type::FloatTyID:
2018 case Type::DoubleTyID: {
2019 SPIRVOperand *WidthOp = new SPIRVOperand(
2020 SPIRVOperandType::LITERAL_INTEGER, Ty->getPrimitiveSizeInBits());
2021
2022 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002023 new SPIRVInstruction(spv::OpTypeFloat, nextID++, WidthOp));
David Neto22f144c2017-06-12 14:26:21 -04002024 break;
2025 }
2026 case Type::ArrayTyID: {
David Neto22f144c2017-06-12 14:26:21 -04002027 ArrayType *ArrTy = cast<ArrayType>(Ty);
David Neto862b7d82018-06-14 18:48:37 -04002028 const uint64_t Length = ArrTy->getArrayNumElements();
2029 if (Length == 0) {
2030 // By convention, map it to a RuntimeArray.
David Neto22f144c2017-06-12 14:26:21 -04002031
David Neto862b7d82018-06-14 18:48:37 -04002032 // Only generate the type once.
2033 // TODO(dneto): Can it ever be generated more than once?
2034 // Doesn't LLVM type uniqueness guarantee we'll only see this
2035 // once?
2036 Type *EleTy = ArrTy->getArrayElementType();
2037 if (OpRuntimeTyMap.count(EleTy) == 0) {
2038 uint32_t OpTypeRuntimeArrayID = nextID;
2039 OpRuntimeTyMap[Ty] = nextID;
David Neto22f144c2017-06-12 14:26:21 -04002040
David Neto862b7d82018-06-14 18:48:37 -04002041 //
2042 // Generate OpTypeRuntimeArray.
2043 //
David Neto22f144c2017-06-12 14:26:21 -04002044
David Neto862b7d82018-06-14 18:48:37 -04002045 // OpTypeRuntimeArray
2046 // Ops[0] = Element Type ID
2047 SPIRVOperandList Ops;
2048 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04002049
David Neto862b7d82018-06-14 18:48:37 -04002050 SPIRVInstList.push_back(
2051 new SPIRVInstruction(spv::OpTypeRuntimeArray, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002052
David Neto862b7d82018-06-14 18:48:37 -04002053 if (Hack_generate_runtime_array_stride_early) {
2054 // Generate OpDecorate.
2055 auto DecoInsertPoint = std::find_if(
2056 SPIRVInstList.begin(), SPIRVInstList.end(),
2057 [](SPIRVInstruction *Inst) -> bool {
2058 return Inst->getOpcode() != spv::OpDecorate &&
2059 Inst->getOpcode() != spv::OpMemberDecorate &&
2060 Inst->getOpcode() != spv::OpExtInstImport;
2061 });
David Neto22f144c2017-06-12 14:26:21 -04002062
David Neto862b7d82018-06-14 18:48:37 -04002063 // Ops[0] = Target ID
2064 // Ops[1] = Decoration (ArrayStride)
2065 // Ops[2] = Stride Number(Literal Number)
2066 Ops.clear();
David Neto85082642018-03-24 06:55:20 -07002067
David Neto862b7d82018-06-14 18:48:37 -04002068 Ops << MkId(OpTypeRuntimeArrayID)
2069 << MkNum(spv::DecorationArrayStride)
2070 << MkNum(static_cast<uint32_t>(DL.getTypeAllocSize(EleTy)));
David Neto22f144c2017-06-12 14:26:21 -04002071
David Neto862b7d82018-06-14 18:48:37 -04002072 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
2073 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
2074 }
2075 }
David Neto22f144c2017-06-12 14:26:21 -04002076
David Neto862b7d82018-06-14 18:48:37 -04002077 } else {
David Neto22f144c2017-06-12 14:26:21 -04002078
David Neto862b7d82018-06-14 18:48:37 -04002079 //
2080 // Generate OpConstant and OpTypeArray.
2081 //
2082
2083 //
2084 // Generate OpConstant for array length.
2085 //
2086 // Ops[0] = Result Type ID
2087 // Ops[1] .. Ops[n] = Values LiteralNumber
2088 SPIRVOperandList Ops;
2089
2090 Type *LengthTy = Type::getInt32Ty(Context);
2091 uint32_t ResTyID = lookupType(LengthTy);
2092 Ops << MkId(ResTyID);
2093
2094 assert(Length < UINT32_MAX);
2095 Ops << MkNum(static_cast<uint32_t>(Length));
2096
2097 // Add constant for length to constant list.
2098 Constant *CstLength = ConstantInt::get(LengthTy, Length);
2099 AllocatedVMap[CstLength] = nextID;
2100 VMap[CstLength] = nextID;
2101 uint32_t LengthID = nextID;
2102
2103 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
2104 SPIRVInstList.push_back(CstInst);
2105
2106 // Remember to generate ArrayStride later
2107 getTypesNeedingArrayStride().insert(Ty);
2108
2109 //
2110 // Generate OpTypeArray.
2111 //
2112 // Ops[0] = Element Type ID
2113 // Ops[1] = Array Length Constant ID
2114 Ops.clear();
2115
2116 uint32_t EleTyID = lookupType(ArrTy->getElementType());
2117 Ops << MkId(EleTyID) << MkId(LengthID);
2118
2119 // Update TypeMap with nextID.
2120 TypeMap[Ty] = nextID;
2121
2122 auto *ArrayInst = new SPIRVInstruction(spv::OpTypeArray, nextID++, Ops);
2123 SPIRVInstList.push_back(ArrayInst);
2124 }
David Neto22f144c2017-06-12 14:26:21 -04002125 break;
2126 }
2127 case Type::VectorTyID: {
2128 // <4 x i8> is changed to i32.
David Neto22f144c2017-06-12 14:26:21 -04002129 if (Ty->getVectorElementType() == Type::getInt8Ty(Context)) {
2130 if (Ty->getVectorNumElements() == 4) {
2131 TypeMap[Ty] = lookupType(Ty->getVectorElementType());
2132 break;
2133 } else {
2134 Ty->print(errs());
2135 llvm_unreachable("Support above i8 vector type");
2136 }
2137 }
2138
2139 // Ops[0] = Component Type ID
2140 // Ops[1] = Component Count (Literal Number)
David Neto257c3892018-04-11 13:19:45 -04002141 SPIRVOperandList Ops;
2142 Ops << MkId(lookupType(Ty->getVectorElementType()))
2143 << MkNum(Ty->getVectorNumElements());
David Neto22f144c2017-06-12 14:26:21 -04002144
David Neto87846742018-04-11 17:36:22 -04002145 SPIRVInstruction* inst = new SPIRVInstruction(spv::OpTypeVector, nextID++, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002146 SPIRVInstList.push_back(inst);
David Neto22f144c2017-06-12 14:26:21 -04002147 break;
2148 }
2149 case Type::VoidTyID: {
David Neto87846742018-04-11 17:36:22 -04002150 auto *Inst = new SPIRVInstruction(spv::OpTypeVoid, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04002151 SPIRVInstList.push_back(Inst);
2152 break;
2153 }
2154 case Type::FunctionTyID: {
2155 // Generate SPIRV instruction for function type.
2156 FunctionType *FTy = cast<FunctionType>(Ty);
2157
2158 // Ops[0] = Return Type ID
2159 // Ops[1] ... Ops[n] = Parameter Type IDs
2160 SPIRVOperandList Ops;
2161
2162 // Find SPIRV instruction for return type
David Netoc6f3ab22018-04-06 18:02:31 -04002163 Ops << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04002164
2165 // Find SPIRV instructions for parameter types
2166 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
2167 // Find SPIRV instruction for parameter type.
2168 auto ParamTy = FTy->getParamType(k);
2169 if (ParamTy->isPointerTy()) {
2170 auto PointeeTy = ParamTy->getPointerElementType();
2171 if (PointeeTy->isStructTy() &&
2172 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
2173 ParamTy = PointeeTy;
2174 }
2175 }
2176
David Netoc6f3ab22018-04-06 18:02:31 -04002177 Ops << MkId(lookupType(ParamTy));
David Neto22f144c2017-06-12 14:26:21 -04002178 }
2179
David Neto87846742018-04-11 17:36:22 -04002180 auto *Inst = new SPIRVInstruction(spv::OpTypeFunction, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002181 SPIRVInstList.push_back(Inst);
2182 break;
2183 }
2184 }
2185 }
2186
2187 // Generate OpTypeSampledImage.
2188 TypeMapType &OpImageTypeMap = getImageTypeMap();
2189 for (auto &ImageType : OpImageTypeMap) {
2190 //
2191 // Generate OpTypeSampledImage.
2192 //
2193 // Ops[0] = Image Type ID
2194 //
2195 SPIRVOperandList Ops;
2196
2197 Type *ImgTy = ImageType.first;
David Netoc6f3ab22018-04-06 18:02:31 -04002198 Ops << MkId(TypeMap[ImgTy]);
David Neto22f144c2017-06-12 14:26:21 -04002199
2200 // Update OpImageTypeMap.
2201 ImageType.second = nextID;
2202
David Neto87846742018-04-11 17:36:22 -04002203 auto *Inst = new SPIRVInstruction(spv::OpTypeSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002204 SPIRVInstList.push_back(Inst);
2205 }
David Netoc6f3ab22018-04-06 18:02:31 -04002206
2207 // Generate types for pointer-to-local arguments.
Alan Baker202c8c72018-08-13 13:47:44 -04002208 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2209 ++spec_id) {
2210 LocalArgInfo& arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002211
2212 // Generate the spec constant.
2213 SPIRVOperandList Ops;
2214 Ops << MkId(lookupType(Type::getInt32Ty(Context))) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04002215 SPIRVInstList.push_back(
2216 new SPIRVInstruction(spv::OpSpecConstant, arg_info.array_size_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002217
2218 // Generate the array type.
2219 Ops.clear();
2220 // The element type must have been created.
2221 uint32_t elem_ty_id = lookupType(arg_info.elem_type);
2222 assert(elem_ty_id);
2223 Ops << MkId(elem_ty_id) << MkId(arg_info.array_size_id);
2224
2225 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002226 new SPIRVInstruction(spv::OpTypeArray, arg_info.array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002227
2228 Ops.clear();
2229 Ops << MkNum(spv::StorageClassWorkgroup) << MkId(arg_info.array_type_id);
David Neto87846742018-04-11 17:36:22 -04002230 SPIRVInstList.push_back(new SPIRVInstruction(
2231 spv::OpTypePointer, arg_info.ptr_array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002232 }
David Neto22f144c2017-06-12 14:26:21 -04002233}
2234
2235void SPIRVProducerPass::GenerateSPIRVConstants() {
2236 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2237 ValueMapType &VMap = getValueMap();
2238 ValueMapType &AllocatedVMap = getAllocatedValueMap();
2239 ValueList &CstList = getConstantList();
David Neto482550a2018-03-24 05:21:07 -07002240 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04002241
2242 for (uint32_t i = 0; i < CstList.size(); i++) {
David Netofb9a7972017-08-25 17:08:24 -04002243 // UniqueVector ids are 1-based.
2244 Constant *Cst = cast<Constant>(CstList[i+1]);
David Neto22f144c2017-06-12 14:26:21 -04002245
2246 // OpTypeArray's constant was already generated.
David Netofb9a7972017-08-25 17:08:24 -04002247 if (AllocatedVMap.find_as(Cst) != AllocatedVMap.end()) {
David Neto22f144c2017-06-12 14:26:21 -04002248 continue;
2249 }
2250
David Netofb9a7972017-08-25 17:08:24 -04002251 // Set ValueMap with nextID for reference later.
David Neto22f144c2017-06-12 14:26:21 -04002252 VMap[Cst] = nextID;
2253
2254 //
2255 // Generate OpConstant.
2256 //
2257
2258 // Ops[0] = Result Type ID
2259 // Ops[1] .. Ops[n] = Values LiteralNumber
2260 SPIRVOperandList Ops;
2261
David Neto257c3892018-04-11 13:19:45 -04002262 Ops << MkId(lookupType(Cst->getType()));
David Neto22f144c2017-06-12 14:26:21 -04002263
2264 std::vector<uint32_t> LiteralNum;
David Neto22f144c2017-06-12 14:26:21 -04002265 spv::Op Opcode = spv::OpNop;
2266
2267 if (isa<UndefValue>(Cst)) {
2268 // Ops[0] = Result Type ID
David Netoc66b3352017-10-20 14:28:46 -04002269 Opcode = spv::OpUndef;
Alan Baker9bf93fb2018-08-28 16:59:26 -04002270 if (hack_undef && IsTypeNullable(Cst->getType())) {
2271 Opcode = spv::OpConstantNull;
David Netoc66b3352017-10-20 14:28:46 -04002272 }
David Neto22f144c2017-06-12 14:26:21 -04002273 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
2274 unsigned BitWidth = CI->getBitWidth();
2275 if (BitWidth == 1) {
2276 // If the bitwidth of constant is 1, generate OpConstantTrue or
2277 // OpConstantFalse.
2278 if (CI->getZExtValue()) {
2279 // Ops[0] = Result Type ID
2280 Opcode = spv::OpConstantTrue;
2281 } else {
2282 // Ops[0] = Result Type ID
2283 Opcode = spv::OpConstantFalse;
2284 }
David Neto22f144c2017-06-12 14:26:21 -04002285 } else {
2286 auto V = CI->getZExtValue();
2287 LiteralNum.push_back(V & 0xFFFFFFFF);
2288
2289 if (BitWidth > 32) {
2290 LiteralNum.push_back(V >> 32);
2291 }
2292
2293 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002294
David Neto257c3892018-04-11 13:19:45 -04002295 Ops << MkInteger(LiteralNum);
2296
2297 if (BitWidth == 32 && V == 0) {
2298 constant_i32_zero_id_ = nextID;
2299 }
David Neto22f144c2017-06-12 14:26:21 -04002300 }
2301 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2302 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2303 Type *CFPTy = CFP->getType();
2304 if (CFPTy->isFloatTy()) {
2305 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2306 } else {
2307 CFPTy->print(errs());
2308 llvm_unreachable("Implement this ConstantFP Type");
2309 }
2310
2311 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002312
David Neto257c3892018-04-11 13:19:45 -04002313 Ops << MkFloat(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002314 } else if (isa<ConstantDataSequential>(Cst) &&
2315 cast<ConstantDataSequential>(Cst)->isString()) {
2316 Cst->print(errs());
2317 llvm_unreachable("Implement this Constant");
2318
2319 } else if (const ConstantDataSequential *CDS =
2320 dyn_cast<ConstantDataSequential>(Cst)) {
David Neto49351ac2017-08-26 17:32:20 -04002321 // Let's convert <4 x i8> constant to int constant specially.
2322 // This case occurs when all the values are specified as constant
2323 // ints.
2324 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;
2332 for (unsigned k = 0; k < 4; k++) {
2333 const uint64_t Val = CDS->getElementAsInteger(k);
David Neto49351ac2017-08-26 17:32:20 -04002334 IntValue = (IntValue << 8) | (Val & 0xffu);
2335 }
2336
2337 Type *i32 = Type::getInt32Ty(Context);
2338 Constant *CstInt = ConstantInt::get(i32, IntValue);
2339 // If this constant is already registered on VMap, use it.
2340 if (VMap.count(CstInt)) {
2341 uint32_t CstID = VMap[CstInt];
2342 VMap[Cst] = CstID;
2343 continue;
2344 }
2345
David Neto257c3892018-04-11 13:19:45 -04002346 Ops << MkNum(IntValue);
David Neto49351ac2017-08-26 17:32:20 -04002347
David Neto87846742018-04-11 17:36:22 -04002348 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto49351ac2017-08-26 17:32:20 -04002349 SPIRVInstList.push_back(CstInst);
2350
2351 continue;
2352 }
2353
2354 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002355 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
2356 Constant *EleCst = CDS->getElementAsConstant(k);
2357 uint32_t EleCstID = VMap[EleCst];
David Neto257c3892018-04-11 13:19:45 -04002358 Ops << MkId(EleCstID);
David Neto22f144c2017-06-12 14:26:21 -04002359 }
2360
2361 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002362 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2363 // Let's convert <4 x i8> constant to int constant specially.
David Neto49351ac2017-08-26 17:32:20 -04002364 // This case occurs when at least one of the values is an undef.
David Neto22f144c2017-06-12 14:26:21 -04002365 Type *CstTy = Cst->getType();
2366 if (is4xi8vec(CstTy)) {
2367 LLVMContext &Context = CstTy->getContext();
2368
2369 //
2370 // Generate OpConstant with OpTypeInt 32 0.
2371 //
Neil Henning39672102017-09-29 14:33:13 +01002372 uint32_t IntValue = 0;
David Neto22f144c2017-06-12 14:26:21 -04002373 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2374 I != E; ++I) {
2375 uint64_t Val = 0;
David Neto49351ac2017-08-26 17:32:20 -04002376 const Value* CV = *I;
Neil Henning39672102017-09-29 14:33:13 +01002377 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2378 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002379 }
David Neto49351ac2017-08-26 17:32:20 -04002380 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002381 }
2382
David Neto49351ac2017-08-26 17:32:20 -04002383 Type *i32 = Type::getInt32Ty(Context);
2384 Constant *CstInt = ConstantInt::get(i32, IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002385 // If this constant is already registered on VMap, use it.
2386 if (VMap.count(CstInt)) {
2387 uint32_t CstID = VMap[CstInt];
2388 VMap[Cst] = CstID;
David Neto19a1bad2017-08-25 15:01:41 -04002389 continue;
David Neto22f144c2017-06-12 14:26:21 -04002390 }
2391
David Neto257c3892018-04-11 13:19:45 -04002392 Ops << MkNum(IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002393
David Neto87846742018-04-11 17:36:22 -04002394 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002395 SPIRVInstList.push_back(CstInst);
2396
David Neto19a1bad2017-08-25 15:01:41 -04002397 continue;
David Neto22f144c2017-06-12 14:26:21 -04002398 }
2399
2400 // We use a constant composite in SPIR-V for our constant aggregate in
2401 // LLVM.
2402 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002403
2404 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
2405 // Look up the ID of the element of this aggregate (which we will
2406 // previously have created a constant for).
2407 uint32_t ElementConstantID = VMap[CA->getAggregateElement(k)];
2408
2409 // And add an operand to the composite we are constructing
David Neto257c3892018-04-11 13:19:45 -04002410 Ops << MkId(ElementConstantID);
David Neto22f144c2017-06-12 14:26:21 -04002411 }
2412 } else if (Cst->isNullValue()) {
2413 Opcode = spv::OpConstantNull;
David Neto22f144c2017-06-12 14:26:21 -04002414 } else {
2415 Cst->print(errs());
2416 llvm_unreachable("Unsupported Constant???");
2417 }
2418
David Neto87846742018-04-11 17:36:22 -04002419 auto *CstInst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002420 SPIRVInstList.push_back(CstInst);
2421 }
2422}
2423
2424void SPIRVProducerPass::GenerateSamplers(Module &M) {
2425 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2426 ValueMapType &VMap = getValueMap();
2427
David Neto862b7d82018-06-14 18:48:37 -04002428 auto& sampler_map = getSamplerMap();
2429 SamplerMapIndexToIDMap.clear();
David Neto22f144c2017-06-12 14:26:21 -04002430 DenseMap<unsigned, unsigned> SamplerLiteralToIDMap;
David Neto862b7d82018-06-14 18:48:37 -04002431 DenseMap<unsigned, unsigned> SamplerLiteralToDescriptorSetMap;
2432 DenseMap<unsigned, unsigned> SamplerLiteralToBindingMap;
David Neto22f144c2017-06-12 14:26:21 -04002433
David Neto862b7d82018-06-14 18:48:37 -04002434 // We might have samplers in the sampler map that are not used
2435 // in the translation unit. We need to allocate variables
2436 // for them and bindings too.
2437 DenseSet<unsigned> used_bindings;
David Neto22f144c2017-06-12 14:26:21 -04002438
David Neto862b7d82018-06-14 18:48:37 -04002439 auto* var_fn = M.getFunction("clspv.sampler.var.literal");
2440 if (!var_fn) return;
2441 for (auto user : var_fn->users()) {
2442 // Populate SamplerLiteralToDescriptorSetMap and
2443 // SamplerLiteralToBindingMap.
2444 //
2445 // Look for calls like
2446 // call %opencl.sampler_t addrspace(2)*
2447 // @clspv.sampler.var.literal(
2448 // i32 descriptor,
2449 // i32 binding,
2450 // i32 index-into-sampler-map)
2451 if (auto* call = dyn_cast<CallInst>(user)) {
2452 const auto index_into_sampler_map =
2453 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue();
2454 if (index_into_sampler_map >= sampler_map.size()) {
2455 errs() << "Out of bounds index to sampler map: " << index_into_sampler_map;
2456 llvm_unreachable("bad sampler init: out of bounds");
2457 }
2458
2459 auto sampler_value = sampler_map[index_into_sampler_map].first;
2460 const auto descriptor_set = static_cast<unsigned>(
2461 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
2462 const auto binding = static_cast<unsigned>(
2463 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
2464
2465 SamplerLiteralToDescriptorSetMap[sampler_value] = descriptor_set;
2466 SamplerLiteralToBindingMap[sampler_value] = binding;
2467 used_bindings.insert(binding);
2468 }
2469 }
2470
2471 unsigned index = 0;
2472 for (auto SamplerLiteral : sampler_map) {
David Neto22f144c2017-06-12 14:26:21 -04002473 // Generate OpVariable.
2474 //
2475 // GIDOps[0] : Result Type ID
2476 // GIDOps[1] : Storage Class
2477 SPIRVOperandList Ops;
2478
David Neto257c3892018-04-11 13:19:45 -04002479 Ops << MkId(lookupType(SamplerTy))
2480 << MkNum(spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002481
David Neto862b7d82018-06-14 18:48:37 -04002482 auto sampler_var_id = nextID++;
2483 auto *Inst = new SPIRVInstruction(spv::OpVariable, sampler_var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002484 SPIRVInstList.push_back(Inst);
2485
David Neto862b7d82018-06-14 18:48:37 -04002486 SamplerMapIndexToIDMap[index] = sampler_var_id;
2487 SamplerLiteralToIDMap[SamplerLiteral.first] = sampler_var_id;
David Neto22f144c2017-06-12 14:26:21 -04002488
2489 // Find Insert Point for OpDecorate.
2490 auto DecoInsertPoint =
2491 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2492 [](SPIRVInstruction *Inst) -> bool {
2493 return Inst->getOpcode() != spv::OpDecorate &&
2494 Inst->getOpcode() != spv::OpMemberDecorate &&
2495 Inst->getOpcode() != spv::OpExtInstImport;
2496 });
2497
2498 // Ops[0] = Target ID
2499 // Ops[1] = Decoration (DescriptorSet)
2500 // Ops[2] = LiteralNumber according to Decoration
2501 Ops.clear();
2502
David Neto862b7d82018-06-14 18:48:37 -04002503 unsigned descriptor_set;
2504 unsigned binding;
2505 if(SamplerLiteralToBindingMap.find(SamplerLiteral.first) == SamplerLiteralToBindingMap.end()) {
2506 // This sampler is not actually used. Find the next one.
2507 for (binding = 0; used_bindings.count(binding); binding++)
2508 ;
2509 descriptor_set = 0; // Literal samplers always use descriptor set 0.
2510 used_bindings.insert(binding);
2511 } else {
2512 descriptor_set = SamplerLiteralToDescriptorSetMap[SamplerLiteral.first];
2513 binding = SamplerLiteralToBindingMap[SamplerLiteral.first];
2514 }
2515
2516 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationDescriptorSet)
2517 << MkNum(descriptor_set);
David Neto22f144c2017-06-12 14:26:21 -04002518
David Neto44795152017-07-13 15:45:28 -04002519 descriptorMapOut << "sampler," << SamplerLiteral.first << ",samplerExpr,\""
David Neto257c3892018-04-11 13:19:45 -04002520 << SamplerLiteral.second << "\",descriptorSet,"
David Neto862b7d82018-06-14 18:48:37 -04002521 << descriptor_set << ",binding," << binding << "\n";
David Neto22f144c2017-06-12 14:26:21 -04002522
David Neto87846742018-04-11 17:36:22 -04002523 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002524 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2525
2526 // Ops[0] = Target ID
2527 // Ops[1] = Decoration (Binding)
2528 // Ops[2] = LiteralNumber according to Decoration
2529 Ops.clear();
David Neto862b7d82018-06-14 18:48:37 -04002530 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationBinding)
2531 << MkNum(binding);
David Neto22f144c2017-06-12 14:26:21 -04002532
David Neto87846742018-04-11 17:36:22 -04002533 auto *BindDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002534 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
David Neto862b7d82018-06-14 18:48:37 -04002535
2536 index++;
David Neto22f144c2017-06-12 14:26:21 -04002537 }
David Neto862b7d82018-06-14 18:48:37 -04002538}
David Neto22f144c2017-06-12 14:26:21 -04002539
David Neto862b7d82018-06-14 18:48:37 -04002540void SPIRVProducerPass::GenerateResourceVars(Module &M) {
2541 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2542 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04002543
David Neto862b7d82018-06-14 18:48:37 -04002544 // Generate variables. Make one for each of resource var info object.
2545 for (auto *info : ModuleOrderedResourceVars) {
2546 Type *type = info->var_fn->getReturnType();
2547 // Remap the address space for opaque types.
2548 switch (info->arg_kind) {
2549 case clspv::ArgKind::Sampler:
2550 case clspv::ArgKind::ReadOnlyImage:
2551 case clspv::ArgKind::WriteOnlyImage:
2552 type = PointerType::get(type->getPointerElementType(),
2553 clspv::AddressSpace::UniformConstant);
2554 break;
2555 default:
2556 break;
2557 }
David Neto22f144c2017-06-12 14:26:21 -04002558
David Neto862b7d82018-06-14 18:48:37 -04002559 info->var_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04002560
David Neto862b7d82018-06-14 18:48:37 -04002561 const auto type_id = lookupType(type);
2562 const auto sc = GetStorageClassForArgKind(info->arg_kind);
2563 SPIRVOperandList Ops;
2564 Ops << MkId(type_id) << MkNum(sc);
David Neto22f144c2017-06-12 14:26:21 -04002565
David Neto862b7d82018-06-14 18:48:37 -04002566 auto *Inst = new SPIRVInstruction(spv::OpVariable, info->var_id, Ops);
2567 SPIRVInstList.push_back(Inst);
2568
2569 // Map calls to the variable-builtin-function.
2570 for (auto &U : info->var_fn->uses()) {
2571 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
2572 const auto set = unsigned(
2573 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
2574 const auto binding = unsigned(
2575 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
2576 if (set == info->descriptor_set && binding == info->binding) {
2577 switch (info->arg_kind) {
2578 case clspv::ArgKind::Buffer:
2579 case clspv::ArgKind::Pod:
2580 // The call maps to the variable directly.
2581 VMap[call] = info->var_id;
2582 break;
2583 case clspv::ArgKind::Sampler:
2584 case clspv::ArgKind::ReadOnlyImage:
2585 case clspv::ArgKind::WriteOnlyImage:
2586 // The call maps to a load we generate later.
2587 ResourceVarDeferredLoadCalls[call] = info->var_id;
2588 break;
2589 default:
2590 llvm_unreachable("Unhandled arg kind");
2591 }
2592 }
David Neto22f144c2017-06-12 14:26:21 -04002593 }
David Neto862b7d82018-06-14 18:48:37 -04002594 }
2595 }
David Neto22f144c2017-06-12 14:26:21 -04002596
David Neto862b7d82018-06-14 18:48:37 -04002597 // Generate associated decorations.
David Neto22f144c2017-06-12 14:26:21 -04002598
David Neto862b7d82018-06-14 18:48:37 -04002599 // Find Insert Point for OpDecorate.
2600 auto DecoInsertPoint =
2601 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2602 [](SPIRVInstruction *Inst) -> bool {
2603 return Inst->getOpcode() != spv::OpDecorate &&
2604 Inst->getOpcode() != spv::OpMemberDecorate &&
2605 Inst->getOpcode() != spv::OpExtInstImport;
2606 });
2607
2608 SPIRVOperandList Ops;
2609 for (auto *info : ModuleOrderedResourceVars) {
2610 // Decorate with DescriptorSet and Binding.
2611 Ops.clear();
2612 Ops << MkId(info->var_id) << MkNum(spv::DecorationDescriptorSet)
2613 << MkNum(info->descriptor_set);
2614 SPIRVInstList.insert(DecoInsertPoint,
2615 new SPIRVInstruction(spv::OpDecorate, Ops));
2616
2617 Ops.clear();
2618 Ops << MkId(info->var_id) << MkNum(spv::DecorationBinding)
2619 << MkNum(info->binding);
2620 SPIRVInstList.insert(DecoInsertPoint,
2621 new SPIRVInstruction(spv::OpDecorate, Ops));
2622
2623 // Generate NonWritable and NonReadable
2624 switch (info->arg_kind) {
2625 case clspv::ArgKind::Buffer:
2626 if (info->var_fn->getReturnType()->getPointerAddressSpace() ==
2627 clspv::AddressSpace::Constant) {
2628 Ops.clear();
2629 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
2630 SPIRVInstList.insert(DecoInsertPoint,
2631 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002632 }
David Neto862b7d82018-06-14 18:48:37 -04002633 break;
2634 case clspv::ArgKind::ReadOnlyImage:
2635 Ops.clear();
2636 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
2637 SPIRVInstList.insert(DecoInsertPoint,
2638 new SPIRVInstruction(spv::OpDecorate, Ops));
2639 break;
2640 case clspv::ArgKind::WriteOnlyImage:
2641 Ops.clear();
2642 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonReadable);
2643 SPIRVInstList.insert(DecoInsertPoint,
2644 new SPIRVInstruction(spv::OpDecorate, Ops));
2645 break;
2646 default:
2647 break;
David Neto22f144c2017-06-12 14:26:21 -04002648 }
2649 }
2650}
2651
2652void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
David Neto78383442018-06-15 20:31:56 -04002653 Module& M = *GV.getParent();
David Neto22f144c2017-06-12 14:26:21 -04002654 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2655 ValueMapType &VMap = getValueMap();
2656 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07002657 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002658
2659 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2660 Type *Ty = GV.getType();
2661 PointerType *PTy = cast<PointerType>(Ty);
2662
2663 uint32_t InitializerID = 0;
2664
2665 // Workgroup size is handled differently (it goes into a constant)
2666 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2667 std::vector<bool> HasMDVec;
2668 uint32_t PrevXDimCst = 0xFFFFFFFF;
2669 uint32_t PrevYDimCst = 0xFFFFFFFF;
2670 uint32_t PrevZDimCst = 0xFFFFFFFF;
2671 for (Function &Func : *GV.getParent()) {
2672 if (Func.isDeclaration()) {
2673 continue;
2674 }
2675
2676 // We only need to check kernels.
2677 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2678 continue;
2679 }
2680
2681 if (const MDNode *MD =
2682 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2683 uint32_t CurXDimCst = static_cast<uint32_t>(
2684 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2685 uint32_t CurYDimCst = static_cast<uint32_t>(
2686 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2687 uint32_t CurZDimCst = static_cast<uint32_t>(
2688 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2689
2690 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2691 PrevZDimCst == 0xFFFFFFFF) {
2692 PrevXDimCst = CurXDimCst;
2693 PrevYDimCst = CurYDimCst;
2694 PrevZDimCst = CurZDimCst;
2695 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2696 CurZDimCst != PrevZDimCst) {
2697 llvm_unreachable(
2698 "reqd_work_group_size must be the same across all kernels");
2699 } else {
2700 continue;
2701 }
2702
2703 //
2704 // Generate OpConstantComposite.
2705 //
2706 // Ops[0] : Result Type ID
2707 // Ops[1] : Constant size for x dimension.
2708 // Ops[2] : Constant size for y dimension.
2709 // Ops[3] : Constant size for z dimension.
2710 SPIRVOperandList Ops;
2711
2712 uint32_t XDimCstID =
2713 VMap[mdconst::extract<ConstantInt>(MD->getOperand(0))];
2714 uint32_t YDimCstID =
2715 VMap[mdconst::extract<ConstantInt>(MD->getOperand(1))];
2716 uint32_t ZDimCstID =
2717 VMap[mdconst::extract<ConstantInt>(MD->getOperand(2))];
2718
2719 InitializerID = nextID;
2720
David Neto257c3892018-04-11 13:19:45 -04002721 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2722 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002723
David Neto87846742018-04-11 17:36:22 -04002724 auto *Inst =
2725 new SPIRVInstruction(spv::OpConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002726 SPIRVInstList.push_back(Inst);
2727
2728 HasMDVec.push_back(true);
2729 } else {
2730 HasMDVec.push_back(false);
2731 }
2732 }
2733
2734 // Check all kernels have same definitions for work_group_size.
2735 bool HasMD = false;
2736 if (!HasMDVec.empty()) {
2737 HasMD = HasMDVec[0];
2738 for (uint32_t i = 1; i < HasMDVec.size(); i++) {
2739 if (HasMD != HasMDVec[i]) {
2740 llvm_unreachable(
2741 "Kernels should have consistent work group size definition");
2742 }
2743 }
2744 }
2745
2746 // If all kernels do not have metadata for reqd_work_group_size, generate
2747 // OpSpecConstants for x/y/z dimension.
2748 if (!HasMD) {
2749 //
2750 // Generate OpSpecConstants for x/y/z dimension.
2751 //
2752 // Ops[0] : Result Type ID
2753 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
2754 uint32_t XDimCstID = 0;
2755 uint32_t YDimCstID = 0;
2756 uint32_t ZDimCstID = 0;
2757
David Neto22f144c2017-06-12 14:26:21 -04002758 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04002759 uint32_t result_type_id =
2760 lookupType(Ty->getPointerElementType()->getSequentialElementType());
David Neto22f144c2017-06-12 14:26:21 -04002761
David Neto257c3892018-04-11 13:19:45 -04002762 // X Dimension
2763 Ops << MkId(result_type_id) << MkNum(1);
2764 XDimCstID = nextID++;
2765 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002766 new SPIRVInstruction(spv::OpSpecConstant, XDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002767
2768 // Y Dimension
2769 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002770 Ops << MkId(result_type_id) << MkNum(1);
2771 YDimCstID = nextID++;
2772 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002773 new SPIRVInstruction(spv::OpSpecConstant, YDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002774
2775 // Z Dimension
2776 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002777 Ops << MkId(result_type_id) << MkNum(1);
2778 ZDimCstID = nextID++;
2779 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002780 new SPIRVInstruction(spv::OpSpecConstant, ZDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002781
David Neto22f144c2017-06-12 14:26:21 -04002782
David Neto257c3892018-04-11 13:19:45 -04002783 BuiltinDimVec.push_back(XDimCstID);
2784 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002785 BuiltinDimVec.push_back(ZDimCstID);
2786
David Neto22f144c2017-06-12 14:26:21 -04002787
2788 //
2789 // Generate OpSpecConstantComposite.
2790 //
2791 // Ops[0] : Result Type ID
2792 // Ops[1] : Constant size for x dimension.
2793 // Ops[2] : Constant size for y dimension.
2794 // Ops[3] : Constant size for z dimension.
2795 InitializerID = nextID;
2796
2797 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002798 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2799 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002800
David Neto87846742018-04-11 17:36:22 -04002801 auto *Inst =
2802 new SPIRVInstruction(spv::OpSpecConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002803 SPIRVInstList.push_back(Inst);
2804 }
2805 }
2806
David Neto22f144c2017-06-12 14:26:21 -04002807 VMap[&GV] = nextID;
2808
2809 //
2810 // Generate OpVariable.
2811 //
2812 // GIDOps[0] : Result Type ID
2813 // GIDOps[1] : Storage Class
2814 SPIRVOperandList Ops;
2815
David Neto85082642018-03-24 06:55:20 -07002816 const auto AS = PTy->getAddressSpace();
David Netoc6f3ab22018-04-06 18:02:31 -04002817 Ops << MkId(lookupType(Ty)) << MkNum(GetStorageClass(AS));
David Neto22f144c2017-06-12 14:26:21 -04002818
David Neto85082642018-03-24 06:55:20 -07002819 if (GV.hasInitializer()) {
2820 InitializerID = VMap[GV.getInitializer()];
David Neto22f144c2017-06-12 14:26:21 -04002821 }
2822
David Neto85082642018-03-24 06:55:20 -07002823 const bool module_scope_constant_external_init =
David Neto862b7d82018-06-14 18:48:37 -04002824 (AS == AddressSpace::Constant) && GV.hasInitializer() &&
David Neto85082642018-03-24 06:55:20 -07002825 clspv::Option::ModuleConstantsInStorageBuffer();
2826
2827 if (0 != InitializerID) {
2828 if (!module_scope_constant_external_init) {
2829 // Emit the ID of the intiializer as part of the variable definition.
David Netoc6f3ab22018-04-06 18:02:31 -04002830 Ops << MkId(InitializerID);
David Neto85082642018-03-24 06:55:20 -07002831 }
2832 }
2833 const uint32_t var_id = nextID++;
2834
David Neto87846742018-04-11 17:36:22 -04002835 auto *Inst = new SPIRVInstruction(spv::OpVariable, var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002836 SPIRVInstList.push_back(Inst);
2837
2838 // If we have a builtin.
2839 if (spv::BuiltInMax != BuiltinType) {
2840 // Find Insert Point for OpDecorate.
2841 auto DecoInsertPoint =
2842 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2843 [](SPIRVInstruction *Inst) -> bool {
2844 return Inst->getOpcode() != spv::OpDecorate &&
2845 Inst->getOpcode() != spv::OpMemberDecorate &&
2846 Inst->getOpcode() != spv::OpExtInstImport;
2847 });
2848 //
2849 // Generate OpDecorate.
2850 //
2851 // DOps[0] = Target ID
2852 // DOps[1] = Decoration (Builtin)
2853 // DOps[2] = BuiltIn ID
2854 uint32_t ResultID;
2855
2856 // WorkgroupSize is different, we decorate the constant composite that has
2857 // its value, rather than the variable that we use to access the value.
2858 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2859 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04002860 // Save both the value and variable IDs for later.
2861 WorkgroupSizeValueID = InitializerID;
2862 WorkgroupSizeVarID = VMap[&GV];
David Neto22f144c2017-06-12 14:26:21 -04002863 } else {
2864 ResultID = VMap[&GV];
2865 }
2866
2867 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002868 DOps << MkId(ResultID) << MkNum(spv::DecorationBuiltIn)
2869 << MkNum(BuiltinType);
David Neto22f144c2017-06-12 14:26:21 -04002870
David Neto87846742018-04-11 17:36:22 -04002871 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, DOps);
David Neto22f144c2017-06-12 14:26:21 -04002872 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
David Neto85082642018-03-24 06:55:20 -07002873 } else if (module_scope_constant_external_init) {
2874 // This module scope constant is initialized from a storage buffer with data
2875 // provided by the host at binding 0 of the next descriptor set.
David Neto78383442018-06-15 20:31:56 -04002876 const uint32_t descriptor_set = TakeDescriptorIndex(&M);
David Neto85082642018-03-24 06:55:20 -07002877
David Neto862b7d82018-06-14 18:48:37 -04002878 // Emit the intializer to the descriptor map file.
David Neto85082642018-03-24 06:55:20 -07002879 // Use "kind,buffer" to indicate storage buffer. We might want to expand
2880 // that later to other types, like uniform buffer.
2881 descriptorMapOut << "constant,descriptorSet," << descriptor_set
2882 << ",binding,0,kind,buffer,hexbytes,";
2883 clspv::ConstantEmitter(DL, descriptorMapOut).Emit(GV.getInitializer());
2884 descriptorMapOut << "\n";
2885
2886 // Find Insert Point for OpDecorate.
2887 auto DecoInsertPoint =
2888 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2889 [](SPIRVInstruction *Inst) -> bool {
2890 return Inst->getOpcode() != spv::OpDecorate &&
2891 Inst->getOpcode() != spv::OpMemberDecorate &&
2892 Inst->getOpcode() != spv::OpExtInstImport;
2893 });
2894
David Neto257c3892018-04-11 13:19:45 -04002895 // OpDecorate %var Binding <binding>
David Neto85082642018-03-24 06:55:20 -07002896 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002897 DOps << MkId(var_id) << MkNum(spv::DecorationBinding) << MkNum(0);
2898 DecoInsertPoint = SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04002899 DecoInsertPoint, new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto85082642018-03-24 06:55:20 -07002900
2901 // OpDecorate %var DescriptorSet <descriptor_set>
2902 DOps.clear();
David Neto257c3892018-04-11 13:19:45 -04002903 DOps << MkId(var_id) << MkNum(spv::DecorationDescriptorSet)
2904 << MkNum(descriptor_set);
David Netoc6f3ab22018-04-06 18:02:31 -04002905 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04002906 new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto22f144c2017-06-12 14:26:21 -04002907 }
2908}
2909
David Netoc6f3ab22018-04-06 18:02:31 -04002910void SPIRVProducerPass::GenerateWorkgroupVars() {
2911 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
Alan Baker202c8c72018-08-13 13:47:44 -04002912 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2913 ++spec_id) {
2914 LocalArgInfo& info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002915
2916 // Generate OpVariable.
2917 //
2918 // GIDOps[0] : Result Type ID
2919 // GIDOps[1] : Storage Class
2920 SPIRVOperandList Ops;
2921 Ops << MkId(info.ptr_array_type_id) << MkNum(spv::StorageClassWorkgroup);
2922
2923 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002924 new SPIRVInstruction(spv::OpVariable, info.variable_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002925 }
2926}
2927
David Neto862b7d82018-06-14 18:48:37 -04002928void SPIRVProducerPass::GenerateDescriptorMapInfo(const DataLayout &DL,
2929 Function &F) {
David Netoc5fb5242018-07-30 13:28:31 -04002930 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2931 return;
2932 }
David Neto862b7d82018-06-14 18:48:37 -04002933 // Gather the list of resources that are used by this function's arguments.
2934 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
2935
2936 auto remap_arg_kind = [](StringRef argKind) {
2937 return clspv::Option::PodArgsInUniformBuffer() && argKind.equals("pod")
2938 ? "pod_ubo"
2939 : argKind;
2940 };
2941
2942 auto *fty = F.getType()->getPointerElementType();
2943 auto *func_ty = dyn_cast<FunctionType>(fty);
2944
2945 // If we've clustereed POD arguments, then argument details are in metadata.
2946 // If an argument maps to a resource variable, then get descriptor set and
2947 // binding from the resoure variable. Other info comes from the metadata.
2948 const auto *arg_map = F.getMetadata("kernel_arg_map");
2949 if (arg_map) {
2950 for (const auto &arg : arg_map->operands()) {
2951 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
2952 assert(arg_node->getNumOperands() == 6);
2953 const auto name =
2954 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
2955 const auto old_index =
2956 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
2957 // Remapped argument index
2958 const auto new_index =
2959 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getZExtValue();
2960 const auto offset =
2961 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
2962 const auto argKind = remap_arg_kind(
2963 dyn_cast<MDString>(arg_node->getOperand(4))->getString());
2964 const auto spec_id =
2965 dyn_extract<ConstantInt>(arg_node->getOperand(5))->getSExtValue();
2966 if (spec_id > 0) {
2967 // This was a pointer-to-local argument. It is not associated with a
2968 // resource variable.
2969 descriptorMapOut << "kernel," << F.getName() << ",arg," << name
2970 << ",argOrdinal," << old_index << ",argKind,"
2971 << argKind << ",arrayElemSize,"
2972 << DL.getTypeAllocSize(
2973 func_ty->getParamType(unsigned(new_index))
2974 ->getPointerElementType())
2975 << ",arrayNumElemSpecId," << spec_id << "\n";
2976 } else {
2977 auto *info = resource_var_at_index[new_index];
2978 assert(info);
2979 descriptorMapOut << "kernel," << F.getName() << ",arg," << name
2980 << ",argOrdinal," << old_index << ",descriptorSet,"
2981 << info->descriptor_set << ",binding," << info->binding
2982 << ",offset," << offset << ",argKind," << argKind
2983 << "\n";
2984 }
2985 }
2986 } else {
2987 // There is no argument map.
2988 // Take descriptor info from the resource variable calls.
2989 // Take argument name from the arguments list.
2990
2991 SmallVector<Argument *, 4> arguments;
2992 for (auto &arg : F.args()) {
2993 arguments.push_back(&arg);
2994 }
2995
2996 unsigned arg_index = 0;
2997 for (auto *info : resource_var_at_index) {
2998 if (info) {
2999 descriptorMapOut << "kernel," << F.getName() << ",arg,"
3000 << arguments[arg_index]->getName() << ",argOrdinal,"
3001 << arg_index << ",descriptorSet,"
3002 << info->descriptor_set << ",binding," << info->binding
3003 << ",offset," << 0 << ",argKind,"
3004 << remap_arg_kind(
3005 clspv::GetArgKindName(info->arg_kind))
3006 << "\n";
3007 }
3008 arg_index++;
3009 }
3010 // Generate mappings for pointer-to-local arguments.
3011 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
3012 Argument *arg = arguments[arg_index];
Alan Baker202c8c72018-08-13 13:47:44 -04003013 auto where = LocalArgSpecIds.find(arg);
3014 if (where != LocalArgSpecIds.end()) {
3015 auto &local_arg_info = LocalSpecIdInfoMap[where->second];
David Neto862b7d82018-06-14 18:48:37 -04003016 descriptorMapOut << "kernel," << F.getName() << ",arg,"
3017 << arg->getName() << ",argOrdinal," << arg_index
3018 << ",argKind,"
3019 << "local"
3020 << ",arrayElemSize,"
3021 << DL.getTypeAllocSize(local_arg_info.elem_type)
3022 << ",arrayNumElemSpecId," << local_arg_info.spec_id
3023 << "\n";
3024 }
3025 }
3026 }
3027}
3028
David Neto22f144c2017-06-12 14:26:21 -04003029void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
David Neto78383442018-06-15 20:31:56 -04003030 Module& M = *F.getParent();
3031 const DataLayout &DL = M.getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04003032 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3033 ValueMapType &VMap = getValueMap();
3034 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04003035 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
3036 auto &GlobalConstArgSet = getGlobalConstArgSet();
3037
3038 FunctionType *FTy = F.getFunctionType();
3039
3040 //
David Neto22f144c2017-06-12 14:26:21 -04003041 // Generate OPFunction.
3042 //
3043
3044 // FOps[0] : Result Type ID
3045 // FOps[1] : Function Control
3046 // FOps[2] : Function Type ID
3047 SPIRVOperandList FOps;
3048
3049 // Find SPIRV instruction for return type.
David Neto257c3892018-04-11 13:19:45 -04003050 FOps << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04003051
3052 // Check function attributes for SPIRV Function Control.
3053 uint32_t FuncControl = spv::FunctionControlMaskNone;
3054 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
3055 FuncControl |= spv::FunctionControlInlineMask;
3056 }
3057 if (F.hasFnAttribute(Attribute::NoInline)) {
3058 FuncControl |= spv::FunctionControlDontInlineMask;
3059 }
3060 // TODO: Check llvm attribute for Function Control Pure.
3061 if (F.hasFnAttribute(Attribute::ReadOnly)) {
3062 FuncControl |= spv::FunctionControlPureMask;
3063 }
3064 // TODO: Check llvm attribute for Function Control Const.
3065 if (F.hasFnAttribute(Attribute::ReadNone)) {
3066 FuncControl |= spv::FunctionControlConstMask;
3067 }
3068
David Neto257c3892018-04-11 13:19:45 -04003069 FOps << MkNum(FuncControl);
David Neto22f144c2017-06-12 14:26:21 -04003070
3071 uint32_t FTyID;
3072 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3073 SmallVector<Type *, 4> NewFuncParamTys;
3074 FunctionType *NewFTy =
3075 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
3076 FTyID = lookupType(NewFTy);
3077 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07003078 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04003079 if (GlobalConstFuncTyMap.count(FTy)) {
3080 FTyID = lookupType(GlobalConstFuncTyMap[FTy].first);
3081 } else {
3082 FTyID = lookupType(FTy);
3083 }
3084 }
3085
David Neto257c3892018-04-11 13:19:45 -04003086 FOps << MkId(FTyID);
David Neto22f144c2017-06-12 14:26:21 -04003087
3088 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3089 EntryPoints.push_back(std::make_pair(&F, nextID));
3090 }
3091
3092 VMap[&F] = nextID;
3093
David Neto482550a2018-03-24 05:21:07 -07003094 if (clspv::Option::ShowIDs()) {
David Netob05675d2018-02-16 12:37:49 -05003095 errs() << "Function " << F.getName() << " is " << nextID << "\n";
3096 }
David Neto22f144c2017-06-12 14:26:21 -04003097 // Generate SPIRV instruction for function.
David Neto87846742018-04-11 17:36:22 -04003098 auto *FuncInst = new SPIRVInstruction(spv::OpFunction, nextID++, FOps);
David Neto22f144c2017-06-12 14:26:21 -04003099 SPIRVInstList.push_back(FuncInst);
3100
3101 //
3102 // Generate OpFunctionParameter for Normal function.
3103 //
3104
3105 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3106 // Iterate Argument for name instead of param type from function type.
3107 unsigned ArgIdx = 0;
3108 for (Argument &Arg : F.args()) {
3109 VMap[&Arg] = nextID;
3110
3111 // ParamOps[0] : Result Type ID
3112 SPIRVOperandList ParamOps;
3113
3114 // Find SPIRV instruction for parameter type.
3115 uint32_t ParamTyID = lookupType(Arg.getType());
3116 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
3117 if (GlobalConstFuncTyMap.count(FTy)) {
3118 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
3119 Type *EleTy = PTy->getPointerElementType();
3120 Type *ArgTy =
3121 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
3122 ParamTyID = lookupType(ArgTy);
3123 GlobalConstArgSet.insert(&Arg);
3124 }
3125 }
3126 }
David Neto257c3892018-04-11 13:19:45 -04003127 ParamOps << MkId(ParamTyID);
David Neto22f144c2017-06-12 14:26:21 -04003128
3129 // Generate SPIRV instruction for parameter.
David Neto87846742018-04-11 17:36:22 -04003130 auto *ParamInst =
3131 new SPIRVInstruction(spv::OpFunctionParameter, nextID++, ParamOps);
David Neto22f144c2017-06-12 14:26:21 -04003132 SPIRVInstList.push_back(ParamInst);
3133
3134 ArgIdx++;
3135 }
3136 }
3137}
3138
David Neto5c22a252018-03-15 16:07:41 -04003139void SPIRVProducerPass::GenerateModuleInfo(Module& module) {
David Neto22f144c2017-06-12 14:26:21 -04003140 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3141 EntryPointVecType &EntryPoints = getEntryPointVec();
3142 ValueMapType &VMap = getValueMap();
3143 ValueList &EntryPointInterfaces = getEntryPointInterfacesVec();
3144 uint32_t &ExtInstImportID = getOpExtInstImportID();
3145 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
3146
3147 // Set up insert point.
3148 auto InsertPoint = SPIRVInstList.begin();
3149
3150 //
3151 // Generate OpCapability
3152 //
3153 // TODO: Which llvm information is mapped to SPIRV Capapbility?
3154
3155 // Ops[0] = Capability
3156 SPIRVOperandList Ops;
3157
David Neto87846742018-04-11 17:36:22 -04003158 auto *CapInst =
3159 new SPIRVInstruction(spv::OpCapability, {MkNum(spv::CapabilityShader)});
David Neto22f144c2017-06-12 14:26:21 -04003160 SPIRVInstList.insert(InsertPoint, CapInst);
3161
3162 for (Type *Ty : getTypeList()) {
3163 // Find the i16 type.
3164 if (Ty->isIntegerTy(16)) {
3165 // Generate OpCapability for i16 type.
David Neto87846742018-04-11 17:36:22 -04003166 SPIRVInstList.insert(InsertPoint,
3167 new SPIRVInstruction(spv::OpCapability,
3168 {MkNum(spv::CapabilityInt16)}));
David Neto22f144c2017-06-12 14:26:21 -04003169 } else if (Ty->isIntegerTy(64)) {
3170 // Generate OpCapability for i64 type.
David Neto87846742018-04-11 17:36:22 -04003171 SPIRVInstList.insert(InsertPoint,
3172 new SPIRVInstruction(spv::OpCapability,
3173 {MkNum(spv::CapabilityInt64)}));
David Neto22f144c2017-06-12 14:26:21 -04003174 } else if (Ty->isHalfTy()) {
3175 // Generate OpCapability for half type.
3176 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003177 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3178 {MkNum(spv::CapabilityFloat16)}));
David Neto22f144c2017-06-12 14:26:21 -04003179 } else if (Ty->isDoubleTy()) {
3180 // Generate OpCapability for double type.
3181 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003182 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3183 {MkNum(spv::CapabilityFloat64)}));
David Neto22f144c2017-06-12 14:26:21 -04003184 } else if (auto *STy = dyn_cast<StructType>(Ty)) {
3185 if (STy->isOpaque()) {
David Neto565571c2017-08-21 12:00:05 -04003186 if (STy->getName().equals("opencl.image2d_wo_t") ||
3187 STy->getName().equals("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04003188 // Generate OpCapability for write only image type.
3189 SPIRVInstList.insert(
3190 InsertPoint,
3191 new SPIRVInstruction(
David Neto87846742018-04-11 17:36:22 -04003192 spv::OpCapability,
3193 {MkNum(spv::CapabilityStorageImageWriteWithoutFormat)}));
David Neto22f144c2017-06-12 14:26:21 -04003194 }
3195 }
3196 }
3197 }
3198
David Neto5c22a252018-03-15 16:07:41 -04003199 { // OpCapability ImageQuery
3200 bool hasImageQuery = false;
3201 for (const char *imageQuery : {
3202 "_Z15get_image_width14ocl_image2d_ro",
3203 "_Z15get_image_width14ocl_image2d_wo",
3204 "_Z16get_image_height14ocl_image2d_ro",
3205 "_Z16get_image_height14ocl_image2d_wo",
3206 }) {
3207 if (module.getFunction(imageQuery)) {
3208 hasImageQuery = true;
3209 break;
3210 }
3211 }
3212 if (hasImageQuery) {
David Neto87846742018-04-11 17:36:22 -04003213 auto *ImageQueryCapInst = new SPIRVInstruction(
3214 spv::OpCapability, {MkNum(spv::CapabilityImageQuery)});
David Neto5c22a252018-03-15 16:07:41 -04003215 SPIRVInstList.insert(InsertPoint, ImageQueryCapInst);
3216 }
3217 }
3218
David Neto22f144c2017-06-12 14:26:21 -04003219 if (hasVariablePointers()) {
3220 //
3221 // Generate OpCapability and OpExtension
3222 //
3223
3224 //
3225 // Generate OpCapability.
3226 //
3227 // Ops[0] = Capability
3228 //
3229 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003230 Ops << MkNum(spv::CapabilityVariablePointers);
David Neto22f144c2017-06-12 14:26:21 -04003231
David Neto87846742018-04-11 17:36:22 -04003232 SPIRVInstList.insert(InsertPoint,
3233 new SPIRVInstruction(spv::OpCapability, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003234
3235 //
3236 // Generate OpExtension.
3237 //
3238 // Ops[0] = Name (Literal String)
3239 //
David Netoa772fd12017-08-04 14:17:33 -04003240 for (auto extension : {"SPV_KHR_storage_buffer_storage_class",
3241 "SPV_KHR_variable_pointers"}) {
David Neto22f144c2017-06-12 14:26:21 -04003242
David Neto87846742018-04-11 17:36:22 -04003243 auto *ExtensionInst =
3244 new SPIRVInstruction(spv::OpExtension, {MkString(extension)});
David Netoa772fd12017-08-04 14:17:33 -04003245 SPIRVInstList.insert(InsertPoint, ExtensionInst);
David Neto22f144c2017-06-12 14:26:21 -04003246 }
David Neto22f144c2017-06-12 14:26:21 -04003247 }
3248
3249 if (ExtInstImportID) {
3250 ++InsertPoint;
3251 }
3252
3253 //
3254 // Generate OpMemoryModel
3255 //
3256 // Memory model for Vulkan will always be GLSL450.
3257
3258 // Ops[0] = Addressing Model
3259 // Ops[1] = Memory Model
3260 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003261 Ops << MkNum(spv::AddressingModelLogical) << MkNum(spv::MemoryModelGLSL450);
David Neto22f144c2017-06-12 14:26:21 -04003262
David Neto87846742018-04-11 17:36:22 -04003263 auto *MemModelInst = new SPIRVInstruction(spv::OpMemoryModel, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003264 SPIRVInstList.insert(InsertPoint, MemModelInst);
3265
3266 //
3267 // Generate OpEntryPoint
3268 //
3269 for (auto EntryPoint : EntryPoints) {
3270 // Ops[0] = Execution Model
3271 // Ops[1] = EntryPoint ID
3272 // Ops[2] = Name (Literal String)
3273 // ...
3274 //
3275 // TODO: Do we need to consider Interface ID for forward references???
3276 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003277 const StringRef& name = EntryPoint.first->getName();
3278 Ops << MkNum(spv::ExecutionModelGLCompute) << MkId(EntryPoint.second)
3279 << MkString(name);
David Neto22f144c2017-06-12 14:26:21 -04003280
David Neto22f144c2017-06-12 14:26:21 -04003281 for (Value *Interface : EntryPointInterfaces) {
David Neto257c3892018-04-11 13:19:45 -04003282 Ops << MkId(VMap[Interface]);
David Neto22f144c2017-06-12 14:26:21 -04003283 }
3284
David Neto87846742018-04-11 17:36:22 -04003285 auto *EntryPointInst = new SPIRVInstruction(spv::OpEntryPoint, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003286 SPIRVInstList.insert(InsertPoint, EntryPointInst);
3287 }
3288
3289 for (auto EntryPoint : EntryPoints) {
3290 if (const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
3291 ->getMetadata("reqd_work_group_size")) {
3292
3293 if (!BuiltinDimVec.empty()) {
3294 llvm_unreachable(
3295 "Kernels should have consistent work group size definition");
3296 }
3297
3298 //
3299 // Generate OpExecutionMode
3300 //
3301
3302 // Ops[0] = Entry Point ID
3303 // Ops[1] = Execution Mode
3304 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
3305 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003306 Ops << MkId(EntryPoint.second)
3307 << MkNum(spv::ExecutionModeLocalSize);
David Neto22f144c2017-06-12 14:26:21 -04003308
3309 uint32_t XDim = static_cast<uint32_t>(
3310 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3311 uint32_t YDim = static_cast<uint32_t>(
3312 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3313 uint32_t ZDim = static_cast<uint32_t>(
3314 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3315
David Neto257c3892018-04-11 13:19:45 -04003316 Ops << MkNum(XDim) << MkNum(YDim) << MkNum(ZDim);
David Neto22f144c2017-06-12 14:26:21 -04003317
David Neto87846742018-04-11 17:36:22 -04003318 auto *ExecModeInst = new SPIRVInstruction(spv::OpExecutionMode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003319 SPIRVInstList.insert(InsertPoint, ExecModeInst);
3320 }
3321 }
3322
3323 //
3324 // Generate OpSource.
3325 //
3326 // Ops[0] = SourceLanguage ID
3327 // Ops[1] = Version (LiteralNum)
3328 //
3329 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003330 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(120);
David Neto22f144c2017-06-12 14:26:21 -04003331
David Neto87846742018-04-11 17:36:22 -04003332 auto *OpenSourceInst = new SPIRVInstruction(spv::OpSource, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003333 SPIRVInstList.insert(InsertPoint, OpenSourceInst);
3334
3335 if (!BuiltinDimVec.empty()) {
3336 //
3337 // Generate OpDecorates for x/y/z dimension.
3338 //
3339 // Ops[0] = Target ID
3340 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04003341 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04003342
3343 // X Dimension
3344 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003345 Ops << MkId(BuiltinDimVec[0]) << MkNum(spv::DecorationSpecId) << MkNum(0);
David Neto87846742018-04-11 17:36:22 -04003346 SPIRVInstList.insert(InsertPoint,
3347 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003348
3349 // Y Dimension
3350 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003351 Ops << MkId(BuiltinDimVec[1]) << MkNum(spv::DecorationSpecId) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04003352 SPIRVInstList.insert(InsertPoint,
3353 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003354
3355 // Z Dimension
3356 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003357 Ops << MkId(BuiltinDimVec[2]) << MkNum(spv::DecorationSpecId) << MkNum(2);
David Neto87846742018-04-11 17:36:22 -04003358 SPIRVInstList.insert(InsertPoint,
3359 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003360 }
3361}
3362
David Netob6e2e062018-04-25 10:32:06 -04003363void SPIRVProducerPass::GenerateEntryPointInitialStores() {
3364 // Work around a driver bug. Initializers on Private variables might not
3365 // work. So the start of the kernel should store the initializer value to the
3366 // variables. Yes, *every* entry point pays this cost if *any* entry point
3367 // uses this builtin. At this point I judge this to be an acceptable tradeoff
3368 // of complexity vs. runtime, for a broken driver.
3369 // TODO(dneto): Remove this at some point once fixed drivers are widely available.
3370 if (WorkgroupSizeVarID) {
3371 assert(WorkgroupSizeValueID);
3372
3373 SPIRVOperandList Ops;
3374 Ops << MkId(WorkgroupSizeVarID) << MkId(WorkgroupSizeValueID);
3375
3376 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
3377 getSPIRVInstList().push_back(Inst);
3378 }
3379}
3380
David Neto22f144c2017-06-12 14:26:21 -04003381void SPIRVProducerPass::GenerateFuncBody(Function &F) {
3382 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3383 ValueMapType &VMap = getValueMap();
3384
David Netob6e2e062018-04-25 10:32:06 -04003385 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04003386
3387 for (BasicBlock &BB : F) {
3388 // Register BasicBlock to ValueMap.
3389 VMap[&BB] = nextID;
3390
3391 //
3392 // Generate OpLabel for Basic Block.
3393 //
3394 SPIRVOperandList Ops;
David Neto87846742018-04-11 17:36:22 -04003395 auto *Inst = new SPIRVInstruction(spv::OpLabel, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003396 SPIRVInstList.push_back(Inst);
3397
David Neto6dcd4712017-06-23 11:06:47 -04003398 // OpVariable instructions must come first.
3399 for (Instruction &I : BB) {
3400 if (isa<AllocaInst>(I)) {
3401 GenerateInstruction(I);
3402 }
3403 }
3404
David Neto22f144c2017-06-12 14:26:21 -04003405 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04003406 if (clspv::Option::HackInitializers()) {
3407 GenerateEntryPointInitialStores();
3408 }
David Neto22f144c2017-06-12 14:26:21 -04003409 }
3410
3411 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003412 if (!isa<AllocaInst>(I)) {
3413 GenerateInstruction(I);
3414 }
David Neto22f144c2017-06-12 14:26:21 -04003415 }
3416 }
3417}
3418
3419spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3420 const std::map<CmpInst::Predicate, spv::Op> Map = {
3421 {CmpInst::ICMP_EQ, spv::OpIEqual},
3422 {CmpInst::ICMP_NE, spv::OpINotEqual},
3423 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3424 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3425 {CmpInst::ICMP_ULT, spv::OpULessThan},
3426 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3427 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3428 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3429 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3430 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3431 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3432 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3433 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3434 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3435 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3436 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3437 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3438 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3439 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3440 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3441 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3442 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3443
3444 assert(0 != Map.count(I->getPredicate()));
3445
3446 return Map.at(I->getPredicate());
3447}
3448
3449spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3450 const std::map<unsigned, spv::Op> Map{
3451 {Instruction::Trunc, spv::OpUConvert},
3452 {Instruction::ZExt, spv::OpUConvert},
3453 {Instruction::SExt, spv::OpSConvert},
3454 {Instruction::FPToUI, spv::OpConvertFToU},
3455 {Instruction::FPToSI, spv::OpConvertFToS},
3456 {Instruction::UIToFP, spv::OpConvertUToF},
3457 {Instruction::SIToFP, spv::OpConvertSToF},
3458 {Instruction::FPTrunc, spv::OpFConvert},
3459 {Instruction::FPExt, spv::OpFConvert},
3460 {Instruction::BitCast, spv::OpBitcast}};
3461
3462 assert(0 != Map.count(I.getOpcode()));
3463
3464 return Map.at(I.getOpcode());
3465}
3466
3467spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
3468 if (I.getType()->isIntegerTy(1)) {
3469 switch (I.getOpcode()) {
3470 default:
3471 break;
3472 case Instruction::Or:
3473 return spv::OpLogicalOr;
3474 case Instruction::And:
3475 return spv::OpLogicalAnd;
3476 case Instruction::Xor:
3477 return spv::OpLogicalNotEqual;
3478 }
3479 }
3480
3481 const std::map<unsigned, spv::Op> Map {
3482 {Instruction::Add, spv::OpIAdd},
3483 {Instruction::FAdd, spv::OpFAdd},
3484 {Instruction::Sub, spv::OpISub},
3485 {Instruction::FSub, spv::OpFSub},
3486 {Instruction::Mul, spv::OpIMul},
3487 {Instruction::FMul, spv::OpFMul},
3488 {Instruction::UDiv, spv::OpUDiv},
3489 {Instruction::SDiv, spv::OpSDiv},
3490 {Instruction::FDiv, spv::OpFDiv},
3491 {Instruction::URem, spv::OpUMod},
3492 {Instruction::SRem, spv::OpSRem},
3493 {Instruction::FRem, spv::OpFRem},
3494 {Instruction::Or, spv::OpBitwiseOr},
3495 {Instruction::Xor, spv::OpBitwiseXor},
3496 {Instruction::And, spv::OpBitwiseAnd},
3497 {Instruction::Shl, spv::OpShiftLeftLogical},
3498 {Instruction::LShr, spv::OpShiftRightLogical},
3499 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3500
3501 assert(0 != Map.count(I.getOpcode()));
3502
3503 return Map.at(I.getOpcode());
3504}
3505
3506void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
3507 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3508 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04003509 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
3510 LLVMContext &Context = I.getParent()->getParent()->getParent()->getContext();
3511
3512 // Register Instruction to ValueMap.
3513 if (0 == VMap[&I]) {
3514 VMap[&I] = nextID;
3515 }
3516
3517 switch (I.getOpcode()) {
3518 default: {
3519 if (Instruction::isCast(I.getOpcode())) {
3520 //
3521 // Generate SPIRV instructions for cast operators.
3522 //
3523
David Netod2de94a2017-08-28 17:27:47 -04003524
3525 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003526 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003527 auto toI8 = Ty == Type::getInt8Ty(Context);
3528 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003529 // Handle zext, sext and uitofp with i1 type specially.
3530 if ((I.getOpcode() == Instruction::ZExt ||
3531 I.getOpcode() == Instruction::SExt ||
3532 I.getOpcode() == Instruction::UIToFP) &&
3533 (OpTy->isIntegerTy(1) ||
3534 (OpTy->isVectorTy() &&
3535 OpTy->getVectorElementType()->isIntegerTy(1)))) {
3536 //
3537 // Generate OpSelect.
3538 //
3539
3540 // Ops[0] = Result Type ID
3541 // Ops[1] = Condition ID
3542 // Ops[2] = True Constant ID
3543 // Ops[3] = False Constant ID
3544 SPIRVOperandList Ops;
3545
David Neto257c3892018-04-11 13:19:45 -04003546 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003547
David Neto22f144c2017-06-12 14:26:21 -04003548 uint32_t CondID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003549 Ops << MkId(CondID);
David Neto22f144c2017-06-12 14:26:21 -04003550
3551 uint32_t TrueID = 0;
3552 if (I.getOpcode() == Instruction::ZExt) {
3553 APInt One(32, 1);
3554 TrueID = VMap[Constant::getIntegerValue(I.getType(), One)];
3555 } else if (I.getOpcode() == Instruction::SExt) {
3556 APInt MinusOne(32, UINT64_MAX, true);
3557 TrueID = VMap[Constant::getIntegerValue(I.getType(), MinusOne)];
3558 } else {
3559 TrueID = VMap[ConstantFP::get(Context, APFloat(1.0f))];
3560 }
David Neto257c3892018-04-11 13:19:45 -04003561 Ops << MkId(TrueID);
David Neto22f144c2017-06-12 14:26:21 -04003562
3563 uint32_t FalseID = 0;
3564 if (I.getOpcode() == Instruction::ZExt) {
3565 FalseID = VMap[Constant::getNullValue(I.getType())];
3566 } else if (I.getOpcode() == Instruction::SExt) {
3567 FalseID = VMap[Constant::getNullValue(I.getType())];
3568 } else {
3569 FalseID = VMap[ConstantFP::get(Context, APFloat(0.0f))];
3570 }
David Neto257c3892018-04-11 13:19:45 -04003571 Ops << MkId(FalseID);
David Neto22f144c2017-06-12 14:26:21 -04003572
David Neto87846742018-04-11 17:36:22 -04003573 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003574 SPIRVInstList.push_back(Inst);
David Netod2de94a2017-08-28 17:27:47 -04003575 } else if (I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
3576 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3577 // 8 bits.
3578 // Before:
3579 // %result = trunc i32 %a to i8
3580 // After
3581 // %result = OpBitwiseAnd %uint %a %uint_255
3582
3583 SPIRVOperandList Ops;
3584
David Neto257c3892018-04-11 13:19:45 -04003585 Ops << MkId(lookupType(OpTy)) << MkId(VMap[I.getOperand(0)]);
David Netod2de94a2017-08-28 17:27:47 -04003586
3587 Type *UintTy = Type::getInt32Ty(Context);
3588 uint32_t MaskID = VMap[ConstantInt::get(UintTy, 255)];
David Neto257c3892018-04-11 13:19:45 -04003589 Ops << MkId(MaskID);
David Netod2de94a2017-08-28 17:27:47 -04003590
David Neto87846742018-04-11 17:36:22 -04003591 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Netod2de94a2017-08-28 17:27:47 -04003592 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003593 } else {
3594 // Ops[0] = Result Type ID
3595 // Ops[1] = Source Value ID
3596 SPIRVOperandList Ops;
3597
David Neto257c3892018-04-11 13:19:45 -04003598 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003599
David Neto87846742018-04-11 17:36:22 -04003600 auto *Inst = new SPIRVInstruction(GetSPIRVCastOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003601 SPIRVInstList.push_back(Inst);
3602 }
3603 } else if (isa<BinaryOperator>(I)) {
3604 //
3605 // Generate SPIRV instructions for binary operators.
3606 //
3607
3608 // Handle xor with i1 type specially.
3609 if (I.getOpcode() == Instruction::Xor &&
3610 I.getType() == Type::getInt1Ty(Context) &&
3611 (isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
3612 //
3613 // Generate OpLogicalNot.
3614 //
3615 // Ops[0] = Result Type ID
3616 // Ops[1] = Operand
3617 SPIRVOperandList Ops;
3618
David Neto257c3892018-04-11 13:19:45 -04003619 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003620
3621 Value *CondV = I.getOperand(0);
3622 if (isa<Constant>(I.getOperand(0))) {
3623 CondV = I.getOperand(1);
3624 }
David Neto257c3892018-04-11 13:19:45 -04003625 Ops << MkId(VMap[CondV]);
David Neto22f144c2017-06-12 14:26:21 -04003626
David Neto87846742018-04-11 17:36:22 -04003627 auto *Inst = new SPIRVInstruction(spv::OpLogicalNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003628 SPIRVInstList.push_back(Inst);
3629 } else {
3630 // Ops[0] = Result Type ID
3631 // Ops[1] = Operand 0
3632 // Ops[2] = Operand 1
3633 SPIRVOperandList Ops;
3634
David Neto257c3892018-04-11 13:19:45 -04003635 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
3636 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003637
David Neto87846742018-04-11 17:36:22 -04003638 auto *Inst =
3639 new SPIRVInstruction(GetSPIRVBinaryOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003640 SPIRVInstList.push_back(Inst);
3641 }
3642 } else {
3643 I.print(errs());
3644 llvm_unreachable("Unsupported instruction???");
3645 }
3646 break;
3647 }
3648 case Instruction::GetElementPtr: {
3649 auto &GlobalConstArgSet = getGlobalConstArgSet();
3650
3651 //
3652 // Generate OpAccessChain.
3653 //
3654 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
3655
3656 //
3657 // Generate OpAccessChain.
3658 //
3659
3660 // Ops[0] = Result Type ID
3661 // Ops[1] = Base ID
3662 // Ops[2] ... Ops[n] = Indexes ID
3663 SPIRVOperandList Ops;
3664
David Neto1a1a0582017-07-07 12:01:44 -04003665 PointerType* ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04003666 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
3667 GlobalConstArgSet.count(GEP->getPointerOperand())) {
3668 // Use pointer type with private address space for global constant.
3669 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04003670 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04003671 }
David Neto257c3892018-04-11 13:19:45 -04003672
3673 Ops << MkId(lookupType(ResultType));
David Neto22f144c2017-06-12 14:26:21 -04003674
David Neto862b7d82018-06-14 18:48:37 -04003675 // Generate the base pointer.
3676 Ops << MkId(VMap[GEP->getPointerOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04003677
David Neto862b7d82018-06-14 18:48:37 -04003678 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04003679
3680 //
3681 // Follows below rules for gep.
3682 //
David Neto862b7d82018-06-14 18:48:37 -04003683 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
3684 // first index.
David Neto22f144c2017-06-12 14:26:21 -04003685 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
3686 // first index.
3687 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
3688 // use gep's first index.
3689 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
3690 // gep's first index.
3691 //
3692 spv::Op Opcode = spv::OpAccessChain;
3693 unsigned offset = 0;
3694 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04003695 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04003696 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04003697 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04003698 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04003699 }
David Neto862b7d82018-06-14 18:48:37 -04003700 } else {
David Neto22f144c2017-06-12 14:26:21 -04003701 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04003702 }
3703
3704 if (Opcode == spv::OpPtrAccessChain) {
David Neto22f144c2017-06-12 14:26:21 -04003705 setVariablePointers(true);
David Neto1a1a0582017-07-07 12:01:44 -04003706 // Do we need to generate ArrayStride? Check against the GEP result type
3707 // rather than the pointer type of the base because when indexing into
3708 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
3709 // for something else in the SPIR-V.
3710 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
3711 if (GetStorageClass(ResultType->getAddressSpace()) ==
3712 spv::StorageClassStorageBuffer) {
3713 // Save the need to generate an ArrayStride decoration. But defer
3714 // generation until later, so we only make one decoration.
David Neto85082642018-03-24 06:55:20 -07003715 getTypesNeedingArrayStride().insert(ResultType);
David Neto1a1a0582017-07-07 12:01:44 -04003716 }
David Neto22f144c2017-06-12 14:26:21 -04003717 }
3718
3719 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
David Neto257c3892018-04-11 13:19:45 -04003720 Ops << MkId(VMap[*II]);
David Neto22f144c2017-06-12 14:26:21 -04003721 }
3722
David Neto87846742018-04-11 17:36:22 -04003723 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003724 SPIRVInstList.push_back(Inst);
3725 break;
3726 }
3727 case Instruction::ExtractValue: {
3728 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3729 // Ops[0] = Result Type ID
3730 // Ops[1] = Composite ID
3731 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3732 SPIRVOperandList Ops;
3733
David Neto257c3892018-04-11 13:19:45 -04003734 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003735
3736 uint32_t CompositeID = VMap[EVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003737 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003738
3739 for (auto &Index : EVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003740 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003741 }
3742
David Neto87846742018-04-11 17:36:22 -04003743 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003744 SPIRVInstList.push_back(Inst);
3745 break;
3746 }
3747 case Instruction::InsertValue: {
3748 InsertValueInst *IVI = cast<InsertValueInst>(&I);
3749 // Ops[0] = Result Type ID
3750 // Ops[1] = Object ID
3751 // Ops[2] = Composite ID
3752 // Ops[3] ... Ops[n] = Indexes (Literal Number)
3753 SPIRVOperandList Ops;
3754
3755 uint32_t ResTyID = lookupType(I.getType());
David Neto257c3892018-04-11 13:19:45 -04003756 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04003757
3758 uint32_t ObjectID = VMap[IVI->getInsertedValueOperand()];
David Neto257c3892018-04-11 13:19:45 -04003759 Ops << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04003760
3761 uint32_t CompositeID = VMap[IVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003762 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003763
3764 for (auto &Index : IVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003765 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003766 }
3767
David Neto87846742018-04-11 17:36:22 -04003768 auto *Inst = new SPIRVInstruction(spv::OpCompositeInsert, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003769 SPIRVInstList.push_back(Inst);
3770 break;
3771 }
3772 case Instruction::Select: {
3773 //
3774 // Generate OpSelect.
3775 //
3776
3777 // Ops[0] = Result Type ID
3778 // Ops[1] = Condition ID
3779 // Ops[2] = True Constant ID
3780 // Ops[3] = False Constant ID
3781 SPIRVOperandList Ops;
3782
3783 // Find SPIRV instruction for parameter type.
3784 auto Ty = I.getType();
3785 if (Ty->isPointerTy()) {
3786 auto PointeeTy = Ty->getPointerElementType();
3787 if (PointeeTy->isStructTy() &&
3788 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
3789 Ty = PointeeTy;
3790 }
3791 }
3792
David Neto257c3892018-04-11 13:19:45 -04003793 Ops << MkId(lookupType(Ty)) << MkId(VMap[I.getOperand(0)])
3794 << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003795
David Neto87846742018-04-11 17:36:22 -04003796 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003797 SPIRVInstList.push_back(Inst);
3798 break;
3799 }
3800 case Instruction::ExtractElement: {
3801 // Handle <4 x i8> type manually.
3802 Type *CompositeTy = I.getOperand(0)->getType();
3803 if (is4xi8vec(CompositeTy)) {
3804 //
3805 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
3806 // <4 x i8>.
3807 //
3808
3809 //
3810 // Generate OpShiftRightLogical
3811 //
3812 // Ops[0] = Result Type ID
3813 // Ops[1] = Operand 0
3814 // Ops[2] = Operand 1
3815 //
3816 SPIRVOperandList Ops;
3817
David Neto257c3892018-04-11 13:19:45 -04003818 Ops << MkId(lookupType(CompositeTy));
David Neto22f144c2017-06-12 14:26:21 -04003819
3820 uint32_t Op0ID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003821 Ops << MkId(Op0ID);
David Neto22f144c2017-06-12 14:26:21 -04003822
3823 uint32_t Op1ID = 0;
3824 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
3825 // Handle constant index.
3826 uint64_t Idx = CI->getZExtValue();
3827 Value *ShiftAmount =
3828 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3829 Op1ID = VMap[ShiftAmount];
3830 } else {
3831 // Handle variable index.
3832 SPIRVOperandList TmpOps;
3833
David Neto257c3892018-04-11 13:19:45 -04003834 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3835 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003836
3837 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003838 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003839
3840 Op1ID = nextID;
3841
David Neto87846742018-04-11 17:36:22 -04003842 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003843 SPIRVInstList.push_back(TmpInst);
3844 }
David Neto257c3892018-04-11 13:19:45 -04003845 Ops << MkId(Op1ID);
David Neto22f144c2017-06-12 14:26:21 -04003846
3847 uint32_t ShiftID = nextID;
3848
David Neto87846742018-04-11 17:36:22 -04003849 auto *Inst =
3850 new SPIRVInstruction(spv::OpShiftRightLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003851 SPIRVInstList.push_back(Inst);
3852
3853 //
3854 // Generate OpBitwiseAnd
3855 //
3856 // Ops[0] = Result Type ID
3857 // Ops[1] = Operand 0
3858 // Ops[2] = Operand 1
3859 //
3860 Ops.clear();
3861
David Neto257c3892018-04-11 13:19:45 -04003862 Ops << MkId(lookupType(CompositeTy)) << MkId(ShiftID);
David Neto22f144c2017-06-12 14:26:21 -04003863
3864 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
David Neto257c3892018-04-11 13:19:45 -04003865 Ops << MkId(VMap[CstFF]);
David Neto22f144c2017-06-12 14:26:21 -04003866
David Neto9b2d6252017-09-06 15:47:37 -04003867 // Reset mapping for this value to the result of the bitwise and.
3868 VMap[&I] = nextID;
3869
David Neto87846742018-04-11 17:36:22 -04003870 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003871 SPIRVInstList.push_back(Inst);
3872 break;
3873 }
3874
3875 // Ops[0] = Result Type ID
3876 // Ops[1] = Composite ID
3877 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3878 SPIRVOperandList Ops;
3879
David Neto257c3892018-04-11 13:19:45 -04003880 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003881
3882 spv::Op Opcode = spv::OpCompositeExtract;
3883 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
David Neto257c3892018-04-11 13:19:45 -04003884 Ops << MkNum(static_cast<uint32_t>(CI->getZExtValue()));
David Neto22f144c2017-06-12 14:26:21 -04003885 } else {
David Neto257c3892018-04-11 13:19:45 -04003886 Ops << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003887 Opcode = spv::OpVectorExtractDynamic;
3888 }
3889
David Neto87846742018-04-11 17:36:22 -04003890 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003891 SPIRVInstList.push_back(Inst);
3892 break;
3893 }
3894 case Instruction::InsertElement: {
3895 // Handle <4 x i8> type manually.
3896 Type *CompositeTy = I.getOperand(0)->getType();
3897 if (is4xi8vec(CompositeTy)) {
3898 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
3899 uint32_t CstFFID = VMap[CstFF];
3900
3901 uint32_t ShiftAmountID = 0;
3902 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
3903 // Handle constant index.
3904 uint64_t Idx = CI->getZExtValue();
3905 Value *ShiftAmount =
3906 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3907 ShiftAmountID = VMap[ShiftAmount];
3908 } else {
3909 // Handle variable index.
3910 SPIRVOperandList TmpOps;
3911
David Neto257c3892018-04-11 13:19:45 -04003912 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3913 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003914
3915 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003916 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003917
3918 ShiftAmountID = nextID;
3919
David Neto87846742018-04-11 17:36:22 -04003920 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003921 SPIRVInstList.push_back(TmpInst);
3922 }
3923
3924 //
3925 // Generate mask operations.
3926 //
3927
3928 // ShiftLeft mask according to index of insertelement.
3929 SPIRVOperandList Ops;
3930
David Neto257c3892018-04-11 13:19:45 -04003931 const uint32_t ResTyID = lookupType(CompositeTy);
3932 Ops << MkId(ResTyID) << MkId(CstFFID) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04003933
3934 uint32_t MaskID = nextID;
3935
David Neto87846742018-04-11 17:36:22 -04003936 auto *Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003937 SPIRVInstList.push_back(Inst);
3938
3939 // Inverse mask.
3940 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003941 Ops << MkId(ResTyID) << MkId(MaskID);
David Neto22f144c2017-06-12 14:26:21 -04003942
3943 uint32_t InvMaskID = nextID;
3944
David Neto87846742018-04-11 17:36:22 -04003945 Inst = new SPIRVInstruction(spv::OpNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003946 SPIRVInstList.push_back(Inst);
3947
3948 // Apply mask.
3949 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003950 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(0)]) << MkId(InvMaskID);
David Neto22f144c2017-06-12 14:26:21 -04003951
3952 uint32_t OrgValID = nextID;
3953
David Neto87846742018-04-11 17:36:22 -04003954 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003955 SPIRVInstList.push_back(Inst);
3956
3957 // Create correct value according to index of insertelement.
3958 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003959 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(1)]) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04003960
3961 uint32_t InsertValID = nextID;
3962
David Neto87846742018-04-11 17:36:22 -04003963 Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003964 SPIRVInstList.push_back(Inst);
3965
3966 // Insert value to original value.
3967 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003968 Ops << MkId(ResTyID) << MkId(OrgValID) << MkId(InsertValID);
David Neto22f144c2017-06-12 14:26:21 -04003969
David Netoa394f392017-08-26 20:45:29 -04003970 VMap[&I] = nextID;
3971
David Neto87846742018-04-11 17:36:22 -04003972 Inst = new SPIRVInstruction(spv::OpBitwiseOr, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003973 SPIRVInstList.push_back(Inst);
3974
3975 break;
3976 }
3977
David Neto22f144c2017-06-12 14:26:21 -04003978 SPIRVOperandList Ops;
3979
James Priced26efea2018-06-09 23:28:32 +01003980 // Ops[0] = Result Type ID
3981 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003982
3983 spv::Op Opcode = spv::OpCompositeInsert;
3984 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04003985 const auto value = CI->getZExtValue();
3986 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01003987 // Ops[1] = Object ID
3988 // Ops[2] = Composite ID
3989 // Ops[3] ... Ops[n] = Indexes (Literal Number)
3990 Ops << MkId(VMap[I.getOperand(1)])
3991 << MkId(VMap[I.getOperand(0)])
3992 << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04003993 } else {
James Priced26efea2018-06-09 23:28:32 +01003994 // Ops[1] = Composite ID
3995 // Ops[2] = Object ID
3996 // Ops[3] ... Ops[n] = Indexes (Literal Number)
3997 Ops << MkId(VMap[I.getOperand(0)])
3998 << MkId(VMap[I.getOperand(1)])
3999 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004000 Opcode = spv::OpVectorInsertDynamic;
4001 }
4002
David Neto87846742018-04-11 17:36:22 -04004003 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004004 SPIRVInstList.push_back(Inst);
4005 break;
4006 }
4007 case Instruction::ShuffleVector: {
4008 // Ops[0] = Result Type ID
4009 // Ops[1] = Vector 1 ID
4010 // Ops[2] = Vector 2 ID
4011 // Ops[3] ... Ops[n] = Components (Literal Number)
4012 SPIRVOperandList Ops;
4013
David Neto257c3892018-04-11 13:19:45 -04004014 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4015 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004016
4017 uint64_t NumElements = 0;
4018 if (Constant *Cst = dyn_cast<Constant>(I.getOperand(2))) {
4019 NumElements = cast<VectorType>(Cst->getType())->getNumElements();
4020
4021 if (Cst->isNullValue()) {
4022 for (unsigned i = 0; i < NumElements; i++) {
David Neto257c3892018-04-11 13:19:45 -04004023 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04004024 }
4025 } else if (const ConstantDataSequential *CDS =
4026 dyn_cast<ConstantDataSequential>(Cst)) {
4027 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
4028 std::vector<uint32_t> LiteralNum;
David Neto257c3892018-04-11 13:19:45 -04004029 const auto value = CDS->getElementAsInteger(i);
4030 assert(value <= UINT32_MAX);
4031 Ops << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004032 }
4033 } else if (const ConstantVector *CV = dyn_cast<ConstantVector>(Cst)) {
4034 for (unsigned i = 0; i < CV->getNumOperands(); i++) {
4035 auto Op = CV->getOperand(i);
4036
4037 uint32_t literal = 0;
4038
4039 if (auto CI = dyn_cast<ConstantInt>(Op)) {
4040 literal = static_cast<uint32_t>(CI->getZExtValue());
4041 } else if (auto UI = dyn_cast<UndefValue>(Op)) {
4042 literal = 0xFFFFFFFFu;
4043 } else {
4044 Op->print(errs());
4045 llvm_unreachable("Unsupported element in ConstantVector!");
4046 }
4047
David Neto257c3892018-04-11 13:19:45 -04004048 Ops << MkNum(literal);
David Neto22f144c2017-06-12 14:26:21 -04004049 }
4050 } else {
4051 Cst->print(errs());
4052 llvm_unreachable("Unsupported constant mask in ShuffleVector!");
4053 }
4054 }
4055
David Neto87846742018-04-11 17:36:22 -04004056 auto *Inst = new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004057 SPIRVInstList.push_back(Inst);
4058 break;
4059 }
4060 case Instruction::ICmp:
4061 case Instruction::FCmp: {
4062 CmpInst *CmpI = cast<CmpInst>(&I);
4063
David Netod4ca2e62017-07-06 18:47:35 -04004064 // Pointer equality is invalid.
4065 Type* ArgTy = CmpI->getOperand(0)->getType();
4066 if (isa<PointerType>(ArgTy)) {
4067 CmpI->print(errs());
4068 std::string name = I.getParent()->getParent()->getName();
4069 errs()
4070 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4071 << "in function " << name << "\n";
4072 llvm_unreachable("Pointer equality check is invalid");
4073 break;
4074 }
4075
David Neto257c3892018-04-11 13:19:45 -04004076 // Ops[0] = Result Type ID
4077 // Ops[1] = Operand 1 ID
4078 // Ops[2] = Operand 2 ID
4079 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004080
David Neto257c3892018-04-11 13:19:45 -04004081 Ops << MkId(lookupType(CmpI->getType())) << MkId(VMap[CmpI->getOperand(0)])
4082 << MkId(VMap[CmpI->getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004083
4084 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
David Neto87846742018-04-11 17:36:22 -04004085 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004086 SPIRVInstList.push_back(Inst);
4087 break;
4088 }
4089 case Instruction::Br: {
4090 // Branch instrucion is deferred because it needs label's ID. Record slot's
4091 // location on SPIRVInstructionList.
4092 DeferredInsts.push_back(
4093 std::make_tuple(&I, --SPIRVInstList.end(), 0 /* No id */));
4094 break;
4095 }
4096 case Instruction::Switch: {
4097 I.print(errs());
4098 llvm_unreachable("Unsupported instruction???");
4099 break;
4100 }
4101 case Instruction::IndirectBr: {
4102 I.print(errs());
4103 llvm_unreachable("Unsupported instruction???");
4104 break;
4105 }
4106 case Instruction::PHI: {
4107 // Branch instrucion is deferred because it needs label's ID. Record slot's
4108 // location on SPIRVInstructionList.
4109 DeferredInsts.push_back(
4110 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4111 break;
4112 }
4113 case Instruction::Alloca: {
4114 //
4115 // Generate OpVariable.
4116 //
4117 // Ops[0] : Result Type ID
4118 // Ops[1] : Storage Class
4119 SPIRVOperandList Ops;
4120
David Neto257c3892018-04-11 13:19:45 -04004121 Ops << MkId(lookupType(I.getType())) << MkNum(spv::StorageClassFunction);
David Neto22f144c2017-06-12 14:26:21 -04004122
David Neto87846742018-04-11 17:36:22 -04004123 auto *Inst = new SPIRVInstruction(spv::OpVariable, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004124 SPIRVInstList.push_back(Inst);
4125 break;
4126 }
4127 case Instruction::Load: {
4128 LoadInst *LD = cast<LoadInst>(&I);
4129 //
4130 // Generate OpLoad.
4131 //
4132
David Neto0a2f98d2017-09-15 19:38:40 -04004133 uint32_t ResTyID = lookupType(LD->getType());
David Netoa60b00b2017-09-15 16:34:09 -04004134 uint32_t PointerID = VMap[LD->getPointerOperand()];
4135
4136 // This is a hack to work around what looks like a driver bug.
4137 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004138 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4139 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004140 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004141 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004142 // Generate a bitwise-and of the original value with itself.
4143 // We should have been able to get away with just an OpCopyObject,
4144 // but we need something more complex to get past certain driver bugs.
4145 // This is ridiculous, but necessary.
4146 // TODO(dneto): Revisit this once drivers fix their bugs.
4147
4148 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004149 Ops << MkId(ResTyID) << MkId(WorkgroupSizeValueID)
4150 << MkId(WorkgroupSizeValueID);
David Neto0a2f98d2017-09-15 19:38:40 -04004151
David Neto87846742018-04-11 17:36:22 -04004152 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto0a2f98d2017-09-15 19:38:40 -04004153 SPIRVInstList.push_back(Inst);
David Netoa60b00b2017-09-15 16:34:09 -04004154 break;
4155 }
4156
4157 // This is the normal path. Generate a load.
4158
David Neto22f144c2017-06-12 14:26:21 -04004159 // Ops[0] = Result Type ID
4160 // Ops[1] = Pointer ID
4161 // Ops[2] ... Ops[n] = Optional Memory Access
4162 //
4163 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004164
David Neto22f144c2017-06-12 14:26:21 -04004165 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004166 Ops << MkId(ResTyID) << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04004167
David Neto87846742018-04-11 17:36:22 -04004168 auto *Inst = new SPIRVInstruction(spv::OpLoad, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004169 SPIRVInstList.push_back(Inst);
4170 break;
4171 }
4172 case Instruction::Store: {
4173 StoreInst *ST = cast<StoreInst>(&I);
4174 //
4175 // Generate OpStore.
4176 //
4177
4178 // Ops[0] = Pointer ID
4179 // Ops[1] = Object ID
4180 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4181 //
4182 // TODO: Do we need to implement Optional Memory Access???
David Neto257c3892018-04-11 13:19:45 -04004183 SPIRVOperandList Ops;
4184 Ops << MkId(VMap[ST->getPointerOperand()])
4185 << MkId(VMap[ST->getValueOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004186
David Neto87846742018-04-11 17:36:22 -04004187 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004188 SPIRVInstList.push_back(Inst);
4189 break;
4190 }
4191 case Instruction::AtomicCmpXchg: {
4192 I.print(errs());
4193 llvm_unreachable("Unsupported instruction???");
4194 break;
4195 }
4196 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004197 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4198
4199 spv::Op opcode;
4200
4201 switch (AtomicRMW->getOperation()) {
4202 default:
4203 I.print(errs());
4204 llvm_unreachable("Unsupported instruction???");
4205 case llvm::AtomicRMWInst::Add:
4206 opcode = spv::OpAtomicIAdd;
4207 break;
4208 case llvm::AtomicRMWInst::Sub:
4209 opcode = spv::OpAtomicISub;
4210 break;
4211 case llvm::AtomicRMWInst::Xchg:
4212 opcode = spv::OpAtomicExchange;
4213 break;
4214 case llvm::AtomicRMWInst::Min:
4215 opcode = spv::OpAtomicSMin;
4216 break;
4217 case llvm::AtomicRMWInst::Max:
4218 opcode = spv::OpAtomicSMax;
4219 break;
4220 case llvm::AtomicRMWInst::UMin:
4221 opcode = spv::OpAtomicUMin;
4222 break;
4223 case llvm::AtomicRMWInst::UMax:
4224 opcode = spv::OpAtomicUMax;
4225 break;
4226 case llvm::AtomicRMWInst::And:
4227 opcode = spv::OpAtomicAnd;
4228 break;
4229 case llvm::AtomicRMWInst::Or:
4230 opcode = spv::OpAtomicOr;
4231 break;
4232 case llvm::AtomicRMWInst::Xor:
4233 opcode = spv::OpAtomicXor;
4234 break;
4235 }
4236
4237 //
4238 // Generate OpAtomic*.
4239 //
4240 SPIRVOperandList Ops;
4241
David Neto257c3892018-04-11 13:19:45 -04004242 Ops << MkId(lookupType(I.getType()))
4243 << MkId(VMap[AtomicRMW->getPointerOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004244
4245 auto IntTy = Type::getInt32Ty(I.getContext());
Neil Henning39672102017-09-29 14:33:13 +01004246 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
David Neto257c3892018-04-11 13:19:45 -04004247 Ops << MkId(VMap[ConstantScopeDevice]);
Neil Henning39672102017-09-29 14:33:13 +01004248
4249 const auto ConstantMemorySemantics = ConstantInt::get(
4250 IntTy, spv::MemorySemanticsUniformMemoryMask |
4251 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto257c3892018-04-11 13:19:45 -04004252 Ops << MkId(VMap[ConstantMemorySemantics]);
Neil Henning39672102017-09-29 14:33:13 +01004253
David Neto257c3892018-04-11 13:19:45 -04004254 Ops << MkId(VMap[AtomicRMW->getValOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004255
4256 VMap[&I] = nextID;
4257
David Neto87846742018-04-11 17:36:22 -04004258 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
Neil Henning39672102017-09-29 14:33:13 +01004259 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004260 break;
4261 }
4262 case Instruction::Fence: {
4263 I.print(errs());
4264 llvm_unreachable("Unsupported instruction???");
4265 break;
4266 }
4267 case Instruction::Call: {
4268 CallInst *Call = dyn_cast<CallInst>(&I);
4269 Function *Callee = Call->getCalledFunction();
4270
Alan Baker202c8c72018-08-13 13:47:44 -04004271 if (Callee->getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004272 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
4273 // Generate an OpLoad
4274 SPIRVOperandList Ops;
4275 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004276
David Neto862b7d82018-06-14 18:48:37 -04004277 Ops << MkId(lookupType(Call->getType()->getPointerElementType()))
4278 << MkId(ResourceVarDeferredLoadCalls[Call]);
4279
4280 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
4281 SPIRVInstList.push_back(Inst);
4282 VMap[Call] = load_id;
4283 break;
4284
4285 } else {
4286 // This maps to an OpVariable we've already generated.
4287 // No code is generated for the call.
4288 }
4289 break;
Alan Baker202c8c72018-08-13 13:47:44 -04004290 } else if (Callee->getName().startswith(clspv::WorkgroupAccessorFunction())) {
4291 // Don't codegen an instruction here, but instead map this call directly
4292 // to the workgroup variable id.
4293 int spec_id = cast<ConstantInt>(Call->getOperand(0))->getSExtValue();
4294 const auto &info = LocalSpecIdInfoMap[spec_id];
4295 VMap[Call] = info.variable_id;
4296 break;
David Neto862b7d82018-06-14 18:48:37 -04004297 }
4298
4299 // Sampler initializers become a load of the corresponding sampler.
4300
4301 if (Callee->getName().equals("clspv.sampler.var.literal")) {
4302 // Map this to a load from the variable.
4303 const auto index_into_sampler_map =
4304 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4305
4306 // Generate an OpLoad
David Neto22f144c2017-06-12 14:26:21 -04004307 SPIRVOperandList Ops;
David Neto862b7d82018-06-14 18:48:37 -04004308 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004309
David Neto257c3892018-04-11 13:19:45 -04004310 Ops << MkId(lookupType(SamplerTy->getPointerElementType()))
David Neto862b7d82018-06-14 18:48:37 -04004311 << MkId(SamplerMapIndexToIDMap[index_into_sampler_map]);
David Neto22f144c2017-06-12 14:26:21 -04004312
David Neto862b7d82018-06-14 18:48:37 -04004313 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004314 SPIRVInstList.push_back(Inst);
David Neto862b7d82018-06-14 18:48:37 -04004315 VMap[Call] = load_id;
David Neto22f144c2017-06-12 14:26:21 -04004316 break;
4317 }
4318
4319 if (Callee->getName().startswith("spirv.atomic")) {
4320 spv::Op opcode = StringSwitch<spv::Op>(Callee->getName())
4321 .Case("spirv.atomic_add", spv::OpAtomicIAdd)
4322 .Case("spirv.atomic_sub", spv::OpAtomicISub)
4323 .Case("spirv.atomic_exchange", spv::OpAtomicExchange)
4324 .Case("spirv.atomic_inc", spv::OpAtomicIIncrement)
4325 .Case("spirv.atomic_dec", spv::OpAtomicIDecrement)
4326 .Case("spirv.atomic_compare_exchange",
4327 spv::OpAtomicCompareExchange)
4328 .Case("spirv.atomic_umin", spv::OpAtomicUMin)
4329 .Case("spirv.atomic_smin", spv::OpAtomicSMin)
4330 .Case("spirv.atomic_umax", spv::OpAtomicUMax)
4331 .Case("spirv.atomic_smax", spv::OpAtomicSMax)
4332 .Case("spirv.atomic_and", spv::OpAtomicAnd)
4333 .Case("spirv.atomic_or", spv::OpAtomicOr)
4334 .Case("spirv.atomic_xor", spv::OpAtomicXor)
4335 .Default(spv::OpNop);
4336
4337 //
4338 // Generate OpAtomic*.
4339 //
4340 SPIRVOperandList Ops;
4341
David Neto257c3892018-04-11 13:19:45 -04004342 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004343
4344 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004345 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004346 }
4347
4348 VMap[&I] = nextID;
4349
David Neto87846742018-04-11 17:36:22 -04004350 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004351 SPIRVInstList.push_back(Inst);
4352 break;
4353 }
4354
4355 if (Callee->getName().startswith("_Z3dot")) {
4356 // If the argument is a vector type, generate OpDot
4357 if (Call->getArgOperand(0)->getType()->isVectorTy()) {
4358 //
4359 // Generate OpDot.
4360 //
4361 SPIRVOperandList Ops;
4362
David Neto257c3892018-04-11 13:19:45 -04004363 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004364
4365 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004366 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004367 }
4368
4369 VMap[&I] = nextID;
4370
David Neto87846742018-04-11 17:36:22 -04004371 auto *Inst = new SPIRVInstruction(spv::OpDot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004372 SPIRVInstList.push_back(Inst);
4373 } else {
4374 //
4375 // Generate OpFMul.
4376 //
4377 SPIRVOperandList Ops;
4378
David Neto257c3892018-04-11 13:19:45 -04004379 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004380
4381 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004382 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004383 }
4384
4385 VMap[&I] = nextID;
4386
David Neto87846742018-04-11 17:36:22 -04004387 auto *Inst = new SPIRVInstruction(spv::OpFMul, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004388 SPIRVInstList.push_back(Inst);
4389 }
4390 break;
4391 }
4392
David Neto8505ebf2017-10-13 18:50:50 -04004393 if (Callee->getName().startswith("_Z4fmod")) {
4394 // OpenCL fmod(x,y) is x - y * trunc(x/y)
4395 // The sign for a non-zero result is taken from x.
4396 // (Try an example.)
4397 // So translate to OpFRem
4398
4399 SPIRVOperandList Ops;
4400
David Neto257c3892018-04-11 13:19:45 -04004401 Ops << MkId(lookupType(I.getType()));
David Neto8505ebf2017-10-13 18:50:50 -04004402
4403 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004404 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto8505ebf2017-10-13 18:50:50 -04004405 }
4406
4407 VMap[&I] = nextID;
4408
David Neto87846742018-04-11 17:36:22 -04004409 auto *Inst = new SPIRVInstruction(spv::OpFRem, nextID++, Ops);
David Neto8505ebf2017-10-13 18:50:50 -04004410 SPIRVInstList.push_back(Inst);
4411 break;
4412 }
4413
David Neto22f144c2017-06-12 14:26:21 -04004414 // spirv.store_null.* intrinsics become OpStore's.
4415 if (Callee->getName().startswith("spirv.store_null")) {
4416 //
4417 // Generate OpStore.
4418 //
4419
4420 // Ops[0] = Pointer ID
4421 // Ops[1] = Object ID
4422 // Ops[2] ... Ops[n]
4423 SPIRVOperandList Ops;
4424
4425 uint32_t PointerID = VMap[Call->getArgOperand(0)];
David Neto22f144c2017-06-12 14:26:21 -04004426 uint32_t ObjectID = VMap[Call->getArgOperand(1)];
David Neto257c3892018-04-11 13:19:45 -04004427 Ops << MkId(PointerID) << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04004428
David Neto87846742018-04-11 17:36:22 -04004429 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpStore, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004430
4431 break;
4432 }
4433
4434 // spirv.copy_memory.* intrinsics become OpMemoryMemory's.
4435 if (Callee->getName().startswith("spirv.copy_memory")) {
4436 //
4437 // Generate OpCopyMemory.
4438 //
4439
4440 // Ops[0] = Dst ID
4441 // Ops[1] = Src ID
4442 // Ops[2] = Memory Access
4443 // Ops[3] = Alignment
4444
4445 auto IsVolatile =
4446 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
4447
4448 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
4449 : spv::MemoryAccessMaskNone;
4450
4451 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
4452
4453 auto Alignment =
4454 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4455
David Neto257c3892018-04-11 13:19:45 -04004456 SPIRVOperandList Ops;
4457 Ops << MkId(VMap[Call->getArgOperand(0)])
4458 << MkId(VMap[Call->getArgOperand(1)]) << MkNum(MemoryAccess)
4459 << MkNum(static_cast<uint32_t>(Alignment));
David Neto22f144c2017-06-12 14:26:21 -04004460
David Neto87846742018-04-11 17:36:22 -04004461 auto *Inst = new SPIRVInstruction(spv::OpCopyMemory, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004462
4463 SPIRVInstList.push_back(Inst);
4464
4465 break;
4466 }
4467
4468 // Nothing to do for abs with uint. Map abs's operand ID to VMap for abs
4469 // with unit.
4470 if (Callee->getName().equals("_Z3absj") ||
4471 Callee->getName().equals("_Z3absDv2_j") ||
4472 Callee->getName().equals("_Z3absDv3_j") ||
4473 Callee->getName().equals("_Z3absDv4_j")) {
4474 VMap[&I] = VMap[Call->getOperand(0)];
4475 break;
4476 }
4477
4478 // barrier is converted to OpControlBarrier
4479 if (Callee->getName().equals("__spirv_control_barrier")) {
4480 //
4481 // Generate OpControlBarrier.
4482 //
4483 // Ops[0] = Execution Scope ID
4484 // Ops[1] = Memory Scope ID
4485 // Ops[2] = Memory Semantics ID
4486 //
4487 Value *ExecutionScope = Call->getArgOperand(0);
4488 Value *MemoryScope = Call->getArgOperand(1);
4489 Value *MemorySemantics = Call->getArgOperand(2);
4490
David Neto257c3892018-04-11 13:19:45 -04004491 SPIRVOperandList Ops;
4492 Ops << MkId(VMap[ExecutionScope]) << MkId(VMap[MemoryScope])
4493 << MkId(VMap[MemorySemantics]);
David Neto22f144c2017-06-12 14:26:21 -04004494
David Neto87846742018-04-11 17:36:22 -04004495 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpControlBarrier, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004496 break;
4497 }
4498
4499 // memory barrier is converted to OpMemoryBarrier
4500 if (Callee->getName().equals("__spirv_memory_barrier")) {
4501 //
4502 // Generate OpMemoryBarrier.
4503 //
4504 // Ops[0] = Memory Scope ID
4505 // Ops[1] = Memory Semantics ID
4506 //
4507 SPIRVOperandList Ops;
4508
David Neto257c3892018-04-11 13:19:45 -04004509 uint32_t MemoryScopeID = VMap[Call->getArgOperand(0)];
4510 uint32_t MemorySemanticsID = VMap[Call->getArgOperand(1)];
David Neto22f144c2017-06-12 14:26:21 -04004511
David Neto257c3892018-04-11 13:19:45 -04004512 Ops << MkId(MemoryScopeID) << MkId(MemorySemanticsID);
David Neto22f144c2017-06-12 14:26:21 -04004513
David Neto87846742018-04-11 17:36:22 -04004514 auto *Inst = new SPIRVInstruction(spv::OpMemoryBarrier, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004515 SPIRVInstList.push_back(Inst);
4516 break;
4517 }
4518
4519 // isinf is converted to OpIsInf
4520 if (Callee->getName().equals("__spirv_isinff") ||
4521 Callee->getName().equals("__spirv_isinfDv2_f") ||
4522 Callee->getName().equals("__spirv_isinfDv3_f") ||
4523 Callee->getName().equals("__spirv_isinfDv4_f")) {
4524 //
4525 // Generate OpIsInf.
4526 //
4527 // Ops[0] = Result Type ID
4528 // Ops[1] = X ID
4529 //
4530 SPIRVOperandList Ops;
4531
David Neto257c3892018-04-11 13:19:45 -04004532 Ops << MkId(lookupType(I.getType()))
4533 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004534
4535 VMap[&I] = nextID;
4536
David Neto87846742018-04-11 17:36:22 -04004537 auto *Inst = new SPIRVInstruction(spv::OpIsInf, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004538 SPIRVInstList.push_back(Inst);
4539 break;
4540 }
4541
4542 // isnan is converted to OpIsNan
4543 if (Callee->getName().equals("__spirv_isnanf") ||
4544 Callee->getName().equals("__spirv_isnanDv2_f") ||
4545 Callee->getName().equals("__spirv_isnanDv3_f") ||
4546 Callee->getName().equals("__spirv_isnanDv4_f")) {
4547 //
4548 // Generate OpIsInf.
4549 //
4550 // Ops[0] = Result Type ID
4551 // Ops[1] = X ID
4552 //
4553 SPIRVOperandList Ops;
4554
David Neto257c3892018-04-11 13:19:45 -04004555 Ops << MkId(lookupType(I.getType()))
4556 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004557
4558 VMap[&I] = nextID;
4559
David Neto87846742018-04-11 17:36:22 -04004560 auto *Inst = new SPIRVInstruction(spv::OpIsNan, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004561 SPIRVInstList.push_back(Inst);
4562 break;
4563 }
4564
4565 // all is converted to OpAll
4566 if (Callee->getName().equals("__spirv_allDv2_i") ||
4567 Callee->getName().equals("__spirv_allDv3_i") ||
4568 Callee->getName().equals("__spirv_allDv4_i")) {
4569 //
4570 // Generate OpAll.
4571 //
4572 // Ops[0] = Result Type ID
4573 // Ops[1] = Vector ID
4574 //
4575 SPIRVOperandList Ops;
4576
David Neto257c3892018-04-11 13:19:45 -04004577 Ops << MkId(lookupType(I.getType()))
4578 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004579
4580 VMap[&I] = nextID;
4581
David Neto87846742018-04-11 17:36:22 -04004582 auto *Inst = new SPIRVInstruction(spv::OpAll, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004583 SPIRVInstList.push_back(Inst);
4584 break;
4585 }
4586
4587 // any is converted to OpAny
4588 if (Callee->getName().equals("__spirv_anyDv2_i") ||
4589 Callee->getName().equals("__spirv_anyDv3_i") ||
4590 Callee->getName().equals("__spirv_anyDv4_i")) {
4591 //
4592 // Generate OpAny.
4593 //
4594 // Ops[0] = Result Type ID
4595 // Ops[1] = Vector ID
4596 //
4597 SPIRVOperandList Ops;
4598
David Neto257c3892018-04-11 13:19:45 -04004599 Ops << MkId(lookupType(I.getType()))
4600 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004601
4602 VMap[&I] = nextID;
4603
David Neto87846742018-04-11 17:36:22 -04004604 auto *Inst = new SPIRVInstruction(spv::OpAny, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004605 SPIRVInstList.push_back(Inst);
4606 break;
4607 }
4608
4609 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
4610 // Additionally, OpTypeSampledImage is generated.
4611 if (Callee->getName().equals(
4612 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
4613 Callee->getName().equals(
4614 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
4615 //
4616 // Generate OpSampledImage.
4617 //
4618 // Ops[0] = Result Type ID
4619 // Ops[1] = Image ID
4620 // Ops[2] = Sampler ID
4621 //
4622 SPIRVOperandList Ops;
4623
4624 Value *Image = Call->getArgOperand(0);
4625 Value *Sampler = Call->getArgOperand(1);
4626 Value *Coordinate = Call->getArgOperand(2);
4627
4628 TypeMapType &OpImageTypeMap = getImageTypeMap();
4629 Type *ImageTy = Image->getType()->getPointerElementType();
4630 uint32_t ImageTyID = OpImageTypeMap[ImageTy];
David Neto22f144c2017-06-12 14:26:21 -04004631 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004632 uint32_t SamplerID = VMap[Sampler];
David Neto257c3892018-04-11 13:19:45 -04004633
4634 Ops << MkId(ImageTyID) << MkId(ImageID) << MkId(SamplerID);
David Neto22f144c2017-06-12 14:26:21 -04004635
4636 uint32_t SampledImageID = nextID;
4637
David Neto87846742018-04-11 17:36:22 -04004638 auto *Inst = new SPIRVInstruction(spv::OpSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004639 SPIRVInstList.push_back(Inst);
4640
4641 //
4642 // Generate OpImageSampleExplicitLod.
4643 //
4644 // Ops[0] = Result Type ID
4645 // Ops[1] = Sampled Image ID
4646 // Ops[2] = Coordinate ID
4647 // Ops[3] = Image Operands Type ID
4648 // Ops[4] ... Ops[n] = Operands ID
4649 //
4650 Ops.clear();
4651
David Neto257c3892018-04-11 13:19:45 -04004652 Ops << MkId(lookupType(Call->getType())) << MkId(SampledImageID)
4653 << MkId(VMap[Coordinate]) << MkNum(spv::ImageOperandsLodMask);
David Neto22f144c2017-06-12 14:26:21 -04004654
4655 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
David Neto257c3892018-04-11 13:19:45 -04004656 Ops << MkId(VMap[CstFP0]);
David Neto22f144c2017-06-12 14:26:21 -04004657
4658 VMap[&I] = nextID;
4659
David Neto87846742018-04-11 17:36:22 -04004660 Inst = new SPIRVInstruction(spv::OpImageSampleExplicitLod, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004661 SPIRVInstList.push_back(Inst);
4662 break;
4663 }
4664
4665 // write_imagef is mapped to OpImageWrite.
4666 if (Callee->getName().equals(
4667 "_Z12write_imagef14ocl_image2d_woDv2_iDv4_f") ||
4668 Callee->getName().equals(
4669 "_Z12write_imagef14ocl_image3d_woDv4_iDv4_f")) {
4670 //
4671 // Generate OpImageWrite.
4672 //
4673 // Ops[0] = Image ID
4674 // Ops[1] = Coordinate ID
4675 // Ops[2] = Texel ID
4676 // Ops[3] = (Optional) Image Operands Type (Literal Number)
4677 // Ops[4] ... Ops[n] = (Optional) Operands ID
4678 //
4679 SPIRVOperandList Ops;
4680
4681 Value *Image = Call->getArgOperand(0);
4682 Value *Coordinate = Call->getArgOperand(1);
4683 Value *Texel = Call->getArgOperand(2);
4684
4685 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004686 uint32_t CoordinateID = VMap[Coordinate];
David Neto22f144c2017-06-12 14:26:21 -04004687 uint32_t TexelID = VMap[Texel];
David Neto257c3892018-04-11 13:19:45 -04004688 Ops << MkId(ImageID) << MkId(CoordinateID) << MkId(TexelID);
David Neto22f144c2017-06-12 14:26:21 -04004689
David Neto87846742018-04-11 17:36:22 -04004690 auto *Inst = new SPIRVInstruction(spv::OpImageWrite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004691 SPIRVInstList.push_back(Inst);
4692 break;
4693 }
4694
David Neto5c22a252018-03-15 16:07:41 -04004695 // get_image_width is mapped to OpImageQuerySize
4696 if (Callee->getName().equals("_Z15get_image_width14ocl_image2d_ro") ||
4697 Callee->getName().equals("_Z15get_image_width14ocl_image2d_wo") ||
4698 Callee->getName().equals("_Z16get_image_height14ocl_image2d_ro") ||
4699 Callee->getName().equals("_Z16get_image_height14ocl_image2d_wo")) {
4700 //
4701 // Generate OpImageQuerySize, then pull out the right component.
4702 // Assume 2D image for now.
4703 //
4704 // Ops[0] = Image ID
4705 //
4706 // %sizes = OpImageQuerySizes %uint2 %im
4707 // %result = OpCompositeExtract %uint %sizes 0-or-1
4708 SPIRVOperandList Ops;
4709
4710 // Implement:
4711 // %sizes = OpImageQuerySizes %uint2 %im
4712 uint32_t SizesTypeID =
4713 TypeMap[VectorType::get(Type::getInt32Ty(Context), 2)];
David Neto5c22a252018-03-15 16:07:41 -04004714 Value *Image = Call->getArgOperand(0);
4715 uint32_t ImageID = VMap[Image];
David Neto257c3892018-04-11 13:19:45 -04004716 Ops << MkId(SizesTypeID) << MkId(ImageID);
David Neto5c22a252018-03-15 16:07:41 -04004717
4718 uint32_t SizesID = nextID++;
David Neto87846742018-04-11 17:36:22 -04004719 auto *QueryInst =
4720 new SPIRVInstruction(spv::OpImageQuerySize, SizesID, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004721 SPIRVInstList.push_back(QueryInst);
4722
4723 // Reset value map entry since we generated an intermediate instruction.
4724 VMap[&I] = nextID;
4725
4726 // Implement:
4727 // %result = OpCompositeExtract %uint %sizes 0-or-1
4728 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004729 Ops << MkId(TypeMap[I.getType()]) << MkId(SizesID);
David Neto5c22a252018-03-15 16:07:41 -04004730
4731 uint32_t component = Callee->getName().contains("height") ? 1 : 0;
David Neto257c3892018-04-11 13:19:45 -04004732 Ops << MkNum(component);
David Neto5c22a252018-03-15 16:07:41 -04004733
David Neto87846742018-04-11 17:36:22 -04004734 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004735 SPIRVInstList.push_back(Inst);
4736 break;
4737 }
4738
David Neto22f144c2017-06-12 14:26:21 -04004739 // Call instrucion is deferred because it needs function's ID. Record
4740 // slot's location on SPIRVInstructionList.
4741 DeferredInsts.push_back(
4742 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4743
David Neto3fbb4072017-10-16 11:28:14 -04004744 // Check whether the implementation of this call uses an extended
4745 // instruction plus one more value-producing instruction. If so, then
4746 // reserve the id for the extra value-producing slot.
4747 glsl::ExtInst EInst = getIndirectExtInstEnum(Callee->getName());
4748 if (EInst != kGlslExtInstBad) {
4749 // Reserve a spot for the extra value.
David Neto4d02a532017-09-17 12:57:44 -04004750 // Increase nextID.
David Neto22f144c2017-06-12 14:26:21 -04004751 VMap[&I] = nextID;
4752 nextID++;
4753 }
4754 break;
4755 }
4756 case Instruction::Ret: {
4757 unsigned NumOps = I.getNumOperands();
4758 if (NumOps == 0) {
4759 //
4760 // Generate OpReturn.
4761 //
David Neto87846742018-04-11 17:36:22 -04004762 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpReturn, {}));
David Neto22f144c2017-06-12 14:26:21 -04004763 } else {
4764 //
4765 // Generate OpReturnValue.
4766 //
4767
4768 // Ops[0] = Return Value ID
4769 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004770
4771 Ops << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004772
David Neto87846742018-04-11 17:36:22 -04004773 auto *Inst = new SPIRVInstruction(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004774 SPIRVInstList.push_back(Inst);
4775 break;
4776 }
4777 break;
4778 }
4779 }
4780}
4781
4782void SPIRVProducerPass::GenerateFuncEpilogue() {
4783 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4784
4785 //
4786 // Generate OpFunctionEnd
4787 //
4788
David Neto87846742018-04-11 17:36:22 -04004789 auto *Inst = new SPIRVInstruction(spv::OpFunctionEnd, {});
David Neto22f144c2017-06-12 14:26:21 -04004790 SPIRVInstList.push_back(Inst);
4791}
4792
4793bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
4794 LLVMContext &Context = Ty->getContext();
4795 if (Ty->isVectorTy()) {
4796 if (Ty->getVectorElementType() == Type::getInt8Ty(Context) &&
4797 Ty->getVectorNumElements() == 4) {
4798 return true;
4799 }
4800 }
4801
4802 return false;
4803}
4804
David Neto257c3892018-04-11 13:19:45 -04004805uint32_t SPIRVProducerPass::GetI32Zero() {
4806 if (0 == constant_i32_zero_id_) {
4807 llvm_unreachable("Requesting a 32-bit integer constant but it is not "
4808 "defined in the SPIR-V module");
4809 }
4810 return constant_i32_zero_id_;
4811}
4812
David Neto22f144c2017-06-12 14:26:21 -04004813void SPIRVProducerPass::HandleDeferredInstruction() {
4814 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4815 ValueMapType &VMap = getValueMap();
4816 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4817
4818 for (auto DeferredInst = DeferredInsts.rbegin();
4819 DeferredInst != DeferredInsts.rend(); ++DeferredInst) {
4820 Value *Inst = std::get<0>(*DeferredInst);
4821 SPIRVInstructionList::iterator InsertPoint = ++std::get<1>(*DeferredInst);
4822 if (InsertPoint != SPIRVInstList.end()) {
4823 while ((*InsertPoint)->getOpcode() == spv::OpPhi) {
4824 ++InsertPoint;
4825 }
4826 }
4827
4828 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
4829 // Check whether basic block, which has this branch instruction, is loop
4830 // header or not. If it is loop header, generate OpLoopMerge and
4831 // OpBranchConditional.
4832 Function *Func = Br->getParent()->getParent();
4833 DominatorTree &DT =
4834 getAnalysis<DominatorTreeWrapperPass>(*Func).getDomTree();
4835 const LoopInfo &LI =
4836 getAnalysis<LoopInfoWrapperPass>(*Func).getLoopInfo();
4837
4838 BasicBlock *BrBB = Br->getParent();
4839 if (LI.isLoopHeader(BrBB)) {
4840 Value *ContinueBB = nullptr;
4841 Value *MergeBB = nullptr;
4842
4843 Loop *L = LI.getLoopFor(BrBB);
4844 MergeBB = L->getExitBlock();
4845 if (!MergeBB) {
4846 // StructurizeCFG pass converts CFG into triangle shape and the cfg
4847 // has regions with single entry/exit. As a result, loop should not
4848 // have multiple exits.
4849 llvm_unreachable("Loop has multiple exits???");
4850 }
4851
4852 if (L->isLoopLatch(BrBB)) {
4853 ContinueBB = BrBB;
4854 } else {
4855 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
4856 // block.
4857 BasicBlock *Header = L->getHeader();
4858 BasicBlock *Latch = L->getLoopLatch();
4859 for (BasicBlock *BB : L->blocks()) {
4860 if (BB == Header) {
4861 continue;
4862 }
4863
4864 // Check whether block dominates block with back-edge.
4865 if (DT.dominates(BB, Latch)) {
4866 ContinueBB = BB;
4867 }
4868 }
4869
4870 if (!ContinueBB) {
4871 llvm_unreachable("Wrong continue block from loop");
4872 }
4873 }
4874
4875 //
4876 // Generate OpLoopMerge.
4877 //
4878 // Ops[0] = Merge Block ID
4879 // Ops[1] = Continue Target ID
4880 // Ops[2] = Selection Control
4881 SPIRVOperandList Ops;
4882
4883 // StructurizeCFG pass already manipulated CFG. Just use false block of
4884 // branch instruction as merge block.
4885 uint32_t MergeBBID = VMap[MergeBB];
David Neto22f144c2017-06-12 14:26:21 -04004886 uint32_t ContinueBBID = VMap[ContinueBB];
David Neto257c3892018-04-11 13:19:45 -04004887 Ops << MkId(MergeBBID) << MkId(ContinueBBID)
4888 << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004889
David Neto87846742018-04-11 17:36:22 -04004890 auto *MergeInst = new SPIRVInstruction(spv::OpLoopMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004891 SPIRVInstList.insert(InsertPoint, MergeInst);
4892
4893 } else if (Br->isConditional()) {
4894 bool HasBackEdge = false;
4895
4896 for (unsigned i = 0; i < Br->getNumSuccessors(); i++) {
4897 if (LI.isLoopHeader(Br->getSuccessor(i))) {
4898 HasBackEdge = true;
4899 }
4900 }
4901 if (!HasBackEdge) {
4902 //
4903 // Generate OpSelectionMerge.
4904 //
4905 // Ops[0] = Merge Block ID
4906 // Ops[1] = Selection Control
4907 SPIRVOperandList Ops;
4908
4909 // StructurizeCFG pass already manipulated CFG. Just use false block
4910 // of branch instruction as merge block.
4911 uint32_t MergeBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004912 Ops << MkId(MergeBBID) << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004913
David Neto87846742018-04-11 17:36:22 -04004914 auto *MergeInst = new SPIRVInstruction(spv::OpSelectionMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004915 SPIRVInstList.insert(InsertPoint, MergeInst);
4916 }
4917 }
4918
4919 if (Br->isConditional()) {
4920 //
4921 // Generate OpBranchConditional.
4922 //
4923 // Ops[0] = Condition ID
4924 // Ops[1] = True Label ID
4925 // Ops[2] = False Label ID
4926 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
4927 SPIRVOperandList Ops;
4928
4929 uint32_t CondID = VMap[Br->getCondition()];
David Neto22f144c2017-06-12 14:26:21 -04004930 uint32_t TrueBBID = VMap[Br->getSuccessor(0)];
David Neto22f144c2017-06-12 14:26:21 -04004931 uint32_t FalseBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004932
4933 Ops << MkId(CondID) << MkId(TrueBBID) << MkId(FalseBBID);
David Neto22f144c2017-06-12 14:26:21 -04004934
David Neto87846742018-04-11 17:36:22 -04004935 auto *BrInst = new SPIRVInstruction(spv::OpBranchConditional, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004936 SPIRVInstList.insert(InsertPoint, BrInst);
4937 } else {
4938 //
4939 // Generate OpBranch.
4940 //
4941 // Ops[0] = Target Label ID
4942 SPIRVOperandList Ops;
4943
4944 uint32_t TargetID = VMap[Br->getSuccessor(0)];
David Neto257c3892018-04-11 13:19:45 -04004945 Ops << MkId(TargetID);
David Neto22f144c2017-06-12 14:26:21 -04004946
David Neto87846742018-04-11 17:36:22 -04004947 SPIRVInstList.insert(InsertPoint,
4948 new SPIRVInstruction(spv::OpBranch, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004949 }
4950 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
4951 //
4952 // Generate OpPhi.
4953 //
4954 // Ops[0] = Result Type ID
4955 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
4956 SPIRVOperandList Ops;
4957
David Neto257c3892018-04-11 13:19:45 -04004958 Ops << MkId(lookupType(PHI->getType()));
David Neto22f144c2017-06-12 14:26:21 -04004959
David Neto22f144c2017-06-12 14:26:21 -04004960 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
4961 uint32_t VarID = VMap[PHI->getIncomingValue(i)];
David Neto22f144c2017-06-12 14:26:21 -04004962 uint32_t ParentID = VMap[PHI->getIncomingBlock(i)];
David Neto257c3892018-04-11 13:19:45 -04004963 Ops << MkId(VarID) << MkId(ParentID);
David Neto22f144c2017-06-12 14:26:21 -04004964 }
4965
4966 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04004967 InsertPoint,
4968 new SPIRVInstruction(spv::OpPhi, std::get<2>(*DeferredInst), Ops));
David Neto22f144c2017-06-12 14:26:21 -04004969 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
4970 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04004971 auto callee_name = Callee->getName();
4972 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04004973
4974 if (EInst) {
4975 uint32_t &ExtInstImportID = getOpExtInstImportID();
4976
4977 //
4978 // Generate OpExtInst.
4979 //
4980
4981 // Ops[0] = Result Type ID
4982 // Ops[1] = Set ID (OpExtInstImport ID)
4983 // Ops[2] = Instruction Number (Literal Number)
4984 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
4985 SPIRVOperandList Ops;
4986
David Neto862b7d82018-06-14 18:48:37 -04004987 Ops << MkId(lookupType(Call->getType())) << MkId(ExtInstImportID)
4988 << MkNum(EInst);
David Neto22f144c2017-06-12 14:26:21 -04004989
David Neto22f144c2017-06-12 14:26:21 -04004990 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
4991 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004992 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004993 }
4994
David Neto87846742018-04-11 17:36:22 -04004995 auto *ExtInst = new SPIRVInstruction(spv::OpExtInst,
4996 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04004997 SPIRVInstList.insert(InsertPoint, ExtInst);
4998
David Neto3fbb4072017-10-16 11:28:14 -04004999 const auto IndirectExtInst = getIndirectExtInstEnum(callee_name);
5000 if (IndirectExtInst != kGlslExtInstBad) {
5001 // Generate one more instruction that uses the result of the extended
5002 // instruction. Its result id is one more than the id of the
5003 // extended instruction.
David Neto22f144c2017-06-12 14:26:21 -04005004 LLVMContext &Context =
5005 Call->getParent()->getParent()->getParent()->getContext();
David Neto22f144c2017-06-12 14:26:21 -04005006
David Neto3fbb4072017-10-16 11:28:14 -04005007 auto generate_extra_inst = [this, &Context, &Call, &DeferredInst,
5008 &VMap, &SPIRVInstList, &InsertPoint](
5009 spv::Op opcode, Constant *constant) {
5010 //
5011 // Generate instruction like:
5012 // result = opcode constant <extinst-result>
5013 //
5014 // Ops[0] = Result Type ID
5015 // Ops[1] = Operand 0 ;; the constant, suitably splatted
5016 // Ops[2] = Operand 1 ;; the result of the extended instruction
5017 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04005018
David Neto3fbb4072017-10-16 11:28:14 -04005019 Type *resultTy = Call->getType();
David Neto257c3892018-04-11 13:19:45 -04005020 Ops << MkId(lookupType(resultTy));
David Neto3fbb4072017-10-16 11:28:14 -04005021
5022 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
5023 constant = ConstantVector::getSplat(
5024 static_cast<unsigned>(vectorTy->getNumElements()), constant);
5025 }
David Neto257c3892018-04-11 13:19:45 -04005026 Ops << MkId(VMap[constant]) << MkId(std::get<2>(*DeferredInst));
David Neto3fbb4072017-10-16 11:28:14 -04005027
5028 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005029 InsertPoint, new SPIRVInstruction(
5030 opcode, std::get<2>(*DeferredInst) + 1, Ops));
David Neto3fbb4072017-10-16 11:28:14 -04005031 };
5032
5033 switch (IndirectExtInst) {
5034 case glsl::ExtInstFindUMsb: // Implementing clz
5035 generate_extra_inst(
5036 spv::OpISub, ConstantInt::get(Type::getInt32Ty(Context), 31));
5037 break;
5038 case glsl::ExtInstAcos: // Implementing acospi
5039 case glsl::ExtInstAsin: // Implementing asinpi
5040 case glsl::ExtInstAtan2: // Implementing atan2pi
5041 generate_extra_inst(
5042 spv::OpFMul,
5043 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
5044 break;
5045
5046 default:
5047 assert(false && "internally inconsistent");
David Neto4d02a532017-09-17 12:57:44 -04005048 }
David Neto22f144c2017-06-12 14:26:21 -04005049 }
David Neto3fbb4072017-10-16 11:28:14 -04005050
David Neto862b7d82018-06-14 18:48:37 -04005051 } else if (callee_name.equals("_Z8popcounti") ||
5052 callee_name.equals("_Z8popcountj") ||
5053 callee_name.equals("_Z8popcountDv2_i") ||
5054 callee_name.equals("_Z8popcountDv3_i") ||
5055 callee_name.equals("_Z8popcountDv4_i") ||
5056 callee_name.equals("_Z8popcountDv2_j") ||
5057 callee_name.equals("_Z8popcountDv3_j") ||
5058 callee_name.equals("_Z8popcountDv4_j")) {
David Neto22f144c2017-06-12 14:26:21 -04005059 //
5060 // Generate OpBitCount
5061 //
5062 // Ops[0] = Result Type ID
5063 // Ops[1] = Base ID
David Neto257c3892018-04-11 13:19:45 -04005064 SPIRVOperandList Ops;
5065 Ops << MkId(lookupType(Call->getType()))
5066 << MkId(VMap[Call->getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04005067
5068 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005069 InsertPoint, new SPIRVInstruction(spv::OpBitCount,
David Neto22f144c2017-06-12 14:26:21 -04005070 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005071
David Neto862b7d82018-06-14 18:48:37 -04005072 } else if (callee_name.startswith(kCompositeConstructFunctionPrefix)) {
David Netoab03f432017-11-03 17:00:44 -04005073
5074 // Generate an OpCompositeConstruct
5075 SPIRVOperandList Ops;
5076
5077 // The result type.
David Neto257c3892018-04-11 13:19:45 -04005078 Ops << MkId(lookupType(Call->getType()));
David Netoab03f432017-11-03 17:00:44 -04005079
5080 for (Use &use : Call->arg_operands()) {
David Neto257c3892018-04-11 13:19:45 -04005081 Ops << MkId(VMap[use.get()]);
David Netoab03f432017-11-03 17:00:44 -04005082 }
5083
5084 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005085 InsertPoint, new SPIRVInstruction(spv::OpCompositeConstruct,
5086 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005087
Alan Baker202c8c72018-08-13 13:47:44 -04005088 } else if (callee_name.startswith(clspv::ResourceAccessorFunction())) {
5089
5090 // We have already mapped the call's result value to an ID.
5091 // Don't generate any code now.
5092
5093 } else if (callee_name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04005094
5095 // We have already mapped the call's result value to an ID.
5096 // Don't generate any code now.
5097
David Neto22f144c2017-06-12 14:26:21 -04005098 } else {
5099 //
5100 // Generate OpFunctionCall.
5101 //
5102
5103 // Ops[0] = Result Type ID
5104 // Ops[1] = Callee Function ID
5105 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
5106 SPIRVOperandList Ops;
5107
David Neto862b7d82018-06-14 18:48:37 -04005108 Ops << MkId(lookupType(Call->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005109
5110 uint32_t CalleeID = VMap[Callee];
David Neto43568eb2017-10-13 18:25:25 -04005111 if (CalleeID == 0) {
5112 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04005113 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04005114 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
5115 // causes an infinite loop. Instead, go ahead and generate
5116 // the bad function call. A validator will catch the 0-Id.
5117 // llvm_unreachable("Can't translate function call");
5118 }
David Neto22f144c2017-06-12 14:26:21 -04005119
David Neto257c3892018-04-11 13:19:45 -04005120 Ops << MkId(CalleeID);
David Neto22f144c2017-06-12 14:26:21 -04005121
David Neto22f144c2017-06-12 14:26:21 -04005122 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5123 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04005124 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04005125 }
5126
David Neto87846742018-04-11 17:36:22 -04005127 auto *CallInst = new SPIRVInstruction(spv::OpFunctionCall,
5128 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005129 SPIRVInstList.insert(InsertPoint, CallInst);
5130 }
5131 }
5132 }
5133}
5134
David Neto1a1a0582017-07-07 12:01:44 -04005135void SPIRVProducerPass::HandleDeferredDecorations(const DataLayout &DL) {
Alan Baker202c8c72018-08-13 13:47:44 -04005136 if (getTypesNeedingArrayStride().empty() && LocalArgSpecIds.empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04005137 return;
David Netoc6f3ab22018-04-06 18:02:31 -04005138 }
David Neto1a1a0582017-07-07 12:01:44 -04005139
5140 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto1a1a0582017-07-07 12:01:44 -04005141
5142 // Find an iterator pointing just past the last decoration.
5143 bool seen_decorations = false;
5144 auto DecoInsertPoint =
5145 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
5146 [&seen_decorations](SPIRVInstruction *Inst) -> bool {
5147 const bool is_decoration =
5148 Inst->getOpcode() == spv::OpDecorate ||
5149 Inst->getOpcode() == spv::OpMemberDecorate;
5150 if (is_decoration) {
5151 seen_decorations = true;
5152 return false;
5153 } else {
5154 return seen_decorations;
5155 }
5156 });
5157
David Netoc6f3ab22018-04-06 18:02:31 -04005158 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
5159 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07005160 for (auto *type : getTypesNeedingArrayStride()) {
5161 Type *elemTy = nullptr;
5162 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
5163 elemTy = ptrTy->getElementType();
5164 } else if (auto* arrayTy = dyn_cast<ArrayType>(type)) {
5165 elemTy = arrayTy->getArrayElementType();
5166 } else if (auto* seqTy = dyn_cast<SequentialType>(type)) {
5167 elemTy = seqTy->getSequentialElementType();
5168 } else {
5169 errs() << "Unhandled strided type " << *type << "\n";
5170 llvm_unreachable("Unhandled strided type");
5171 }
David Neto1a1a0582017-07-07 12:01:44 -04005172
5173 // Ops[0] = Target ID
5174 // Ops[1] = Decoration (ArrayStride)
5175 // Ops[2] = Stride number (Literal Number)
5176 SPIRVOperandList Ops;
5177
David Neto85082642018-03-24 06:55:20 -07005178 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Neil Henning39672102017-09-29 14:33:13 +01005179 const uint32_t stride = static_cast<uint32_t>(DL.getTypeAllocSize(elemTy));
David Neto257c3892018-04-11 13:19:45 -04005180
5181 Ops << MkId(lookupType(type)) << MkNum(spv::DecorationArrayStride)
5182 << MkNum(stride);
David Neto1a1a0582017-07-07 12:01:44 -04005183
David Neto87846742018-04-11 17:36:22 -04005184 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto1a1a0582017-07-07 12:01:44 -04005185 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
5186 }
David Netoc6f3ab22018-04-06 18:02:31 -04005187
5188 // Emit SpecId decorations targeting the array size value.
Alan Baker202c8c72018-08-13 13:47:44 -04005189 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
5190 ++spec_id) {
5191 LocalArgInfo& arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04005192 SPIRVOperandList Ops;
5193 Ops << MkId(arg_info.array_size_id) << MkNum(spv::DecorationSpecId)
5194 << MkNum(arg_info.spec_id);
5195 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04005196 new SPIRVInstruction(spv::OpDecorate, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04005197 }
David Neto1a1a0582017-07-07 12:01:44 -04005198}
5199
David Neto22f144c2017-06-12 14:26:21 -04005200glsl::ExtInst SPIRVProducerPass::getExtInstEnum(StringRef Name) {
5201 return StringSwitch<glsl::ExtInst>(Name)
5202 .Case("_Z3absi", glsl::ExtInst::ExtInstSAbs)
5203 .Case("_Z3absDv2_i", glsl::ExtInst::ExtInstSAbs)
5204 .Case("_Z3absDv3_i", glsl::ExtInst::ExtInstSAbs)
5205 .Case("_Z3absDv4_i", glsl::ExtInst::ExtInstSAbs)
5206 .Case("_Z5clampiii", glsl::ExtInst::ExtInstSClamp)
5207 .Case("_Z5clampDv2_iS_S_", glsl::ExtInst::ExtInstSClamp)
5208 .Case("_Z5clampDv3_iS_S_", glsl::ExtInst::ExtInstSClamp)
5209 .Case("_Z5clampDv4_iS_S_", glsl::ExtInst::ExtInstSClamp)
5210 .Case("_Z5clampjjj", glsl::ExtInst::ExtInstUClamp)
5211 .Case("_Z5clampDv2_jS_S_", glsl::ExtInst::ExtInstUClamp)
5212 .Case("_Z5clampDv3_jS_S_", glsl::ExtInst::ExtInstUClamp)
5213 .Case("_Z5clampDv4_jS_S_", glsl::ExtInst::ExtInstUClamp)
5214 .Case("_Z5clampfff", glsl::ExtInst::ExtInstFClamp)
5215 .Case("_Z5clampDv2_fS_S_", glsl::ExtInst::ExtInstFClamp)
5216 .Case("_Z5clampDv3_fS_S_", glsl::ExtInst::ExtInstFClamp)
5217 .Case("_Z5clampDv4_fS_S_", glsl::ExtInst::ExtInstFClamp)
David Neto22f144c2017-06-12 14:26:21 -04005218 .Case("_Z3maxii", glsl::ExtInst::ExtInstSMax)
5219 .Case("_Z3maxDv2_iS_", glsl::ExtInst::ExtInstSMax)
5220 .Case("_Z3maxDv3_iS_", glsl::ExtInst::ExtInstSMax)
5221 .Case("_Z3maxDv4_iS_", glsl::ExtInst::ExtInstSMax)
5222 .Case("_Z3maxjj", glsl::ExtInst::ExtInstUMax)
5223 .Case("_Z3maxDv2_jS_", glsl::ExtInst::ExtInstUMax)
5224 .Case("_Z3maxDv3_jS_", glsl::ExtInst::ExtInstUMax)
5225 .Case("_Z3maxDv4_jS_", glsl::ExtInst::ExtInstUMax)
5226 .Case("_Z3maxff", glsl::ExtInst::ExtInstFMax)
5227 .Case("_Z3maxDv2_fS_", glsl::ExtInst::ExtInstFMax)
5228 .Case("_Z3maxDv3_fS_", glsl::ExtInst::ExtInstFMax)
5229 .Case("_Z3maxDv4_fS_", glsl::ExtInst::ExtInstFMax)
5230 .StartsWith("_Z4fmax", glsl::ExtInst::ExtInstFMax)
5231 .Case("_Z3minii", glsl::ExtInst::ExtInstSMin)
5232 .Case("_Z3minDv2_iS_", glsl::ExtInst::ExtInstSMin)
5233 .Case("_Z3minDv3_iS_", glsl::ExtInst::ExtInstSMin)
5234 .Case("_Z3minDv4_iS_", glsl::ExtInst::ExtInstSMin)
5235 .Case("_Z3minjj", glsl::ExtInst::ExtInstUMin)
5236 .Case("_Z3minDv2_jS_", glsl::ExtInst::ExtInstUMin)
5237 .Case("_Z3minDv3_jS_", glsl::ExtInst::ExtInstUMin)
5238 .Case("_Z3minDv4_jS_", glsl::ExtInst::ExtInstUMin)
5239 .Case("_Z3minff", glsl::ExtInst::ExtInstFMin)
5240 .Case("_Z3minDv2_fS_", glsl::ExtInst::ExtInstFMin)
5241 .Case("_Z3minDv3_fS_", glsl::ExtInst::ExtInstFMin)
5242 .Case("_Z3minDv4_fS_", glsl::ExtInst::ExtInstFMin)
5243 .StartsWith("_Z4fmin", glsl::ExtInst::ExtInstFMin)
5244 .StartsWith("_Z7degrees", glsl::ExtInst::ExtInstDegrees)
5245 .StartsWith("_Z7radians", glsl::ExtInst::ExtInstRadians)
5246 .StartsWith("_Z3mix", glsl::ExtInst::ExtInstFMix)
5247 .StartsWith("_Z4acos", glsl::ExtInst::ExtInstAcos)
5248 .StartsWith("_Z5acosh", glsl::ExtInst::ExtInstAcosh)
5249 .StartsWith("_Z4asin", glsl::ExtInst::ExtInstAsin)
5250 .StartsWith("_Z5asinh", glsl::ExtInst::ExtInstAsinh)
5251 .StartsWith("_Z4atan", glsl::ExtInst::ExtInstAtan)
5252 .StartsWith("_Z5atan2", glsl::ExtInst::ExtInstAtan2)
5253 .StartsWith("_Z5atanh", glsl::ExtInst::ExtInstAtanh)
5254 .StartsWith("_Z4ceil", glsl::ExtInst::ExtInstCeil)
5255 .StartsWith("_Z3sin", glsl::ExtInst::ExtInstSin)
5256 .StartsWith("_Z4sinh", glsl::ExtInst::ExtInstSinh)
5257 .StartsWith("_Z8half_sin", glsl::ExtInst::ExtInstSin)
5258 .StartsWith("_Z10native_sin", glsl::ExtInst::ExtInstSin)
5259 .StartsWith("_Z3cos", glsl::ExtInst::ExtInstCos)
5260 .StartsWith("_Z4cosh", glsl::ExtInst::ExtInstCosh)
5261 .StartsWith("_Z8half_cos", glsl::ExtInst::ExtInstCos)
5262 .StartsWith("_Z10native_cos", glsl::ExtInst::ExtInstCos)
5263 .StartsWith("_Z3tan", glsl::ExtInst::ExtInstTan)
5264 .StartsWith("_Z4tanh", glsl::ExtInst::ExtInstTanh)
5265 .StartsWith("_Z8half_tan", glsl::ExtInst::ExtInstTan)
5266 .StartsWith("_Z10native_tan", glsl::ExtInst::ExtInstTan)
5267 .StartsWith("_Z3exp", glsl::ExtInst::ExtInstExp)
5268 .StartsWith("_Z8half_exp", glsl::ExtInst::ExtInstExp)
5269 .StartsWith("_Z10native_exp", glsl::ExtInst::ExtInstExp)
5270 .StartsWith("_Z4exp2", glsl::ExtInst::ExtInstExp2)
5271 .StartsWith("_Z9half_exp2", glsl::ExtInst::ExtInstExp2)
5272 .StartsWith("_Z11native_exp2", glsl::ExtInst::ExtInstExp2)
5273 .StartsWith("_Z3log", glsl::ExtInst::ExtInstLog)
5274 .StartsWith("_Z8half_log", glsl::ExtInst::ExtInstLog)
5275 .StartsWith("_Z10native_log", glsl::ExtInst::ExtInstLog)
5276 .StartsWith("_Z4log2", glsl::ExtInst::ExtInstLog2)
5277 .StartsWith("_Z9half_log2", glsl::ExtInst::ExtInstLog2)
5278 .StartsWith("_Z11native_log2", glsl::ExtInst::ExtInstLog2)
5279 .StartsWith("_Z4fabs", glsl::ExtInst::ExtInstFAbs)
5280 .StartsWith("_Z5floor", glsl::ExtInst::ExtInstFloor)
5281 .StartsWith("_Z5ldexp", glsl::ExtInst::ExtInstLdexp)
5282 .StartsWith("_Z3pow", glsl::ExtInst::ExtInstPow)
5283 .StartsWith("_Z4powr", glsl::ExtInst::ExtInstPow)
5284 .StartsWith("_Z9half_powr", glsl::ExtInst::ExtInstPow)
5285 .StartsWith("_Z11native_powr", glsl::ExtInst::ExtInstPow)
5286 .StartsWith("_Z5round", glsl::ExtInst::ExtInstRound)
5287 .StartsWith("_Z4sqrt", glsl::ExtInst::ExtInstSqrt)
5288 .StartsWith("_Z9half_sqrt", glsl::ExtInst::ExtInstSqrt)
5289 .StartsWith("_Z11native_sqrt", glsl::ExtInst::ExtInstSqrt)
5290 .StartsWith("_Z5rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5291 .StartsWith("_Z10half_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5292 .StartsWith("_Z12native_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5293 .StartsWith("_Z5trunc", glsl::ExtInst::ExtInstTrunc)
5294 .StartsWith("_Z5frexp", glsl::ExtInst::ExtInstFrexp)
5295 .StartsWith("_Z4sign", glsl::ExtInst::ExtInstFSign)
5296 .StartsWith("_Z6length", glsl::ExtInst::ExtInstLength)
5297 .StartsWith("_Z8distance", glsl::ExtInst::ExtInstDistance)
David Netoe9a03512017-10-16 10:08:27 -04005298 .StartsWith("_Z4step", glsl::ExtInst::ExtInstStep)
David Neto22f144c2017-06-12 14:26:21 -04005299 .Case("_Z5crossDv3_fS_", glsl::ExtInst::ExtInstCross)
5300 .StartsWith("_Z9normalize", glsl::ExtInst::ExtInstNormalize)
5301 .StartsWith("llvm.fmuladd.", glsl::ExtInst::ExtInstFma)
5302 .Case("spirv.unpack.v2f16", glsl::ExtInst::ExtInstUnpackHalf2x16)
5303 .Case("spirv.pack.v2f16", glsl::ExtInst::ExtInstPackHalf2x16)
David Neto62653202017-10-16 19:05:18 -04005304 .Case("clspv.fract.f", glsl::ExtInst::ExtInstFract)
5305 .Case("clspv.fract.v2f", glsl::ExtInst::ExtInstFract)
5306 .Case("clspv.fract.v3f", glsl::ExtInst::ExtInstFract)
5307 .Case("clspv.fract.v4f", glsl::ExtInst::ExtInstFract)
David Neto3fbb4072017-10-16 11:28:14 -04005308 .Default(kGlslExtInstBad);
5309}
5310
5311glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(StringRef Name) {
5312 // Check indirect cases.
5313 return StringSwitch<glsl::ExtInst>(Name)
5314 .StartsWith("_Z3clz", glsl::ExtInst::ExtInstFindUMsb)
5315 // Use exact match on float arg because these need a multiply
5316 // of a constant of the right floating point type.
5317 .Case("_Z6acospif", glsl::ExtInst::ExtInstAcos)
5318 .Case("_Z6acospiDv2_f", glsl::ExtInst::ExtInstAcos)
5319 .Case("_Z6acospiDv3_f", glsl::ExtInst::ExtInstAcos)
5320 .Case("_Z6acospiDv4_f", glsl::ExtInst::ExtInstAcos)
5321 .Case("_Z6asinpif", glsl::ExtInst::ExtInstAsin)
5322 .Case("_Z6asinpiDv2_f", glsl::ExtInst::ExtInstAsin)
5323 .Case("_Z6asinpiDv3_f", glsl::ExtInst::ExtInstAsin)
5324 .Case("_Z6asinpiDv4_f", glsl::ExtInst::ExtInstAsin)
5325 .Case("_Z7atan2piff", glsl::ExtInst::ExtInstAtan2)
5326 .Case("_Z7atan2piDv2_fS_", glsl::ExtInst::ExtInstAtan2)
5327 .Case("_Z7atan2piDv3_fS_", glsl::ExtInst::ExtInstAtan2)
5328 .Case("_Z7atan2piDv4_fS_", glsl::ExtInst::ExtInstAtan2)
5329 .Default(kGlslExtInstBad);
5330}
5331
5332glsl::ExtInst SPIRVProducerPass::getDirectOrIndirectExtInstEnum(StringRef Name) {
5333 auto direct = getExtInstEnum(Name);
5334 if (direct != kGlslExtInstBad)
5335 return direct;
5336 return getIndirectExtInstEnum(Name);
David Neto22f144c2017-06-12 14:26:21 -04005337}
5338
5339void SPIRVProducerPass::PrintResID(SPIRVInstruction *Inst) {
5340 out << "%" << Inst->getResultID();
5341}
5342
5343void SPIRVProducerPass::PrintOpcode(SPIRVInstruction *Inst) {
5344 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5345 out << "\t" << spv::getOpName(Opcode);
5346}
5347
5348void SPIRVProducerPass::PrintOperand(SPIRVOperand *Op) {
5349 SPIRVOperandType OpTy = Op->getType();
5350 switch (OpTy) {
5351 default: {
5352 llvm_unreachable("Unsupported SPIRV Operand Type???");
5353 break;
5354 }
5355 case SPIRVOperandType::NUMBERID: {
5356 out << "%" << Op->getNumID();
5357 break;
5358 }
5359 case SPIRVOperandType::LITERAL_STRING: {
5360 out << "\"" << Op->getLiteralStr() << "\"";
5361 break;
5362 }
5363 case SPIRVOperandType::LITERAL_INTEGER: {
5364 // TODO: Handle LiteralNum carefully.
5365 for (auto Word : Op->getLiteralNum()) {
5366 out << Word;
5367 }
5368 break;
5369 }
5370 case SPIRVOperandType::LITERAL_FLOAT: {
5371 // TODO: Handle LiteralNum carefully.
5372 for (auto Word : Op->getLiteralNum()) {
5373 APFloat APF = APFloat(APFloat::IEEEsingle(), APInt(32, Word));
5374 SmallString<8> Str;
5375 APF.toString(Str, 6, 2);
5376 out << Str;
5377 }
5378 break;
5379 }
5380 }
5381}
5382
5383void SPIRVProducerPass::PrintCapability(SPIRVOperand *Op) {
5384 spv::Capability Cap = static_cast<spv::Capability>(Op->getNumID());
5385 out << spv::getCapabilityName(Cap);
5386}
5387
5388void SPIRVProducerPass::PrintExtInst(SPIRVOperand *Op) {
5389 auto LiteralNum = Op->getLiteralNum();
5390 glsl::ExtInst Ext = static_cast<glsl::ExtInst>(LiteralNum[0]);
5391 out << glsl::getExtInstName(Ext);
5392}
5393
5394void SPIRVProducerPass::PrintAddrModel(SPIRVOperand *Op) {
5395 spv::AddressingModel AddrModel =
5396 static_cast<spv::AddressingModel>(Op->getNumID());
5397 out << spv::getAddressingModelName(AddrModel);
5398}
5399
5400void SPIRVProducerPass::PrintMemModel(SPIRVOperand *Op) {
5401 spv::MemoryModel MemModel = static_cast<spv::MemoryModel>(Op->getNumID());
5402 out << spv::getMemoryModelName(MemModel);
5403}
5404
5405void SPIRVProducerPass::PrintExecModel(SPIRVOperand *Op) {
5406 spv::ExecutionModel ExecModel =
5407 static_cast<spv::ExecutionModel>(Op->getNumID());
5408 out << spv::getExecutionModelName(ExecModel);
5409}
5410
5411void SPIRVProducerPass::PrintExecMode(SPIRVOperand *Op) {
5412 spv::ExecutionMode ExecMode = static_cast<spv::ExecutionMode>(Op->getNumID());
5413 out << spv::getExecutionModeName(ExecMode);
5414}
5415
5416void SPIRVProducerPass::PrintSourceLanguage(SPIRVOperand *Op) {
5417 spv::SourceLanguage SourceLang = static_cast<spv::SourceLanguage>(Op->getNumID());
5418 out << spv::getSourceLanguageName(SourceLang);
5419}
5420
5421void SPIRVProducerPass::PrintFuncCtrl(SPIRVOperand *Op) {
5422 spv::FunctionControlMask FuncCtrl =
5423 static_cast<spv::FunctionControlMask>(Op->getNumID());
5424 out << spv::getFunctionControlName(FuncCtrl);
5425}
5426
5427void SPIRVProducerPass::PrintStorageClass(SPIRVOperand *Op) {
5428 spv::StorageClass StClass = static_cast<spv::StorageClass>(Op->getNumID());
5429 out << getStorageClassName(StClass);
5430}
5431
5432void SPIRVProducerPass::PrintDecoration(SPIRVOperand *Op) {
5433 spv::Decoration Deco = static_cast<spv::Decoration>(Op->getNumID());
5434 out << getDecorationName(Deco);
5435}
5436
5437void SPIRVProducerPass::PrintBuiltIn(SPIRVOperand *Op) {
5438 spv::BuiltIn BIn = static_cast<spv::BuiltIn>(Op->getNumID());
5439 out << getBuiltInName(BIn);
5440}
5441
5442void SPIRVProducerPass::PrintSelectionControl(SPIRVOperand *Op) {
5443 spv::SelectionControlMask BIn =
5444 static_cast<spv::SelectionControlMask>(Op->getNumID());
5445 out << getSelectionControlName(BIn);
5446}
5447
5448void SPIRVProducerPass::PrintLoopControl(SPIRVOperand *Op) {
5449 spv::LoopControlMask BIn = static_cast<spv::LoopControlMask>(Op->getNumID());
5450 out << getLoopControlName(BIn);
5451}
5452
5453void SPIRVProducerPass::PrintDimensionality(SPIRVOperand *Op) {
5454 spv::Dim DIM = static_cast<spv::Dim>(Op->getNumID());
5455 out << getDimName(DIM);
5456}
5457
5458void SPIRVProducerPass::PrintImageFormat(SPIRVOperand *Op) {
5459 spv::ImageFormat Format = static_cast<spv::ImageFormat>(Op->getNumID());
5460 out << getImageFormatName(Format);
5461}
5462
5463void SPIRVProducerPass::PrintMemoryAccess(SPIRVOperand *Op) {
5464 out << spv::getMemoryAccessName(
5465 static_cast<spv::MemoryAccessMask>(Op->getNumID()));
5466}
5467
5468void SPIRVProducerPass::PrintImageOperandsType(SPIRVOperand *Op) {
5469 auto LiteralNum = Op->getLiteralNum();
5470 spv::ImageOperandsMask Type =
5471 static_cast<spv::ImageOperandsMask>(LiteralNum[0]);
5472 out << getImageOperandsName(Type);
5473}
5474
5475void SPIRVProducerPass::WriteSPIRVAssembly() {
5476 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5477
5478 for (auto Inst : SPIRVInstList) {
5479 SPIRVOperandList Ops = Inst->getOperands();
5480 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5481
5482 switch (Opcode) {
5483 default: {
5484 llvm_unreachable("Unsupported SPIRV instruction");
5485 break;
5486 }
5487 case spv::OpCapability: {
5488 // Ops[0] = Capability
5489 PrintOpcode(Inst);
5490 out << " ";
5491 PrintCapability(Ops[0]);
5492 out << "\n";
5493 break;
5494 }
5495 case spv::OpMemoryModel: {
5496 // Ops[0] = Addressing Model
5497 // Ops[1] = Memory Model
5498 PrintOpcode(Inst);
5499 out << " ";
5500 PrintAddrModel(Ops[0]);
5501 out << " ";
5502 PrintMemModel(Ops[1]);
5503 out << "\n";
5504 break;
5505 }
5506 case spv::OpEntryPoint: {
5507 // Ops[0] = Execution Model
5508 // Ops[1] = EntryPoint ID
5509 // Ops[2] = Name (Literal String)
5510 // Ops[3] ... Ops[n] = Interface ID
5511 PrintOpcode(Inst);
5512 out << " ";
5513 PrintExecModel(Ops[0]);
5514 for (uint32_t i = 1; i < Ops.size(); i++) {
5515 out << " ";
5516 PrintOperand(Ops[i]);
5517 }
5518 out << "\n";
5519 break;
5520 }
5521 case spv::OpExecutionMode: {
5522 // Ops[0] = Entry Point ID
5523 // Ops[1] = Execution Mode
5524 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
5525 PrintOpcode(Inst);
5526 out << " ";
5527 PrintOperand(Ops[0]);
5528 out << " ";
5529 PrintExecMode(Ops[1]);
5530 for (uint32_t i = 2; i < Ops.size(); i++) {
5531 out << " ";
5532 PrintOperand(Ops[i]);
5533 }
5534 out << "\n";
5535 break;
5536 }
5537 case spv::OpSource: {
5538 // Ops[0] = SourceLanguage ID
5539 // Ops[1] = Version (LiteralNum)
5540 PrintOpcode(Inst);
5541 out << " ";
5542 PrintSourceLanguage(Ops[0]);
5543 out << " ";
5544 PrintOperand(Ops[1]);
5545 out << "\n";
5546 break;
5547 }
5548 case spv::OpDecorate: {
5549 // Ops[0] = Target ID
5550 // Ops[1] = Decoration (Block or BufferBlock)
5551 // Ops[2] ... Ops[n] = Optional literals according to Decoration
5552 PrintOpcode(Inst);
5553 out << " ";
5554 PrintOperand(Ops[0]);
5555 out << " ";
5556 PrintDecoration(Ops[1]);
5557 // Handle BuiltIn OpDecorate specially.
5558 if (Ops[1]->getNumID() == spv::DecorationBuiltIn) {
5559 out << " ";
5560 PrintBuiltIn(Ops[2]);
5561 } else {
5562 for (uint32_t i = 2; i < Ops.size(); i++) {
5563 out << " ";
5564 PrintOperand(Ops[i]);
5565 }
5566 }
5567 out << "\n";
5568 break;
5569 }
5570 case spv::OpMemberDecorate: {
5571 // Ops[0] = Structure Type ID
5572 // Ops[1] = Member Index(Literal Number)
5573 // Ops[2] = Decoration
5574 // Ops[3] ... Ops[n] = Optional literals according to Decoration
5575 PrintOpcode(Inst);
5576 out << " ";
5577 PrintOperand(Ops[0]);
5578 out << " ";
5579 PrintOperand(Ops[1]);
5580 out << " ";
5581 PrintDecoration(Ops[2]);
5582 for (uint32_t i = 3; i < Ops.size(); i++) {
5583 out << " ";
5584 PrintOperand(Ops[i]);
5585 }
5586 out << "\n";
5587 break;
5588 }
5589 case spv::OpTypePointer: {
5590 // Ops[0] = Storage Class
5591 // Ops[1] = Element Type ID
5592 PrintResID(Inst);
5593 out << " = ";
5594 PrintOpcode(Inst);
5595 out << " ";
5596 PrintStorageClass(Ops[0]);
5597 out << " ";
5598 PrintOperand(Ops[1]);
5599 out << "\n";
5600 break;
5601 }
5602 case spv::OpTypeImage: {
5603 // Ops[0] = Sampled Type ID
5604 // Ops[1] = Dim ID
5605 // Ops[2] = Depth (Literal Number)
5606 // Ops[3] = Arrayed (Literal Number)
5607 // Ops[4] = MS (Literal Number)
5608 // Ops[5] = Sampled (Literal Number)
5609 // Ops[6] = Image Format ID
5610 PrintResID(Inst);
5611 out << " = ";
5612 PrintOpcode(Inst);
5613 out << " ";
5614 PrintOperand(Ops[0]);
5615 out << " ";
5616 PrintDimensionality(Ops[1]);
5617 out << " ";
5618 PrintOperand(Ops[2]);
5619 out << " ";
5620 PrintOperand(Ops[3]);
5621 out << " ";
5622 PrintOperand(Ops[4]);
5623 out << " ";
5624 PrintOperand(Ops[5]);
5625 out << " ";
5626 PrintImageFormat(Ops[6]);
5627 out << "\n";
5628 break;
5629 }
5630 case spv::OpFunction: {
5631 // Ops[0] : Result Type ID
5632 // Ops[1] : Function Control
5633 // Ops[2] : Function Type ID
5634 PrintResID(Inst);
5635 out << " = ";
5636 PrintOpcode(Inst);
5637 out << " ";
5638 PrintOperand(Ops[0]);
5639 out << " ";
5640 PrintFuncCtrl(Ops[1]);
5641 out << " ";
5642 PrintOperand(Ops[2]);
5643 out << "\n";
5644 break;
5645 }
5646 case spv::OpSelectionMerge: {
5647 // Ops[0] = Merge Block ID
5648 // Ops[1] = Selection Control
5649 PrintOpcode(Inst);
5650 out << " ";
5651 PrintOperand(Ops[0]);
5652 out << " ";
5653 PrintSelectionControl(Ops[1]);
5654 out << "\n";
5655 break;
5656 }
5657 case spv::OpLoopMerge: {
5658 // Ops[0] = Merge Block ID
5659 // Ops[1] = Continue Target ID
5660 // Ops[2] = Selection Control
5661 PrintOpcode(Inst);
5662 out << " ";
5663 PrintOperand(Ops[0]);
5664 out << " ";
5665 PrintOperand(Ops[1]);
5666 out << " ";
5667 PrintLoopControl(Ops[2]);
5668 out << "\n";
5669 break;
5670 }
5671 case spv::OpImageSampleExplicitLod: {
5672 // Ops[0] = Result Type ID
5673 // Ops[1] = Sampled Image ID
5674 // Ops[2] = Coordinate ID
5675 // Ops[3] = Image Operands Type ID
5676 // Ops[4] ... Ops[n] = Operands ID
5677 PrintResID(Inst);
5678 out << " = ";
5679 PrintOpcode(Inst);
5680 for (uint32_t i = 0; i < 3; i++) {
5681 out << " ";
5682 PrintOperand(Ops[i]);
5683 }
5684 out << " ";
5685 PrintImageOperandsType(Ops[3]);
5686 for (uint32_t i = 4; i < Ops.size(); i++) {
5687 out << " ";
5688 PrintOperand(Ops[i]);
5689 }
5690 out << "\n";
5691 break;
5692 }
5693 case spv::OpVariable: {
5694 // Ops[0] : Result Type ID
5695 // Ops[1] : Storage Class
5696 // Ops[2] ... Ops[n] = Initializer IDs
5697 PrintResID(Inst);
5698 out << " = ";
5699 PrintOpcode(Inst);
5700 out << " ";
5701 PrintOperand(Ops[0]);
5702 out << " ";
5703 PrintStorageClass(Ops[1]);
5704 for (uint32_t i = 2; i < Ops.size(); i++) {
5705 out << " ";
5706 PrintOperand(Ops[i]);
5707 }
5708 out << "\n";
5709 break;
5710 }
5711 case spv::OpExtInst: {
5712 // Ops[0] = Result Type ID
5713 // Ops[1] = Set ID (OpExtInstImport ID)
5714 // Ops[2] = Instruction Number (Literal Number)
5715 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5716 PrintResID(Inst);
5717 out << " = ";
5718 PrintOpcode(Inst);
5719 out << " ";
5720 PrintOperand(Ops[0]);
5721 out << " ";
5722 PrintOperand(Ops[1]);
5723 out << " ";
5724 PrintExtInst(Ops[2]);
5725 for (uint32_t i = 3; i < Ops.size(); i++) {
5726 out << " ";
5727 PrintOperand(Ops[i]);
5728 }
5729 out << "\n";
5730 break;
5731 }
5732 case spv::OpCopyMemory: {
5733 // Ops[0] = Addressing Model
5734 // Ops[1] = Memory Model
5735 PrintOpcode(Inst);
5736 out << " ";
5737 PrintOperand(Ops[0]);
5738 out << " ";
5739 PrintOperand(Ops[1]);
5740 out << " ";
5741 PrintMemoryAccess(Ops[2]);
5742 out << " ";
5743 PrintOperand(Ops[3]);
5744 out << "\n";
5745 break;
5746 }
5747 case spv::OpExtension:
5748 case spv::OpControlBarrier:
5749 case spv::OpMemoryBarrier:
5750 case spv::OpBranch:
5751 case spv::OpBranchConditional:
5752 case spv::OpStore:
5753 case spv::OpImageWrite:
5754 case spv::OpReturnValue:
5755 case spv::OpReturn:
5756 case spv::OpFunctionEnd: {
5757 PrintOpcode(Inst);
5758 for (uint32_t i = 0; i < Ops.size(); i++) {
5759 out << " ";
5760 PrintOperand(Ops[i]);
5761 }
5762 out << "\n";
5763 break;
5764 }
5765 case spv::OpExtInstImport:
5766 case spv::OpTypeRuntimeArray:
5767 case spv::OpTypeStruct:
5768 case spv::OpTypeSampler:
5769 case spv::OpTypeSampledImage:
5770 case spv::OpTypeInt:
5771 case spv::OpTypeFloat:
5772 case spv::OpTypeArray:
5773 case spv::OpTypeVector:
5774 case spv::OpTypeBool:
5775 case spv::OpTypeVoid:
5776 case spv::OpTypeFunction:
5777 case spv::OpFunctionParameter:
5778 case spv::OpLabel:
5779 case spv::OpPhi:
5780 case spv::OpLoad:
5781 case spv::OpSelect:
5782 case spv::OpAccessChain:
5783 case spv::OpPtrAccessChain:
5784 case spv::OpInBoundsAccessChain:
5785 case spv::OpUConvert:
5786 case spv::OpSConvert:
5787 case spv::OpConvertFToU:
5788 case spv::OpConvertFToS:
5789 case spv::OpConvertUToF:
5790 case spv::OpConvertSToF:
5791 case spv::OpFConvert:
5792 case spv::OpConvertPtrToU:
5793 case spv::OpConvertUToPtr:
5794 case spv::OpBitcast:
5795 case spv::OpIAdd:
5796 case spv::OpFAdd:
5797 case spv::OpISub:
5798 case spv::OpFSub:
5799 case spv::OpIMul:
5800 case spv::OpFMul:
5801 case spv::OpUDiv:
5802 case spv::OpSDiv:
5803 case spv::OpFDiv:
5804 case spv::OpUMod:
5805 case spv::OpSRem:
5806 case spv::OpFRem:
5807 case spv::OpBitwiseOr:
5808 case spv::OpBitwiseXor:
5809 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005810 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005811 case spv::OpShiftLeftLogical:
5812 case spv::OpShiftRightLogical:
5813 case spv::OpShiftRightArithmetic:
5814 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04005815 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04005816 case spv::OpCompositeExtract:
5817 case spv::OpVectorExtractDynamic:
5818 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04005819 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04005820 case spv::OpVectorInsertDynamic:
5821 case spv::OpVectorShuffle:
5822 case spv::OpIEqual:
5823 case spv::OpINotEqual:
5824 case spv::OpUGreaterThan:
5825 case spv::OpUGreaterThanEqual:
5826 case spv::OpULessThan:
5827 case spv::OpULessThanEqual:
5828 case spv::OpSGreaterThan:
5829 case spv::OpSGreaterThanEqual:
5830 case spv::OpSLessThan:
5831 case spv::OpSLessThanEqual:
5832 case spv::OpFOrdEqual:
5833 case spv::OpFOrdGreaterThan:
5834 case spv::OpFOrdGreaterThanEqual:
5835 case spv::OpFOrdLessThan:
5836 case spv::OpFOrdLessThanEqual:
5837 case spv::OpFOrdNotEqual:
5838 case spv::OpFUnordEqual:
5839 case spv::OpFUnordGreaterThan:
5840 case spv::OpFUnordGreaterThanEqual:
5841 case spv::OpFUnordLessThan:
5842 case spv::OpFUnordLessThanEqual:
5843 case spv::OpFUnordNotEqual:
5844 case spv::OpSampledImage:
5845 case spv::OpFunctionCall:
5846 case spv::OpConstantTrue:
5847 case spv::OpConstantFalse:
5848 case spv::OpConstant:
5849 case spv::OpSpecConstant:
5850 case spv::OpConstantComposite:
5851 case spv::OpSpecConstantComposite:
5852 case spv::OpConstantNull:
5853 case spv::OpLogicalOr:
5854 case spv::OpLogicalAnd:
5855 case spv::OpLogicalNot:
5856 case spv::OpLogicalNotEqual:
5857 case spv::OpUndef:
5858 case spv::OpIsInf:
5859 case spv::OpIsNan:
5860 case spv::OpAny:
5861 case spv::OpAll:
David Neto5c22a252018-03-15 16:07:41 -04005862 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04005863 case spv::OpAtomicIAdd:
5864 case spv::OpAtomicISub:
5865 case spv::OpAtomicExchange:
5866 case spv::OpAtomicIIncrement:
5867 case spv::OpAtomicIDecrement:
5868 case spv::OpAtomicCompareExchange:
5869 case spv::OpAtomicUMin:
5870 case spv::OpAtomicSMin:
5871 case spv::OpAtomicUMax:
5872 case spv::OpAtomicSMax:
5873 case spv::OpAtomicAnd:
5874 case spv::OpAtomicOr:
5875 case spv::OpAtomicXor:
5876 case spv::OpDot: {
5877 PrintResID(Inst);
5878 out << " = ";
5879 PrintOpcode(Inst);
5880 for (uint32_t i = 0; i < Ops.size(); i++) {
5881 out << " ";
5882 PrintOperand(Ops[i]);
5883 }
5884 out << "\n";
5885 break;
5886 }
5887 }
5888 }
5889}
5890
5891void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04005892 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04005893}
5894
5895void SPIRVProducerPass::WriteResultID(SPIRVInstruction *Inst) {
5896 WriteOneWord(Inst->getResultID());
5897}
5898
5899void SPIRVProducerPass::WriteWordCountAndOpcode(SPIRVInstruction *Inst) {
5900 // High 16 bit : Word Count
5901 // Low 16 bit : Opcode
5902 uint32_t Word = Inst->getOpcode();
David Netoee2660d2018-06-28 16:31:29 -04005903 const uint32_t count = Inst->getWordCount();
5904 if (count > 65535) {
5905 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
5906 llvm_unreachable("Word count too high");
5907 }
David Neto22f144c2017-06-12 14:26:21 -04005908 Word |= Inst->getWordCount() << 16;
5909 WriteOneWord(Word);
5910}
5911
5912void SPIRVProducerPass::WriteOperand(SPIRVOperand *Op) {
5913 SPIRVOperandType OpTy = Op->getType();
5914 switch (OpTy) {
5915 default: {
5916 llvm_unreachable("Unsupported SPIRV Operand Type???");
5917 break;
5918 }
5919 case SPIRVOperandType::NUMBERID: {
5920 WriteOneWord(Op->getNumID());
5921 break;
5922 }
5923 case SPIRVOperandType::LITERAL_STRING: {
5924 std::string Str = Op->getLiteralStr();
5925 const char *Data = Str.c_str();
5926 size_t WordSize = Str.size() / 4;
5927 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
5928 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
5929 }
5930
5931 uint32_t Remainder = Str.size() % 4;
5932 uint32_t LastWord = 0;
5933 if (Remainder) {
5934 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
5935 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
5936 }
5937 }
5938
5939 WriteOneWord(LastWord);
5940 break;
5941 }
5942 case SPIRVOperandType::LITERAL_INTEGER:
5943 case SPIRVOperandType::LITERAL_FLOAT: {
5944 auto LiteralNum = Op->getLiteralNum();
5945 // TODO: Handle LiteranNum carefully.
5946 for (auto Word : LiteralNum) {
5947 WriteOneWord(Word);
5948 }
5949 break;
5950 }
5951 }
5952}
5953
5954void SPIRVProducerPass::WriteSPIRVBinary() {
5955 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5956
5957 for (auto Inst : SPIRVInstList) {
David Netoc6f3ab22018-04-06 18:02:31 -04005958 SPIRVOperandList Ops{Inst->getOperands()};
David Neto22f144c2017-06-12 14:26:21 -04005959 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5960
5961 switch (Opcode) {
5962 default: {
David Neto5c22a252018-03-15 16:07:41 -04005963 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04005964 llvm_unreachable("Unsupported SPIRV instruction");
5965 break;
5966 }
5967 case spv::OpCapability:
5968 case spv::OpExtension:
5969 case spv::OpMemoryModel:
5970 case spv::OpEntryPoint:
5971 case spv::OpExecutionMode:
5972 case spv::OpSource:
5973 case spv::OpDecorate:
5974 case spv::OpMemberDecorate:
5975 case spv::OpBranch:
5976 case spv::OpBranchConditional:
5977 case spv::OpSelectionMerge:
5978 case spv::OpLoopMerge:
5979 case spv::OpStore:
5980 case spv::OpImageWrite:
5981 case spv::OpReturnValue:
5982 case spv::OpControlBarrier:
5983 case spv::OpMemoryBarrier:
5984 case spv::OpReturn:
5985 case spv::OpFunctionEnd:
5986 case spv::OpCopyMemory: {
5987 WriteWordCountAndOpcode(Inst);
5988 for (uint32_t i = 0; i < Ops.size(); i++) {
5989 WriteOperand(Ops[i]);
5990 }
5991 break;
5992 }
5993 case spv::OpTypeBool:
5994 case spv::OpTypeVoid:
5995 case spv::OpTypeSampler:
5996 case spv::OpLabel:
5997 case spv::OpExtInstImport:
5998 case spv::OpTypePointer:
5999 case spv::OpTypeRuntimeArray:
6000 case spv::OpTypeStruct:
6001 case spv::OpTypeImage:
6002 case spv::OpTypeSampledImage:
6003 case spv::OpTypeInt:
6004 case spv::OpTypeFloat:
6005 case spv::OpTypeArray:
6006 case spv::OpTypeVector:
6007 case spv::OpTypeFunction: {
6008 WriteWordCountAndOpcode(Inst);
6009 WriteResultID(Inst);
6010 for (uint32_t i = 0; i < Ops.size(); i++) {
6011 WriteOperand(Ops[i]);
6012 }
6013 break;
6014 }
6015 case spv::OpFunction:
6016 case spv::OpFunctionParameter:
6017 case spv::OpAccessChain:
6018 case spv::OpPtrAccessChain:
6019 case spv::OpInBoundsAccessChain:
6020 case spv::OpUConvert:
6021 case spv::OpSConvert:
6022 case spv::OpConvertFToU:
6023 case spv::OpConvertFToS:
6024 case spv::OpConvertUToF:
6025 case spv::OpConvertSToF:
6026 case spv::OpFConvert:
6027 case spv::OpConvertPtrToU:
6028 case spv::OpConvertUToPtr:
6029 case spv::OpBitcast:
6030 case spv::OpIAdd:
6031 case spv::OpFAdd:
6032 case spv::OpISub:
6033 case spv::OpFSub:
6034 case spv::OpIMul:
6035 case spv::OpFMul:
6036 case spv::OpUDiv:
6037 case spv::OpSDiv:
6038 case spv::OpFDiv:
6039 case spv::OpUMod:
6040 case spv::OpSRem:
6041 case spv::OpFRem:
6042 case spv::OpBitwiseOr:
6043 case spv::OpBitwiseXor:
6044 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04006045 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04006046 case spv::OpShiftLeftLogical:
6047 case spv::OpShiftRightLogical:
6048 case spv::OpShiftRightArithmetic:
6049 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04006050 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04006051 case spv::OpCompositeExtract:
6052 case spv::OpVectorExtractDynamic:
6053 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04006054 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04006055 case spv::OpVectorInsertDynamic:
6056 case spv::OpVectorShuffle:
6057 case spv::OpIEqual:
6058 case spv::OpINotEqual:
6059 case spv::OpUGreaterThan:
6060 case spv::OpUGreaterThanEqual:
6061 case spv::OpULessThan:
6062 case spv::OpULessThanEqual:
6063 case spv::OpSGreaterThan:
6064 case spv::OpSGreaterThanEqual:
6065 case spv::OpSLessThan:
6066 case spv::OpSLessThanEqual:
6067 case spv::OpFOrdEqual:
6068 case spv::OpFOrdGreaterThan:
6069 case spv::OpFOrdGreaterThanEqual:
6070 case spv::OpFOrdLessThan:
6071 case spv::OpFOrdLessThanEqual:
6072 case spv::OpFOrdNotEqual:
6073 case spv::OpFUnordEqual:
6074 case spv::OpFUnordGreaterThan:
6075 case spv::OpFUnordGreaterThanEqual:
6076 case spv::OpFUnordLessThan:
6077 case spv::OpFUnordLessThanEqual:
6078 case spv::OpFUnordNotEqual:
6079 case spv::OpExtInst:
6080 case spv::OpIsInf:
6081 case spv::OpIsNan:
6082 case spv::OpAny:
6083 case spv::OpAll:
6084 case spv::OpUndef:
6085 case spv::OpConstantNull:
6086 case spv::OpLogicalOr:
6087 case spv::OpLogicalAnd:
6088 case spv::OpLogicalNot:
6089 case spv::OpLogicalNotEqual:
6090 case spv::OpConstantComposite:
6091 case spv::OpSpecConstantComposite:
6092 case spv::OpConstantTrue:
6093 case spv::OpConstantFalse:
6094 case spv::OpConstant:
6095 case spv::OpSpecConstant:
6096 case spv::OpVariable:
6097 case spv::OpFunctionCall:
6098 case spv::OpSampledImage:
6099 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04006100 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04006101 case spv::OpSelect:
6102 case spv::OpPhi:
6103 case spv::OpLoad:
6104 case spv::OpAtomicIAdd:
6105 case spv::OpAtomicISub:
6106 case spv::OpAtomicExchange:
6107 case spv::OpAtomicIIncrement:
6108 case spv::OpAtomicIDecrement:
6109 case spv::OpAtomicCompareExchange:
6110 case spv::OpAtomicUMin:
6111 case spv::OpAtomicSMin:
6112 case spv::OpAtomicUMax:
6113 case spv::OpAtomicSMax:
6114 case spv::OpAtomicAnd:
6115 case spv::OpAtomicOr:
6116 case spv::OpAtomicXor:
6117 case spv::OpDot: {
6118 WriteWordCountAndOpcode(Inst);
6119 WriteOperand(Ops[0]);
6120 WriteResultID(Inst);
6121 for (uint32_t i = 1; i < Ops.size(); i++) {
6122 WriteOperand(Ops[i]);
6123 }
6124 break;
6125 }
6126 }
6127 }
6128}
Alan Baker9bf93fb2018-08-28 16:59:26 -04006129
6130bool SPIRVProducerPass::IsTypeNullable(const Type* type) const {
6131 switch (type->getTypeID()) {
6132 case Type::HalfTyID:
6133 case Type::FloatTyID:
6134 case Type::DoubleTyID:
6135 case Type::IntegerTyID:
6136 case Type::VectorTyID:
6137 return true;
6138 case Type::PointerTyID: {
6139 const PointerType *pointer_type = cast<PointerType>(type);
6140 if (pointer_type->getPointerAddressSpace() !=
6141 AddressSpace::UniformConstant) {
6142 auto pointee_type = pointer_type->getPointerElementType();
6143 if (pointee_type->isStructTy() &&
6144 cast<StructType>(pointee_type)->isOpaque()) {
6145 // Images and samplers are not nullable.
6146 return false;
6147 }
6148 }
6149 return true;
6150 }
6151 case Type::ArrayTyID:
6152 return IsTypeNullable(cast<CompositeType>(type)->getTypeAtIndex(0u));
6153 case Type::StructTyID: {
6154 const StructType* struct_type = cast<StructType>(type);
6155 // Images and samplers are not nullable.
6156 if (struct_type->isOpaque()) return false;
6157 for (const auto element : struct_type->elements()) {
6158 if (!IsTypeNullable(element)) return false;
6159 }
6160 return true;
6161 }
6162 default:
6163 return false;
6164 }
6165}