blob: 15d10a56ae37ea58b8a886cc8d7f7f4079288cd2 [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:
Kévin Petiteb9f90a2018-09-29 12:29:34 +01001161 case glsl::ExtInstAtan:
David Neto3fbb4072017-10-16 11:28:14 -04001162 case glsl::ExtInstAtan2:
1163 // We need 1/pi for acospi, asinpi, atan2pi.
1164 register_constant(
1165 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
1166 break;
1167 default:
1168 assert(false && "internally inconsistent");
1169 }
David Neto22f144c2017-06-12 14:26:21 -04001170 }
1171 }
1172 }
1173 }
1174 }
1175
1176 return HasExtInst;
1177}
1178
1179void SPIRVProducerPass::FindTypePerGlobalVar(GlobalVariable &GV) {
1180 // Investigate global variable's type.
1181 FindType(GV.getType());
1182}
1183
1184void SPIRVProducerPass::FindTypePerFunc(Function &F) {
1185 // Investigate function's type.
1186 FunctionType *FTy = F.getFunctionType();
1187
1188 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
1189 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
David Neto9ed8e2f2018-03-24 06:47:24 -07001190 // Handle a regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04001191 if (GlobalConstFuncTyMap.count(FTy)) {
1192 uint32_t GVCstArgIdx = GlobalConstFuncTypeMap[FTy].second;
1193 SmallVector<Type *, 4> NewFuncParamTys;
1194 for (unsigned i = 0; i < FTy->getNumParams(); i++) {
1195 Type *ParamTy = FTy->getParamType(i);
1196 if (i == GVCstArgIdx) {
1197 Type *EleTy = ParamTy->getPointerElementType();
1198 ParamTy = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1199 }
1200
1201 NewFuncParamTys.push_back(ParamTy);
1202 }
1203
1204 FunctionType *NewFTy =
1205 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1206 GlobalConstFuncTyMap[FTy] = std::make_pair(NewFTy, GVCstArgIdx);
1207 FTy = NewFTy;
1208 }
1209
1210 FindType(FTy);
1211 } else {
1212 // As kernel functions do not have parameters, create new function type and
1213 // add it to type map.
1214 SmallVector<Type *, 4> NewFuncParamTys;
1215 FunctionType *NewFTy =
1216 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1217 FindType(NewFTy);
1218 }
1219
1220 // Investigate instructions' type in function body.
1221 for (BasicBlock &BB : F) {
1222 for (Instruction &I : BB) {
1223 if (isa<ShuffleVectorInst>(I)) {
1224 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1225 // Ignore type for mask of shuffle vector instruction.
1226 if (i == 2) {
1227 continue;
1228 }
1229
1230 Value *Op = I.getOperand(i);
1231 if (!isa<MetadataAsValue>(Op)) {
1232 FindType(Op->getType());
1233 }
1234 }
1235
1236 FindType(I.getType());
1237 continue;
1238 }
1239
David Neto862b7d82018-06-14 18:48:37 -04001240 CallInst *Call = dyn_cast<CallInst>(&I);
1241
1242 if (Call && Call->getCalledFunction()->getName().startswith(
Alan Baker202c8c72018-08-13 13:47:44 -04001243 clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001244 // This is a fake call representing access to a resource variable.
1245 // We handle that elsewhere.
1246 continue;
1247 }
1248
Alan Baker202c8c72018-08-13 13:47:44 -04001249 if (Call && Call->getCalledFunction()->getName().startswith(
1250 clspv::WorkgroupAccessorFunction())) {
1251 // This is a fake call representing access to a workgroup variable.
1252 // We handle that elsewhere.
1253 continue;
1254 }
1255
David Neto22f144c2017-06-12 14:26:21 -04001256 // Work through the operands of the instruction.
1257 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1258 Value *const Op = I.getOperand(i);
1259 // If any of the operands is a constant, find the type!
1260 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1261 FindType(Op->getType());
1262 }
1263 }
1264
1265 for (Use &Op : I.operands()) {
1266 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1267 // Avoid to check call instruction's type.
1268 break;
1269 }
Alan Baker202c8c72018-08-13 13:47:44 -04001270 if (CallInst *OpCall = dyn_cast<CallInst>(Op)) {
1271 if (OpCall && OpCall->getCalledFunction()->getName().startswith(
1272 clspv::WorkgroupAccessorFunction())) {
1273 // This is a fake call representing access to a workgroup variable.
1274 // We handle that elsewhere.
1275 continue;
1276 }
1277 }
David Neto22f144c2017-06-12 14:26:21 -04001278 if (!isa<MetadataAsValue>(&Op)) {
1279 FindType(Op->getType());
1280 continue;
1281 }
1282 }
1283
David Neto22f144c2017-06-12 14:26:21 -04001284 // We don't want to track the type of this call as we are going to replace
1285 // it.
David Neto862b7d82018-06-14 18:48:37 -04001286 if (Call && ("clspv.sampler.var.literal" ==
David Neto22f144c2017-06-12 14:26:21 -04001287 Call->getCalledFunction()->getName())) {
1288 continue;
1289 }
1290
1291 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1292 // If gep's base operand has ModuleScopePrivate address space, make gep
1293 // return ModuleScopePrivate address space.
1294 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate) {
1295 // Add pointer type with private address space for global constant to
1296 // type list.
1297 Type *EleTy = I.getType()->getPointerElementType();
1298 Type *NewPTy =
1299 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1300
1301 FindType(NewPTy);
1302 continue;
1303 }
1304 }
1305
1306 FindType(I.getType());
1307 }
1308 }
1309}
1310
David Neto862b7d82018-06-14 18:48:37 -04001311void SPIRVProducerPass::FindTypesForSamplerMap(Module &M) {
1312 // If we are using a sampler map, find the type of the sampler.
1313 if (M.getFunction("clspv.sampler.var.literal") ||
1314 0 < getSamplerMap().size()) {
1315 auto SamplerStructTy = M.getTypeByName("opencl.sampler_t");
1316 if (!SamplerStructTy) {
1317 SamplerStructTy = StructType::create(M.getContext(), "opencl.sampler_t");
1318 }
1319
1320 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
1321
1322 FindType(SamplerTy);
1323 }
1324}
1325
1326void SPIRVProducerPass::FindTypesForResourceVars(Module &M) {
1327 // Record types so they are generated.
1328 TypesNeedingLayout.reset();
1329 StructTypesNeedingBlock.reset();
1330
1331 // To match older clspv codegen, generate the float type first if required
1332 // for images.
1333 for (const auto *info : ModuleOrderedResourceVars) {
1334 if (info->arg_kind == clspv::ArgKind::ReadOnlyImage ||
1335 info->arg_kind == clspv::ArgKind::WriteOnlyImage) {
1336 // We need "float" for the sampled component type.
1337 FindType(Type::getFloatTy(M.getContext()));
1338 // We only need to find it once.
1339 break;
1340 }
1341 }
1342
1343 for (const auto *info : ModuleOrderedResourceVars) {
1344 Type *type = info->var_fn->getReturnType();
1345
1346 switch (info->arg_kind) {
1347 case clspv::ArgKind::Buffer:
1348 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1349 StructTypesNeedingBlock.insert(sty);
1350 } else {
1351 errs() << *type << "\n";
1352 llvm_unreachable("Buffer arguments must map to structures!");
1353 }
1354 break;
1355 case clspv::ArgKind::Pod:
1356 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1357 StructTypesNeedingBlock.insert(sty);
1358 } else {
1359 errs() << *type << "\n";
1360 llvm_unreachable("POD arguments must map to structures!");
1361 }
1362 break;
1363 case clspv::ArgKind::ReadOnlyImage:
1364 case clspv::ArgKind::WriteOnlyImage:
1365 case clspv::ArgKind::Sampler:
1366 // Sampler and image types map to the pointee type but
1367 // in the uniform constant address space.
1368 type = PointerType::get(type->getPointerElementType(),
1369 clspv::AddressSpace::UniformConstant);
1370 break;
1371 default:
1372 break;
1373 }
1374
1375 // The converted type is the type of the OpVariable we will generate.
1376 // If the pointee type is an array of size zero, FindType will convert it
1377 // to a runtime array.
1378 FindType(type);
1379 }
1380
1381 // Traverse the arrays and structures underneath each Block, and
1382 // mark them as needing layout.
1383 std::vector<Type *> work_list(StructTypesNeedingBlock.begin(),
1384 StructTypesNeedingBlock.end());
1385 while (!work_list.empty()) {
1386 Type *type = work_list.back();
1387 work_list.pop_back();
1388 TypesNeedingLayout.insert(type);
1389 switch (type->getTypeID()) {
1390 case Type::ArrayTyID:
1391 work_list.push_back(type->getArrayElementType());
1392 if (!Hack_generate_runtime_array_stride_early) {
1393 // Remember this array type for deferred decoration.
1394 TypesNeedingArrayStride.insert(type);
1395 }
1396 break;
1397 case Type::StructTyID:
1398 for (auto *elem_ty : cast<StructType>(type)->elements()) {
1399 work_list.push_back(elem_ty);
1400 }
1401 default:
1402 // This type and its contained types don't get layout.
1403 break;
1404 }
1405 }
1406}
1407
Alan Baker202c8c72018-08-13 13:47:44 -04001408void SPIRVProducerPass::FindWorkgroupVars(Module &M) {
1409 // The SpecId assignment for pointer-to-local arguments is recorded in
1410 // module-level metadata. Translate that information into local argument
1411 // information.
1412 NamedMDNode *nmd = M.getNamedMetadata(clspv::LocalSpecIdMetadataName());
1413 if (!nmd) return;
1414 for (auto operand : nmd->operands()) {
1415 MDTuple *tuple = cast<MDTuple>(operand);
1416 ValueAsMetadata *fn_md = cast<ValueAsMetadata>(tuple->getOperand(0));
1417 Function *func = cast<Function>(fn_md->getValue());
1418 ConstantAsMetadata *arg_index_md = cast<ConstantAsMetadata>(tuple->getOperand(1));
1419 int arg_index = cast<ConstantInt>(arg_index_md->getValue())->getSExtValue();
1420 Argument* arg = &*(func->arg_begin() + arg_index);
1421
1422 ConstantAsMetadata *spec_id_md =
1423 cast<ConstantAsMetadata>(tuple->getOperand(2));
1424 int spec_id = cast<ConstantInt>(spec_id_md->getValue())->getSExtValue();
1425
1426 max_local_spec_id_ = std::max(max_local_spec_id_, spec_id + 1);
1427 LocalArgSpecIds[arg] = spec_id;
1428 if (LocalSpecIdInfoMap.count(spec_id)) continue;
1429
1430 // We haven't seen this SpecId yet, so generate the LocalArgInfo for it.
1431 LocalArgInfo info{nextID, arg->getType()->getPointerElementType(),
1432 nextID + 1, nextID + 2,
1433 nextID + 3, spec_id};
1434 LocalSpecIdInfoMap[spec_id] = info;
1435 nextID += 4;
1436
1437 // Ensure the types necessary for this argument get generated.
1438 Type *IdxTy = Type::getInt32Ty(M.getContext());
1439 FindConstant(ConstantInt::get(IdxTy, 0));
1440 FindType(IdxTy);
1441 FindType(arg->getType());
1442 }
1443}
1444
David Neto22f144c2017-06-12 14:26:21 -04001445void SPIRVProducerPass::FindType(Type *Ty) {
1446 TypeList &TyList = getTypeList();
1447
1448 if (0 != TyList.idFor(Ty)) {
1449 return;
1450 }
1451
1452 if (Ty->isPointerTy()) {
1453 auto AddrSpace = Ty->getPointerAddressSpace();
1454 if ((AddressSpace::Constant == AddrSpace) ||
1455 (AddressSpace::Global == AddrSpace)) {
1456 auto PointeeTy = Ty->getPointerElementType();
1457
1458 if (PointeeTy->isStructTy() &&
1459 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1460 FindType(PointeeTy);
1461 auto ActualPointerTy =
1462 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1463 FindType(ActualPointerTy);
1464 return;
1465 }
1466 }
1467 }
1468
David Neto862b7d82018-06-14 18:48:37 -04001469 // By convention, LLVM array type with 0 elements will map to
1470 // OpTypeRuntimeArray. Otherwise, it will map to OpTypeArray, which
1471 // has a constant number of elements. We need to support type of the
1472 // constant.
1473 if (auto *arrayTy = dyn_cast<ArrayType>(Ty)) {
1474 if (arrayTy->getNumElements() > 0) {
1475 LLVMContext &Context = Ty->getContext();
1476 FindType(Type::getInt32Ty(Context));
1477 }
David Neto22f144c2017-06-12 14:26:21 -04001478 }
1479
1480 for (Type *SubTy : Ty->subtypes()) {
1481 FindType(SubTy);
1482 }
1483
1484 TyList.insert(Ty);
1485}
1486
1487void SPIRVProducerPass::FindConstantPerGlobalVar(GlobalVariable &GV) {
1488 // If the global variable has a (non undef) initializer.
1489 if (GV.hasInitializer() && !isa<UndefValue>(GV.getInitializer())) {
David Neto862b7d82018-06-14 18:48:37 -04001490 // Generate the constant if it's not the initializer to a module scope
1491 // constant that we will expect in a storage buffer.
1492 const bool module_scope_constant_external_init =
1493 (GV.getType()->getPointerAddressSpace() == AddressSpace::Constant) &&
1494 clspv::Option::ModuleConstantsInStorageBuffer();
1495 if (!module_scope_constant_external_init) {
1496 FindConstant(GV.getInitializer());
1497 }
David Neto22f144c2017-06-12 14:26:21 -04001498 }
1499}
1500
1501void SPIRVProducerPass::FindConstantPerFunc(Function &F) {
1502 // Investigate constants in function body.
1503 for (BasicBlock &BB : F) {
1504 for (Instruction &I : BB) {
David Neto862b7d82018-06-14 18:48:37 -04001505 if (auto *call = dyn_cast<CallInst>(&I)) {
1506 auto name = call->getCalledFunction()->getName();
1507 if (name == "clspv.sampler.var.literal") {
1508 // We've handled these constants elsewhere, so skip it.
1509 continue;
1510 }
Alan Baker202c8c72018-08-13 13:47:44 -04001511 if (name.startswith(clspv::ResourceAccessorFunction())) {
1512 continue;
1513 }
1514 if (name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001515 continue;
1516 }
David Neto22f144c2017-06-12 14:26:21 -04001517 }
1518
1519 if (isa<AllocaInst>(I)) {
1520 // Alloca instruction has constant for the number of element. Ignore it.
1521 continue;
1522 } else if (isa<ShuffleVectorInst>(I)) {
1523 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1524 // Ignore constant for mask of shuffle vector instruction.
1525 if (i == 2) {
1526 continue;
1527 }
1528
1529 if (isa<Constant>(I.getOperand(i)) &&
1530 !isa<GlobalValue>(I.getOperand(i))) {
1531 FindConstant(I.getOperand(i));
1532 }
1533 }
1534
1535 continue;
1536 } else if (isa<InsertElementInst>(I)) {
1537 // Handle InsertElement with <4 x i8> specially.
1538 Type *CompositeTy = I.getOperand(0)->getType();
1539 if (is4xi8vec(CompositeTy)) {
1540 LLVMContext &Context = CompositeTy->getContext();
1541 if (isa<Constant>(I.getOperand(0))) {
1542 FindConstant(I.getOperand(0));
1543 }
1544
1545 if (isa<Constant>(I.getOperand(1))) {
1546 FindConstant(I.getOperand(1));
1547 }
1548
1549 // Add mask constant 0xFF.
1550 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1551 FindConstant(CstFF);
1552
1553 // Add shift amount constant.
1554 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
1555 uint64_t Idx = CI->getZExtValue();
1556 Constant *CstShiftAmount =
1557 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1558 FindConstant(CstShiftAmount);
1559 }
1560
1561 continue;
1562 }
1563
1564 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1565 // Ignore constant for index of InsertElement instruction.
1566 if (i == 2) {
1567 continue;
1568 }
1569
1570 if (isa<Constant>(I.getOperand(i)) &&
1571 !isa<GlobalValue>(I.getOperand(i))) {
1572 FindConstant(I.getOperand(i));
1573 }
1574 }
1575
1576 continue;
1577 } else if (isa<ExtractElementInst>(I)) {
1578 // Handle ExtractElement with <4 x i8> specially.
1579 Type *CompositeTy = I.getOperand(0)->getType();
1580 if (is4xi8vec(CompositeTy)) {
1581 LLVMContext &Context = CompositeTy->getContext();
1582 if (isa<Constant>(I.getOperand(0))) {
1583 FindConstant(I.getOperand(0));
1584 }
1585
1586 // Add mask constant 0xFF.
1587 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1588 FindConstant(CstFF);
1589
1590 // Add shift amount constant.
1591 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1592 uint64_t Idx = CI->getZExtValue();
1593 Constant *CstShiftAmount =
1594 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1595 FindConstant(CstShiftAmount);
1596 } else {
1597 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
1598 FindConstant(Cst8);
1599 }
1600
1601 continue;
1602 }
1603
1604 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1605 // Ignore constant for index of ExtractElement instruction.
1606 if (i == 1) {
1607 continue;
1608 }
1609
1610 if (isa<Constant>(I.getOperand(i)) &&
1611 !isa<GlobalValue>(I.getOperand(i))) {
1612 FindConstant(I.getOperand(i));
1613 }
1614 }
1615
1616 continue;
1617 } else if ((Instruction::Xor == I.getOpcode()) && I.getType()->isIntegerTy(1)) {
1618 // 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
1619 bool foundConstantTrue = false;
1620 for (Use &Op : I.operands()) {
1621 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1622 auto CI = cast<ConstantInt>(Op);
1623
1624 if (CI->isZero() || foundConstantTrue) {
1625 // 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.
1626 FindConstant(Op);
1627 } else {
1628 foundConstantTrue = true;
1629 }
1630 }
1631 }
1632
1633 continue;
David Netod2de94a2017-08-28 17:27:47 -04001634 } else if (isa<TruncInst>(I)) {
1635 // For truncation to i8 we mask against 255.
1636 Type *ToTy = I.getType();
1637 if (8u == ToTy->getPrimitiveSizeInBits()) {
1638 LLVMContext &Context = ToTy->getContext();
1639 Constant *Cst255 = ConstantInt::get(Type::getInt32Ty(Context), 0xff);
1640 FindConstant(Cst255);
1641 }
1642 // Fall through.
Neil Henning39672102017-09-29 14:33:13 +01001643 } else if (isa<AtomicRMWInst>(I)) {
1644 LLVMContext &Context = I.getContext();
1645
1646 FindConstant(
1647 ConstantInt::get(Type::getInt32Ty(Context), spv::ScopeDevice));
1648 FindConstant(ConstantInt::get(
1649 Type::getInt32Ty(Context),
1650 spv::MemorySemanticsUniformMemoryMask |
1651 spv::MemorySemanticsSequentiallyConsistentMask));
David Neto22f144c2017-06-12 14:26:21 -04001652 }
1653
1654 for (Use &Op : I.operands()) {
1655 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1656 FindConstant(Op);
1657 }
1658 }
1659 }
1660 }
1661}
1662
1663void SPIRVProducerPass::FindConstant(Value *V) {
David Neto22f144c2017-06-12 14:26:21 -04001664 ValueList &CstList = getConstantList();
1665
David Netofb9a7972017-08-25 17:08:24 -04001666 // If V is already tracked, ignore it.
1667 if (0 != CstList.idFor(V)) {
David Neto22f144c2017-06-12 14:26:21 -04001668 return;
1669 }
1670
David Neto862b7d82018-06-14 18:48:37 -04001671 if (isa<GlobalValue>(V) && clspv::Option::ModuleConstantsInStorageBuffer()) {
1672 return;
1673 }
1674
David Neto22f144c2017-06-12 14:26:21 -04001675 Constant *Cst = cast<Constant>(V);
David Neto862b7d82018-06-14 18:48:37 -04001676 Type *CstTy = Cst->getType();
David Neto22f144c2017-06-12 14:26:21 -04001677
1678 // Handle constant with <4 x i8> type specially.
David Neto22f144c2017-06-12 14:26:21 -04001679 if (is4xi8vec(CstTy)) {
1680 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001681 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001682 }
1683 }
1684
1685 if (Cst->getNumOperands()) {
1686 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end(); I != E;
1687 ++I) {
1688 FindConstant(*I);
1689 }
1690
David Netofb9a7972017-08-25 17:08:24 -04001691 CstList.insert(Cst);
David Neto22f144c2017-06-12 14:26:21 -04001692 return;
1693 } else if (const ConstantDataSequential *CDS =
1694 dyn_cast<ConstantDataSequential>(Cst)) {
1695 // Add constants for each element to constant list.
1696 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
1697 Constant *EleCst = CDS->getElementAsConstant(i);
1698 FindConstant(EleCst);
1699 }
1700 }
1701
1702 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001703 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001704 }
1705}
1706
1707spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1708 switch (AddrSpace) {
1709 default:
1710 llvm_unreachable("Unsupported OpenCL address space");
1711 case AddressSpace::Private:
1712 return spv::StorageClassFunction;
1713 case AddressSpace::Global:
1714 case AddressSpace::Constant:
1715 return spv::StorageClassStorageBuffer;
1716 case AddressSpace::Input:
1717 return spv::StorageClassInput;
1718 case AddressSpace::Local:
1719 return spv::StorageClassWorkgroup;
1720 case AddressSpace::UniformConstant:
1721 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001722 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001723 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001724 case AddressSpace::ModuleScopePrivate:
1725 return spv::StorageClassPrivate;
1726 }
1727}
1728
David Neto862b7d82018-06-14 18:48:37 -04001729spv::StorageClass
1730SPIRVProducerPass::GetStorageClassForArgKind(clspv::ArgKind arg_kind) const {
1731 switch (arg_kind) {
1732 case clspv::ArgKind::Buffer:
1733 return spv::StorageClassStorageBuffer;
1734 case clspv::ArgKind::Pod:
1735 return clspv::Option::PodArgsInUniformBuffer()
1736 ? spv::StorageClassUniform
1737 : spv::StorageClassStorageBuffer;
1738 case clspv::ArgKind::Local:
1739 return spv::StorageClassWorkgroup;
1740 case clspv::ArgKind::ReadOnlyImage:
1741 case clspv::ArgKind::WriteOnlyImage:
1742 case clspv::ArgKind::Sampler:
1743 return spv::StorageClassUniformConstant;
1744 }
1745}
1746
David Neto22f144c2017-06-12 14:26:21 -04001747spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1748 return StringSwitch<spv::BuiltIn>(Name)
1749 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1750 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1751 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1752 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1753 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
1754 .Default(spv::BuiltInMax);
1755}
1756
1757void SPIRVProducerPass::GenerateExtInstImport() {
1758 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1759 uint32_t &ExtInstImportID = getOpExtInstImportID();
1760
1761 //
1762 // Generate OpExtInstImport.
1763 //
1764 // Ops[0] ... Ops[n] = Name (Literal String)
David Neto22f144c2017-06-12 14:26:21 -04001765 ExtInstImportID = nextID;
David Neto87846742018-04-11 17:36:22 -04001766 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpExtInstImport, nextID++,
1767 MkString("GLSL.std.450")));
David Neto22f144c2017-06-12 14:26:21 -04001768}
1769
David Netoc6f3ab22018-04-06 18:02:31 -04001770void SPIRVProducerPass::GenerateSPIRVTypes(LLVMContext& Context, const DataLayout &DL) {
David Neto22f144c2017-06-12 14:26:21 -04001771 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1772 ValueMapType &VMap = getValueMap();
1773 ValueMapType &AllocatedVMap = getAllocatedValueMap();
David Neto22f144c2017-06-12 14:26:21 -04001774
1775 // Map for OpTypeRuntimeArray. If argument has pointer type, 2 spirv type
1776 // instructions are generated. They are OpTypePointer and OpTypeRuntimeArray.
1777 DenseMap<Type *, uint32_t> OpRuntimeTyMap;
1778
1779 for (Type *Ty : getTypeList()) {
1780 // Update TypeMap with nextID for reference later.
1781 TypeMap[Ty] = nextID;
1782
1783 switch (Ty->getTypeID()) {
1784 default: {
1785 Ty->print(errs());
1786 llvm_unreachable("Unsupported type???");
1787 break;
1788 }
1789 case Type::MetadataTyID:
1790 case Type::LabelTyID: {
1791 // Ignore these types.
1792 break;
1793 }
1794 case Type::PointerTyID: {
1795 PointerType *PTy = cast<PointerType>(Ty);
1796 unsigned AddrSpace = PTy->getAddressSpace();
1797
1798 // For the purposes of our Vulkan SPIR-V type system, constant and global
1799 // are conflated.
1800 bool UseExistingOpTypePointer = false;
1801 if (AddressSpace::Constant == AddrSpace) {
1802 AddrSpace = AddressSpace::Global;
1803
1804 // Check to see if we already created this type (for instance, if we had
1805 // a constant <type>* and a global <type>*, the type would be created by
1806 // one of these types, and shared by both).
1807 auto GlobalTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1808 if (0 < TypeMap.count(GlobalTy)) {
1809 TypeMap[PTy] = TypeMap[GlobalTy];
David Netoe439d702018-03-23 13:14:08 -07001810 UseExistingOpTypePointer = true;
David Neto22f144c2017-06-12 14:26:21 -04001811 break;
1812 }
1813 } else if (AddressSpace::Global == AddrSpace) {
1814 AddrSpace = AddressSpace::Constant;
1815
1816 // Check to see if we already created this type (for instance, if we had
1817 // a constant <type>* and a global <type>*, the type would be created by
1818 // one of these types, and shared by both).
1819 auto ConstantTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1820 if (0 < TypeMap.count(ConstantTy)) {
1821 TypeMap[PTy] = TypeMap[ConstantTy];
1822 UseExistingOpTypePointer = true;
1823 }
1824 }
1825
David Neto862b7d82018-06-14 18:48:37 -04001826 const bool HasArgUser = true;
David Neto22f144c2017-06-12 14:26:21 -04001827
David Neto862b7d82018-06-14 18:48:37 -04001828 if (HasArgUser && !UseExistingOpTypePointer) {
David Neto22f144c2017-06-12 14:26:21 -04001829 //
1830 // Generate OpTypePointer.
1831 //
1832
1833 // OpTypePointer
1834 // Ops[0] = Storage Class
1835 // Ops[1] = Element Type ID
1836 SPIRVOperandList Ops;
1837
David Neto257c3892018-04-11 13:19:45 -04001838 Ops << MkNum(GetStorageClass(AddrSpace))
1839 << MkId(lookupType(PTy->getElementType()));
David Neto22f144c2017-06-12 14:26:21 -04001840
David Neto87846742018-04-11 17:36:22 -04001841 auto *Inst = new SPIRVInstruction(spv::OpTypePointer, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001842 SPIRVInstList.push_back(Inst);
1843 }
David Neto22f144c2017-06-12 14:26:21 -04001844 break;
1845 }
1846 case Type::StructTyID: {
David Neto22f144c2017-06-12 14:26:21 -04001847 StructType *STy = cast<StructType>(Ty);
1848
1849 // Handle sampler type.
1850 if (STy->isOpaque()) {
1851 if (STy->getName().equals("opencl.sampler_t")) {
1852 //
1853 // Generate OpTypeSampler
1854 //
1855 // Empty Ops.
1856 SPIRVOperandList Ops;
1857
David Neto87846742018-04-11 17:36:22 -04001858 auto *Inst = new SPIRVInstruction(spv::OpTypeSampler, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001859 SPIRVInstList.push_back(Inst);
1860 break;
1861 } else if (STy->getName().equals("opencl.image2d_ro_t") ||
1862 STy->getName().equals("opencl.image2d_wo_t") ||
1863 STy->getName().equals("opencl.image3d_ro_t") ||
1864 STy->getName().equals("opencl.image3d_wo_t")) {
1865 //
1866 // Generate OpTypeImage
1867 //
1868 // Ops[0] = Sampled Type ID
1869 // Ops[1] = Dim ID
1870 // Ops[2] = Depth (Literal Number)
1871 // Ops[3] = Arrayed (Literal Number)
1872 // Ops[4] = MS (Literal Number)
1873 // Ops[5] = Sampled (Literal Number)
1874 // Ops[6] = Image Format ID
1875 //
1876 SPIRVOperandList Ops;
1877
1878 // TODO: Changed Sampled Type according to situations.
1879 uint32_t SampledTyID = lookupType(Type::getFloatTy(Context));
David Neto257c3892018-04-11 13:19:45 -04001880 Ops << MkId(SampledTyID);
David Neto22f144c2017-06-12 14:26:21 -04001881
1882 spv::Dim DimID = spv::Dim2D;
1883 if (STy->getName().equals("opencl.image3d_ro_t") ||
1884 STy->getName().equals("opencl.image3d_wo_t")) {
1885 DimID = spv::Dim3D;
1886 }
David Neto257c3892018-04-11 13:19:45 -04001887 Ops << MkNum(DimID);
David Neto22f144c2017-06-12 14:26:21 -04001888
1889 // TODO: Set up Depth.
David Neto257c3892018-04-11 13:19:45 -04001890 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001891
1892 // TODO: Set up Arrayed.
David Neto257c3892018-04-11 13:19:45 -04001893 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001894
1895 // TODO: Set up MS.
David Neto257c3892018-04-11 13:19:45 -04001896 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001897
1898 // TODO: Set up Sampled.
1899 //
1900 // From Spec
1901 //
1902 // 0 indicates this is only known at run time, not at compile time
1903 // 1 indicates will be used with sampler
1904 // 2 indicates will be used without a sampler (a storage image)
1905 uint32_t Sampled = 1;
1906 if (STy->getName().equals("opencl.image2d_wo_t") ||
1907 STy->getName().equals("opencl.image3d_wo_t")) {
1908 Sampled = 2;
1909 }
David Neto257c3892018-04-11 13:19:45 -04001910 Ops << MkNum(Sampled);
David Neto22f144c2017-06-12 14:26:21 -04001911
1912 // TODO: Set up Image Format.
David Neto257c3892018-04-11 13:19:45 -04001913 Ops << MkNum(spv::ImageFormatUnknown);
David Neto22f144c2017-06-12 14:26:21 -04001914
David Neto87846742018-04-11 17:36:22 -04001915 auto *Inst = new SPIRVInstruction(spv::OpTypeImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001916 SPIRVInstList.push_back(Inst);
1917 break;
1918 }
1919 }
1920
1921 //
1922 // Generate OpTypeStruct
1923 //
1924 // Ops[0] ... Ops[n] = Member IDs
1925 SPIRVOperandList Ops;
1926
1927 for (auto *EleTy : STy->elements()) {
David Neto862b7d82018-06-14 18:48:37 -04001928 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04001929 }
1930
David Neto22f144c2017-06-12 14:26:21 -04001931 uint32_t STyID = nextID;
1932
David Neto87846742018-04-11 17:36:22 -04001933 auto *Inst =
1934 new SPIRVInstruction(spv::OpTypeStruct, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001935 SPIRVInstList.push_back(Inst);
1936
1937 // Generate OpMemberDecorate.
1938 auto DecoInsertPoint =
1939 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
1940 [](SPIRVInstruction *Inst) -> bool {
1941 return Inst->getOpcode() != spv::OpDecorate &&
1942 Inst->getOpcode() != spv::OpMemberDecorate &&
1943 Inst->getOpcode() != spv::OpExtInstImport;
1944 });
1945
David Netoc463b372017-08-10 15:32:21 -04001946 const auto StructLayout = DL.getStructLayout(STy);
1947
David Neto862b7d82018-06-14 18:48:37 -04001948 // #error TODO(dneto): Only do this if in TypesNeedingLayout.
David Neto22f144c2017-06-12 14:26:21 -04001949 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
1950 MemberIdx++) {
1951 // Ops[0] = Structure Type ID
1952 // Ops[1] = Member Index(Literal Number)
1953 // Ops[2] = Decoration (Offset)
1954 // Ops[3] = Byte Offset (Literal Number)
1955 Ops.clear();
1956
David Neto257c3892018-04-11 13:19:45 -04001957 Ops << MkId(STyID) << MkNum(MemberIdx) << MkNum(spv::DecorationOffset);
David Neto22f144c2017-06-12 14:26:21 -04001958
David Netoc463b372017-08-10 15:32:21 -04001959 const auto ByteOffset =
1960 uint32_t(StructLayout->getElementOffset(MemberIdx));
David Neto257c3892018-04-11 13:19:45 -04001961 Ops << MkNum(ByteOffset);
David Neto22f144c2017-06-12 14:26:21 -04001962
David Neto87846742018-04-11 17:36:22 -04001963 auto *DecoInst = new SPIRVInstruction(spv::OpMemberDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001964 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04001965 }
1966
1967 // Generate OpDecorate.
David Neto862b7d82018-06-14 18:48:37 -04001968 if (StructTypesNeedingBlock.idFor(STy)) {
1969 Ops.clear();
1970 // Use Block decorations with StorageBuffer storage class.
1971 Ops << MkId(STyID) << MkNum(spv::DecorationBlock);
David Neto22f144c2017-06-12 14:26:21 -04001972
David Neto862b7d82018-06-14 18:48:37 -04001973 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
1974 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04001975 }
1976 break;
1977 }
1978 case Type::IntegerTyID: {
1979 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
1980
1981 if (BitWidth == 1) {
David Neto87846742018-04-11 17:36:22 -04001982 auto *Inst = new SPIRVInstruction(spv::OpTypeBool, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04001983 SPIRVInstList.push_back(Inst);
1984 } else {
1985 // i8 is added to TypeMap as i32.
David Neto391aeb12017-08-26 15:51:58 -04001986 // No matter what LLVM type is requested first, always alias the
1987 // second one's SPIR-V type to be the same as the one we generated
1988 // first.
Neil Henning39672102017-09-29 14:33:13 +01001989 unsigned aliasToWidth = 0;
David Neto22f144c2017-06-12 14:26:21 -04001990 if (BitWidth == 8) {
David Neto391aeb12017-08-26 15:51:58 -04001991 aliasToWidth = 32;
David Neto22f144c2017-06-12 14:26:21 -04001992 BitWidth = 32;
David Neto391aeb12017-08-26 15:51:58 -04001993 } else if (BitWidth == 32) {
1994 aliasToWidth = 8;
1995 }
1996 if (aliasToWidth) {
1997 Type* otherType = Type::getIntNTy(Ty->getContext(), aliasToWidth);
1998 auto where = TypeMap.find(otherType);
1999 if (where == TypeMap.end()) {
2000 // Go ahead and make it, but also map the other type to it.
2001 TypeMap[otherType] = nextID;
2002 } else {
2003 // Alias this SPIR-V type the existing type.
2004 TypeMap[Ty] = where->second;
2005 break;
2006 }
David Neto22f144c2017-06-12 14:26:21 -04002007 }
2008
David Neto257c3892018-04-11 13:19:45 -04002009 SPIRVOperandList Ops;
2010 Ops << MkNum(BitWidth) << MkNum(0 /* not signed */);
David Neto22f144c2017-06-12 14:26:21 -04002011
2012 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002013 new SPIRVInstruction(spv::OpTypeInt, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002014 }
2015 break;
2016 }
2017 case Type::HalfTyID:
2018 case Type::FloatTyID:
2019 case Type::DoubleTyID: {
2020 SPIRVOperand *WidthOp = new SPIRVOperand(
2021 SPIRVOperandType::LITERAL_INTEGER, Ty->getPrimitiveSizeInBits());
2022
2023 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002024 new SPIRVInstruction(spv::OpTypeFloat, nextID++, WidthOp));
David Neto22f144c2017-06-12 14:26:21 -04002025 break;
2026 }
2027 case Type::ArrayTyID: {
David Neto22f144c2017-06-12 14:26:21 -04002028 ArrayType *ArrTy = cast<ArrayType>(Ty);
David Neto862b7d82018-06-14 18:48:37 -04002029 const uint64_t Length = ArrTy->getArrayNumElements();
2030 if (Length == 0) {
2031 // By convention, map it to a RuntimeArray.
David Neto22f144c2017-06-12 14:26:21 -04002032
David Neto862b7d82018-06-14 18:48:37 -04002033 // Only generate the type once.
2034 // TODO(dneto): Can it ever be generated more than once?
2035 // Doesn't LLVM type uniqueness guarantee we'll only see this
2036 // once?
2037 Type *EleTy = ArrTy->getArrayElementType();
2038 if (OpRuntimeTyMap.count(EleTy) == 0) {
2039 uint32_t OpTypeRuntimeArrayID = nextID;
2040 OpRuntimeTyMap[Ty] = nextID;
David Neto22f144c2017-06-12 14:26:21 -04002041
David Neto862b7d82018-06-14 18:48:37 -04002042 //
2043 // Generate OpTypeRuntimeArray.
2044 //
David Neto22f144c2017-06-12 14:26:21 -04002045
David Neto862b7d82018-06-14 18:48:37 -04002046 // OpTypeRuntimeArray
2047 // Ops[0] = Element Type ID
2048 SPIRVOperandList Ops;
2049 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04002050
David Neto862b7d82018-06-14 18:48:37 -04002051 SPIRVInstList.push_back(
2052 new SPIRVInstruction(spv::OpTypeRuntimeArray, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002053
David Neto862b7d82018-06-14 18:48:37 -04002054 if (Hack_generate_runtime_array_stride_early) {
2055 // Generate OpDecorate.
2056 auto DecoInsertPoint = std::find_if(
2057 SPIRVInstList.begin(), SPIRVInstList.end(),
2058 [](SPIRVInstruction *Inst) -> bool {
2059 return Inst->getOpcode() != spv::OpDecorate &&
2060 Inst->getOpcode() != spv::OpMemberDecorate &&
2061 Inst->getOpcode() != spv::OpExtInstImport;
2062 });
David Neto22f144c2017-06-12 14:26:21 -04002063
David Neto862b7d82018-06-14 18:48:37 -04002064 // Ops[0] = Target ID
2065 // Ops[1] = Decoration (ArrayStride)
2066 // Ops[2] = Stride Number(Literal Number)
2067 Ops.clear();
David Neto85082642018-03-24 06:55:20 -07002068
David Neto862b7d82018-06-14 18:48:37 -04002069 Ops << MkId(OpTypeRuntimeArrayID)
2070 << MkNum(spv::DecorationArrayStride)
2071 << MkNum(static_cast<uint32_t>(DL.getTypeAllocSize(EleTy)));
David Neto22f144c2017-06-12 14:26:21 -04002072
David Neto862b7d82018-06-14 18:48:37 -04002073 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
2074 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
2075 }
2076 }
David Neto22f144c2017-06-12 14:26:21 -04002077
David Neto862b7d82018-06-14 18:48:37 -04002078 } else {
David Neto22f144c2017-06-12 14:26:21 -04002079
David Neto862b7d82018-06-14 18:48:37 -04002080 //
2081 // Generate OpConstant and OpTypeArray.
2082 //
2083
2084 //
2085 // Generate OpConstant for array length.
2086 //
2087 // Ops[0] = Result Type ID
2088 // Ops[1] .. Ops[n] = Values LiteralNumber
2089 SPIRVOperandList Ops;
2090
2091 Type *LengthTy = Type::getInt32Ty(Context);
2092 uint32_t ResTyID = lookupType(LengthTy);
2093 Ops << MkId(ResTyID);
2094
2095 assert(Length < UINT32_MAX);
2096 Ops << MkNum(static_cast<uint32_t>(Length));
2097
2098 // Add constant for length to constant list.
2099 Constant *CstLength = ConstantInt::get(LengthTy, Length);
2100 AllocatedVMap[CstLength] = nextID;
2101 VMap[CstLength] = nextID;
2102 uint32_t LengthID = nextID;
2103
2104 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
2105 SPIRVInstList.push_back(CstInst);
2106
2107 // Remember to generate ArrayStride later
2108 getTypesNeedingArrayStride().insert(Ty);
2109
2110 //
2111 // Generate OpTypeArray.
2112 //
2113 // Ops[0] = Element Type ID
2114 // Ops[1] = Array Length Constant ID
2115 Ops.clear();
2116
2117 uint32_t EleTyID = lookupType(ArrTy->getElementType());
2118 Ops << MkId(EleTyID) << MkId(LengthID);
2119
2120 // Update TypeMap with nextID.
2121 TypeMap[Ty] = nextID;
2122
2123 auto *ArrayInst = new SPIRVInstruction(spv::OpTypeArray, nextID++, Ops);
2124 SPIRVInstList.push_back(ArrayInst);
2125 }
David Neto22f144c2017-06-12 14:26:21 -04002126 break;
2127 }
2128 case Type::VectorTyID: {
2129 // <4 x i8> is changed to i32.
David Neto22f144c2017-06-12 14:26:21 -04002130 if (Ty->getVectorElementType() == Type::getInt8Ty(Context)) {
2131 if (Ty->getVectorNumElements() == 4) {
2132 TypeMap[Ty] = lookupType(Ty->getVectorElementType());
2133 break;
2134 } else {
2135 Ty->print(errs());
2136 llvm_unreachable("Support above i8 vector type");
2137 }
2138 }
2139
2140 // Ops[0] = Component Type ID
2141 // Ops[1] = Component Count (Literal Number)
David Neto257c3892018-04-11 13:19:45 -04002142 SPIRVOperandList Ops;
2143 Ops << MkId(lookupType(Ty->getVectorElementType()))
2144 << MkNum(Ty->getVectorNumElements());
David Neto22f144c2017-06-12 14:26:21 -04002145
David Neto87846742018-04-11 17:36:22 -04002146 SPIRVInstruction* inst = new SPIRVInstruction(spv::OpTypeVector, nextID++, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002147 SPIRVInstList.push_back(inst);
David Neto22f144c2017-06-12 14:26:21 -04002148 break;
2149 }
2150 case Type::VoidTyID: {
David Neto87846742018-04-11 17:36:22 -04002151 auto *Inst = new SPIRVInstruction(spv::OpTypeVoid, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04002152 SPIRVInstList.push_back(Inst);
2153 break;
2154 }
2155 case Type::FunctionTyID: {
2156 // Generate SPIRV instruction for function type.
2157 FunctionType *FTy = cast<FunctionType>(Ty);
2158
2159 // Ops[0] = Return Type ID
2160 // Ops[1] ... Ops[n] = Parameter Type IDs
2161 SPIRVOperandList Ops;
2162
2163 // Find SPIRV instruction for return type
David Netoc6f3ab22018-04-06 18:02:31 -04002164 Ops << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04002165
2166 // Find SPIRV instructions for parameter types
2167 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
2168 // Find SPIRV instruction for parameter type.
2169 auto ParamTy = FTy->getParamType(k);
2170 if (ParamTy->isPointerTy()) {
2171 auto PointeeTy = ParamTy->getPointerElementType();
2172 if (PointeeTy->isStructTy() &&
2173 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
2174 ParamTy = PointeeTy;
2175 }
2176 }
2177
David Netoc6f3ab22018-04-06 18:02:31 -04002178 Ops << MkId(lookupType(ParamTy));
David Neto22f144c2017-06-12 14:26:21 -04002179 }
2180
David Neto87846742018-04-11 17:36:22 -04002181 auto *Inst = new SPIRVInstruction(spv::OpTypeFunction, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002182 SPIRVInstList.push_back(Inst);
2183 break;
2184 }
2185 }
2186 }
2187
2188 // Generate OpTypeSampledImage.
2189 TypeMapType &OpImageTypeMap = getImageTypeMap();
2190 for (auto &ImageType : OpImageTypeMap) {
2191 //
2192 // Generate OpTypeSampledImage.
2193 //
2194 // Ops[0] = Image Type ID
2195 //
2196 SPIRVOperandList Ops;
2197
2198 Type *ImgTy = ImageType.first;
David Netoc6f3ab22018-04-06 18:02:31 -04002199 Ops << MkId(TypeMap[ImgTy]);
David Neto22f144c2017-06-12 14:26:21 -04002200
2201 // Update OpImageTypeMap.
2202 ImageType.second = nextID;
2203
David Neto87846742018-04-11 17:36:22 -04002204 auto *Inst = new SPIRVInstruction(spv::OpTypeSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002205 SPIRVInstList.push_back(Inst);
2206 }
David Netoc6f3ab22018-04-06 18:02:31 -04002207
2208 // Generate types for pointer-to-local arguments.
Alan Baker202c8c72018-08-13 13:47:44 -04002209 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2210 ++spec_id) {
2211 LocalArgInfo& arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002212
2213 // Generate the spec constant.
2214 SPIRVOperandList Ops;
2215 Ops << MkId(lookupType(Type::getInt32Ty(Context))) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04002216 SPIRVInstList.push_back(
2217 new SPIRVInstruction(spv::OpSpecConstant, arg_info.array_size_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002218
2219 // Generate the array type.
2220 Ops.clear();
2221 // The element type must have been created.
2222 uint32_t elem_ty_id = lookupType(arg_info.elem_type);
2223 assert(elem_ty_id);
2224 Ops << MkId(elem_ty_id) << MkId(arg_info.array_size_id);
2225
2226 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002227 new SPIRVInstruction(spv::OpTypeArray, arg_info.array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002228
2229 Ops.clear();
2230 Ops << MkNum(spv::StorageClassWorkgroup) << MkId(arg_info.array_type_id);
David Neto87846742018-04-11 17:36:22 -04002231 SPIRVInstList.push_back(new SPIRVInstruction(
2232 spv::OpTypePointer, arg_info.ptr_array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002233 }
David Neto22f144c2017-06-12 14:26:21 -04002234}
2235
2236void SPIRVProducerPass::GenerateSPIRVConstants() {
2237 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2238 ValueMapType &VMap = getValueMap();
2239 ValueMapType &AllocatedVMap = getAllocatedValueMap();
2240 ValueList &CstList = getConstantList();
David Neto482550a2018-03-24 05:21:07 -07002241 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04002242
2243 for (uint32_t i = 0; i < CstList.size(); i++) {
David Netofb9a7972017-08-25 17:08:24 -04002244 // UniqueVector ids are 1-based.
2245 Constant *Cst = cast<Constant>(CstList[i+1]);
David Neto22f144c2017-06-12 14:26:21 -04002246
2247 // OpTypeArray's constant was already generated.
David Netofb9a7972017-08-25 17:08:24 -04002248 if (AllocatedVMap.find_as(Cst) != AllocatedVMap.end()) {
David Neto22f144c2017-06-12 14:26:21 -04002249 continue;
2250 }
2251
David Netofb9a7972017-08-25 17:08:24 -04002252 // Set ValueMap with nextID for reference later.
David Neto22f144c2017-06-12 14:26:21 -04002253 VMap[Cst] = nextID;
2254
2255 //
2256 // Generate OpConstant.
2257 //
2258
2259 // Ops[0] = Result Type ID
2260 // Ops[1] .. Ops[n] = Values LiteralNumber
2261 SPIRVOperandList Ops;
2262
David Neto257c3892018-04-11 13:19:45 -04002263 Ops << MkId(lookupType(Cst->getType()));
David Neto22f144c2017-06-12 14:26:21 -04002264
2265 std::vector<uint32_t> LiteralNum;
David Neto22f144c2017-06-12 14:26:21 -04002266 spv::Op Opcode = spv::OpNop;
2267
2268 if (isa<UndefValue>(Cst)) {
2269 // Ops[0] = Result Type ID
David Netoc66b3352017-10-20 14:28:46 -04002270 Opcode = spv::OpUndef;
Alan Baker9bf93fb2018-08-28 16:59:26 -04002271 if (hack_undef && IsTypeNullable(Cst->getType())) {
2272 Opcode = spv::OpConstantNull;
David Netoc66b3352017-10-20 14:28:46 -04002273 }
David Neto22f144c2017-06-12 14:26:21 -04002274 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
2275 unsigned BitWidth = CI->getBitWidth();
2276 if (BitWidth == 1) {
2277 // If the bitwidth of constant is 1, generate OpConstantTrue or
2278 // OpConstantFalse.
2279 if (CI->getZExtValue()) {
2280 // Ops[0] = Result Type ID
2281 Opcode = spv::OpConstantTrue;
2282 } else {
2283 // Ops[0] = Result Type ID
2284 Opcode = spv::OpConstantFalse;
2285 }
David Neto22f144c2017-06-12 14:26:21 -04002286 } else {
2287 auto V = CI->getZExtValue();
2288 LiteralNum.push_back(V & 0xFFFFFFFF);
2289
2290 if (BitWidth > 32) {
2291 LiteralNum.push_back(V >> 32);
2292 }
2293
2294 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002295
David Neto257c3892018-04-11 13:19:45 -04002296 Ops << MkInteger(LiteralNum);
2297
2298 if (BitWidth == 32 && V == 0) {
2299 constant_i32_zero_id_ = nextID;
2300 }
David Neto22f144c2017-06-12 14:26:21 -04002301 }
2302 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2303 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2304 Type *CFPTy = CFP->getType();
2305 if (CFPTy->isFloatTy()) {
2306 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2307 } else {
2308 CFPTy->print(errs());
2309 llvm_unreachable("Implement this ConstantFP Type");
2310 }
2311
2312 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002313
David Neto257c3892018-04-11 13:19:45 -04002314 Ops << MkFloat(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002315 } else if (isa<ConstantDataSequential>(Cst) &&
2316 cast<ConstantDataSequential>(Cst)->isString()) {
2317 Cst->print(errs());
2318 llvm_unreachable("Implement this Constant");
2319
2320 } else if (const ConstantDataSequential *CDS =
2321 dyn_cast<ConstantDataSequential>(Cst)) {
David Neto49351ac2017-08-26 17:32:20 -04002322 // Let's convert <4 x i8> constant to int constant specially.
2323 // This case occurs when all the values are specified as constant
2324 // ints.
2325 Type *CstTy = Cst->getType();
2326 if (is4xi8vec(CstTy)) {
2327 LLVMContext &Context = CstTy->getContext();
2328
2329 //
2330 // Generate OpConstant with OpTypeInt 32 0.
2331 //
Neil Henning39672102017-09-29 14:33:13 +01002332 uint32_t IntValue = 0;
2333 for (unsigned k = 0; k < 4; k++) {
2334 const uint64_t Val = CDS->getElementAsInteger(k);
David Neto49351ac2017-08-26 17:32:20 -04002335 IntValue = (IntValue << 8) | (Val & 0xffu);
2336 }
2337
2338 Type *i32 = Type::getInt32Ty(Context);
2339 Constant *CstInt = ConstantInt::get(i32, IntValue);
2340 // If this constant is already registered on VMap, use it.
2341 if (VMap.count(CstInt)) {
2342 uint32_t CstID = VMap[CstInt];
2343 VMap[Cst] = CstID;
2344 continue;
2345 }
2346
David Neto257c3892018-04-11 13:19:45 -04002347 Ops << MkNum(IntValue);
David Neto49351ac2017-08-26 17:32:20 -04002348
David Neto87846742018-04-11 17:36:22 -04002349 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto49351ac2017-08-26 17:32:20 -04002350 SPIRVInstList.push_back(CstInst);
2351
2352 continue;
2353 }
2354
2355 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002356 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
2357 Constant *EleCst = CDS->getElementAsConstant(k);
2358 uint32_t EleCstID = VMap[EleCst];
David Neto257c3892018-04-11 13:19:45 -04002359 Ops << MkId(EleCstID);
David Neto22f144c2017-06-12 14:26:21 -04002360 }
2361
2362 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002363 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2364 // Let's convert <4 x i8> constant to int constant specially.
David Neto49351ac2017-08-26 17:32:20 -04002365 // This case occurs when at least one of the values is an undef.
David Neto22f144c2017-06-12 14:26:21 -04002366 Type *CstTy = Cst->getType();
2367 if (is4xi8vec(CstTy)) {
2368 LLVMContext &Context = CstTy->getContext();
2369
2370 //
2371 // Generate OpConstant with OpTypeInt 32 0.
2372 //
Neil Henning39672102017-09-29 14:33:13 +01002373 uint32_t IntValue = 0;
David Neto22f144c2017-06-12 14:26:21 -04002374 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2375 I != E; ++I) {
2376 uint64_t Val = 0;
David Neto49351ac2017-08-26 17:32:20 -04002377 const Value* CV = *I;
Neil Henning39672102017-09-29 14:33:13 +01002378 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2379 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002380 }
David Neto49351ac2017-08-26 17:32:20 -04002381 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002382 }
2383
David Neto49351ac2017-08-26 17:32:20 -04002384 Type *i32 = Type::getInt32Ty(Context);
2385 Constant *CstInt = ConstantInt::get(i32, IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002386 // If this constant is already registered on VMap, use it.
2387 if (VMap.count(CstInt)) {
2388 uint32_t CstID = VMap[CstInt];
2389 VMap[Cst] = CstID;
David Neto19a1bad2017-08-25 15:01:41 -04002390 continue;
David Neto22f144c2017-06-12 14:26:21 -04002391 }
2392
David Neto257c3892018-04-11 13:19:45 -04002393 Ops << MkNum(IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002394
David Neto87846742018-04-11 17:36:22 -04002395 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002396 SPIRVInstList.push_back(CstInst);
2397
David Neto19a1bad2017-08-25 15:01:41 -04002398 continue;
David Neto22f144c2017-06-12 14:26:21 -04002399 }
2400
2401 // We use a constant composite in SPIR-V for our constant aggregate in
2402 // LLVM.
2403 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002404
2405 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
2406 // Look up the ID of the element of this aggregate (which we will
2407 // previously have created a constant for).
2408 uint32_t ElementConstantID = VMap[CA->getAggregateElement(k)];
2409
2410 // And add an operand to the composite we are constructing
David Neto257c3892018-04-11 13:19:45 -04002411 Ops << MkId(ElementConstantID);
David Neto22f144c2017-06-12 14:26:21 -04002412 }
2413 } else if (Cst->isNullValue()) {
2414 Opcode = spv::OpConstantNull;
David Neto22f144c2017-06-12 14:26:21 -04002415 } else {
2416 Cst->print(errs());
2417 llvm_unreachable("Unsupported Constant???");
2418 }
2419
David Neto87846742018-04-11 17:36:22 -04002420 auto *CstInst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002421 SPIRVInstList.push_back(CstInst);
2422 }
2423}
2424
2425void SPIRVProducerPass::GenerateSamplers(Module &M) {
2426 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2427 ValueMapType &VMap = getValueMap();
2428
David Neto862b7d82018-06-14 18:48:37 -04002429 auto& sampler_map = getSamplerMap();
2430 SamplerMapIndexToIDMap.clear();
David Neto22f144c2017-06-12 14:26:21 -04002431 DenseMap<unsigned, unsigned> SamplerLiteralToIDMap;
David Neto862b7d82018-06-14 18:48:37 -04002432 DenseMap<unsigned, unsigned> SamplerLiteralToDescriptorSetMap;
2433 DenseMap<unsigned, unsigned> SamplerLiteralToBindingMap;
David Neto22f144c2017-06-12 14:26:21 -04002434
David Neto862b7d82018-06-14 18:48:37 -04002435 // We might have samplers in the sampler map that are not used
2436 // in the translation unit. We need to allocate variables
2437 // for them and bindings too.
2438 DenseSet<unsigned> used_bindings;
David Neto22f144c2017-06-12 14:26:21 -04002439
David Neto862b7d82018-06-14 18:48:37 -04002440 auto* var_fn = M.getFunction("clspv.sampler.var.literal");
2441 if (!var_fn) return;
2442 for (auto user : var_fn->users()) {
2443 // Populate SamplerLiteralToDescriptorSetMap and
2444 // SamplerLiteralToBindingMap.
2445 //
2446 // Look for calls like
2447 // call %opencl.sampler_t addrspace(2)*
2448 // @clspv.sampler.var.literal(
2449 // i32 descriptor,
2450 // i32 binding,
2451 // i32 index-into-sampler-map)
2452 if (auto* call = dyn_cast<CallInst>(user)) {
2453 const auto index_into_sampler_map =
2454 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue();
2455 if (index_into_sampler_map >= sampler_map.size()) {
2456 errs() << "Out of bounds index to sampler map: " << index_into_sampler_map;
2457 llvm_unreachable("bad sampler init: out of bounds");
2458 }
2459
2460 auto sampler_value = sampler_map[index_into_sampler_map].first;
2461 const auto descriptor_set = static_cast<unsigned>(
2462 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
2463 const auto binding = static_cast<unsigned>(
2464 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
2465
2466 SamplerLiteralToDescriptorSetMap[sampler_value] = descriptor_set;
2467 SamplerLiteralToBindingMap[sampler_value] = binding;
2468 used_bindings.insert(binding);
2469 }
2470 }
2471
2472 unsigned index = 0;
2473 for (auto SamplerLiteral : sampler_map) {
David Neto22f144c2017-06-12 14:26:21 -04002474 // Generate OpVariable.
2475 //
2476 // GIDOps[0] : Result Type ID
2477 // GIDOps[1] : Storage Class
2478 SPIRVOperandList Ops;
2479
David Neto257c3892018-04-11 13:19:45 -04002480 Ops << MkId(lookupType(SamplerTy))
2481 << MkNum(spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002482
David Neto862b7d82018-06-14 18:48:37 -04002483 auto sampler_var_id = nextID++;
2484 auto *Inst = new SPIRVInstruction(spv::OpVariable, sampler_var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002485 SPIRVInstList.push_back(Inst);
2486
David Neto862b7d82018-06-14 18:48:37 -04002487 SamplerMapIndexToIDMap[index] = sampler_var_id;
2488 SamplerLiteralToIDMap[SamplerLiteral.first] = sampler_var_id;
David Neto22f144c2017-06-12 14:26:21 -04002489
2490 // Find Insert Point for OpDecorate.
2491 auto DecoInsertPoint =
2492 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2493 [](SPIRVInstruction *Inst) -> bool {
2494 return Inst->getOpcode() != spv::OpDecorate &&
2495 Inst->getOpcode() != spv::OpMemberDecorate &&
2496 Inst->getOpcode() != spv::OpExtInstImport;
2497 });
2498
2499 // Ops[0] = Target ID
2500 // Ops[1] = Decoration (DescriptorSet)
2501 // Ops[2] = LiteralNumber according to Decoration
2502 Ops.clear();
2503
David Neto862b7d82018-06-14 18:48:37 -04002504 unsigned descriptor_set;
2505 unsigned binding;
2506 if(SamplerLiteralToBindingMap.find(SamplerLiteral.first) == SamplerLiteralToBindingMap.end()) {
2507 // This sampler is not actually used. Find the next one.
2508 for (binding = 0; used_bindings.count(binding); binding++)
2509 ;
2510 descriptor_set = 0; // Literal samplers always use descriptor set 0.
2511 used_bindings.insert(binding);
2512 } else {
2513 descriptor_set = SamplerLiteralToDescriptorSetMap[SamplerLiteral.first];
2514 binding = SamplerLiteralToBindingMap[SamplerLiteral.first];
2515 }
2516
2517 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationDescriptorSet)
2518 << MkNum(descriptor_set);
David Neto22f144c2017-06-12 14:26:21 -04002519
David Neto44795152017-07-13 15:45:28 -04002520 descriptorMapOut << "sampler," << SamplerLiteral.first << ",samplerExpr,\""
David Neto257c3892018-04-11 13:19:45 -04002521 << SamplerLiteral.second << "\",descriptorSet,"
David Neto862b7d82018-06-14 18:48:37 -04002522 << descriptor_set << ",binding," << binding << "\n";
David Neto22f144c2017-06-12 14:26:21 -04002523
David Neto87846742018-04-11 17:36:22 -04002524 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002525 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2526
2527 // Ops[0] = Target ID
2528 // Ops[1] = Decoration (Binding)
2529 // Ops[2] = LiteralNumber according to Decoration
2530 Ops.clear();
David Neto862b7d82018-06-14 18:48:37 -04002531 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationBinding)
2532 << MkNum(binding);
David Neto22f144c2017-06-12 14:26:21 -04002533
David Neto87846742018-04-11 17:36:22 -04002534 auto *BindDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002535 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
David Neto862b7d82018-06-14 18:48:37 -04002536
2537 index++;
David Neto22f144c2017-06-12 14:26:21 -04002538 }
David Neto862b7d82018-06-14 18:48:37 -04002539}
David Neto22f144c2017-06-12 14:26:21 -04002540
David Neto862b7d82018-06-14 18:48:37 -04002541void SPIRVProducerPass::GenerateResourceVars(Module &M) {
2542 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2543 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04002544
David Neto862b7d82018-06-14 18:48:37 -04002545 // Generate variables. Make one for each of resource var info object.
2546 for (auto *info : ModuleOrderedResourceVars) {
2547 Type *type = info->var_fn->getReturnType();
2548 // Remap the address space for opaque types.
2549 switch (info->arg_kind) {
2550 case clspv::ArgKind::Sampler:
2551 case clspv::ArgKind::ReadOnlyImage:
2552 case clspv::ArgKind::WriteOnlyImage:
2553 type = PointerType::get(type->getPointerElementType(),
2554 clspv::AddressSpace::UniformConstant);
2555 break;
2556 default:
2557 break;
2558 }
David Neto22f144c2017-06-12 14:26:21 -04002559
David Neto862b7d82018-06-14 18:48:37 -04002560 info->var_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04002561
David Neto862b7d82018-06-14 18:48:37 -04002562 const auto type_id = lookupType(type);
2563 const auto sc = GetStorageClassForArgKind(info->arg_kind);
2564 SPIRVOperandList Ops;
2565 Ops << MkId(type_id) << MkNum(sc);
David Neto22f144c2017-06-12 14:26:21 -04002566
David Neto862b7d82018-06-14 18:48:37 -04002567 auto *Inst = new SPIRVInstruction(spv::OpVariable, info->var_id, Ops);
2568 SPIRVInstList.push_back(Inst);
2569
2570 // Map calls to the variable-builtin-function.
2571 for (auto &U : info->var_fn->uses()) {
2572 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
2573 const auto set = unsigned(
2574 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
2575 const auto binding = unsigned(
2576 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
2577 if (set == info->descriptor_set && binding == info->binding) {
2578 switch (info->arg_kind) {
2579 case clspv::ArgKind::Buffer:
2580 case clspv::ArgKind::Pod:
2581 // The call maps to the variable directly.
2582 VMap[call] = info->var_id;
2583 break;
2584 case clspv::ArgKind::Sampler:
2585 case clspv::ArgKind::ReadOnlyImage:
2586 case clspv::ArgKind::WriteOnlyImage:
2587 // The call maps to a load we generate later.
2588 ResourceVarDeferredLoadCalls[call] = info->var_id;
2589 break;
2590 default:
2591 llvm_unreachable("Unhandled arg kind");
2592 }
2593 }
David Neto22f144c2017-06-12 14:26:21 -04002594 }
David Neto862b7d82018-06-14 18:48:37 -04002595 }
2596 }
David Neto22f144c2017-06-12 14:26:21 -04002597
David Neto862b7d82018-06-14 18:48:37 -04002598 // Generate associated decorations.
David Neto22f144c2017-06-12 14:26:21 -04002599
David Neto862b7d82018-06-14 18:48:37 -04002600 // Find Insert Point for OpDecorate.
2601 auto DecoInsertPoint =
2602 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2603 [](SPIRVInstruction *Inst) -> bool {
2604 return Inst->getOpcode() != spv::OpDecorate &&
2605 Inst->getOpcode() != spv::OpMemberDecorate &&
2606 Inst->getOpcode() != spv::OpExtInstImport;
2607 });
2608
2609 SPIRVOperandList Ops;
2610 for (auto *info : ModuleOrderedResourceVars) {
2611 // Decorate with DescriptorSet and Binding.
2612 Ops.clear();
2613 Ops << MkId(info->var_id) << MkNum(spv::DecorationDescriptorSet)
2614 << MkNum(info->descriptor_set);
2615 SPIRVInstList.insert(DecoInsertPoint,
2616 new SPIRVInstruction(spv::OpDecorate, Ops));
2617
2618 Ops.clear();
2619 Ops << MkId(info->var_id) << MkNum(spv::DecorationBinding)
2620 << MkNum(info->binding);
2621 SPIRVInstList.insert(DecoInsertPoint,
2622 new SPIRVInstruction(spv::OpDecorate, Ops));
2623
2624 // Generate NonWritable and NonReadable
2625 switch (info->arg_kind) {
2626 case clspv::ArgKind::Buffer:
2627 if (info->var_fn->getReturnType()->getPointerAddressSpace() ==
2628 clspv::AddressSpace::Constant) {
2629 Ops.clear();
2630 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
2631 SPIRVInstList.insert(DecoInsertPoint,
2632 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002633 }
David Neto862b7d82018-06-14 18:48:37 -04002634 break;
2635 case clspv::ArgKind::ReadOnlyImage:
2636 Ops.clear();
2637 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
2638 SPIRVInstList.insert(DecoInsertPoint,
2639 new SPIRVInstruction(spv::OpDecorate, Ops));
2640 break;
2641 case clspv::ArgKind::WriteOnlyImage:
2642 Ops.clear();
2643 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonReadable);
2644 SPIRVInstList.insert(DecoInsertPoint,
2645 new SPIRVInstruction(spv::OpDecorate, Ops));
2646 break;
2647 default:
2648 break;
David Neto22f144c2017-06-12 14:26:21 -04002649 }
2650 }
2651}
2652
2653void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
David Neto78383442018-06-15 20:31:56 -04002654 Module& M = *GV.getParent();
David Neto22f144c2017-06-12 14:26:21 -04002655 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2656 ValueMapType &VMap = getValueMap();
2657 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07002658 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002659
2660 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2661 Type *Ty = GV.getType();
2662 PointerType *PTy = cast<PointerType>(Ty);
2663
2664 uint32_t InitializerID = 0;
2665
2666 // Workgroup size is handled differently (it goes into a constant)
2667 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2668 std::vector<bool> HasMDVec;
2669 uint32_t PrevXDimCst = 0xFFFFFFFF;
2670 uint32_t PrevYDimCst = 0xFFFFFFFF;
2671 uint32_t PrevZDimCst = 0xFFFFFFFF;
2672 for (Function &Func : *GV.getParent()) {
2673 if (Func.isDeclaration()) {
2674 continue;
2675 }
2676
2677 // We only need to check kernels.
2678 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2679 continue;
2680 }
2681
2682 if (const MDNode *MD =
2683 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2684 uint32_t CurXDimCst = static_cast<uint32_t>(
2685 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2686 uint32_t CurYDimCst = static_cast<uint32_t>(
2687 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2688 uint32_t CurZDimCst = static_cast<uint32_t>(
2689 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2690
2691 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2692 PrevZDimCst == 0xFFFFFFFF) {
2693 PrevXDimCst = CurXDimCst;
2694 PrevYDimCst = CurYDimCst;
2695 PrevZDimCst = CurZDimCst;
2696 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2697 CurZDimCst != PrevZDimCst) {
2698 llvm_unreachable(
2699 "reqd_work_group_size must be the same across all kernels");
2700 } else {
2701 continue;
2702 }
2703
2704 //
2705 // Generate OpConstantComposite.
2706 //
2707 // Ops[0] : Result Type ID
2708 // Ops[1] : Constant size for x dimension.
2709 // Ops[2] : Constant size for y dimension.
2710 // Ops[3] : Constant size for z dimension.
2711 SPIRVOperandList Ops;
2712
2713 uint32_t XDimCstID =
2714 VMap[mdconst::extract<ConstantInt>(MD->getOperand(0))];
2715 uint32_t YDimCstID =
2716 VMap[mdconst::extract<ConstantInt>(MD->getOperand(1))];
2717 uint32_t ZDimCstID =
2718 VMap[mdconst::extract<ConstantInt>(MD->getOperand(2))];
2719
2720 InitializerID = nextID;
2721
David Neto257c3892018-04-11 13:19:45 -04002722 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2723 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002724
David Neto87846742018-04-11 17:36:22 -04002725 auto *Inst =
2726 new SPIRVInstruction(spv::OpConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002727 SPIRVInstList.push_back(Inst);
2728
2729 HasMDVec.push_back(true);
2730 } else {
2731 HasMDVec.push_back(false);
2732 }
2733 }
2734
2735 // Check all kernels have same definitions for work_group_size.
2736 bool HasMD = false;
2737 if (!HasMDVec.empty()) {
2738 HasMD = HasMDVec[0];
2739 for (uint32_t i = 1; i < HasMDVec.size(); i++) {
2740 if (HasMD != HasMDVec[i]) {
2741 llvm_unreachable(
2742 "Kernels should have consistent work group size definition");
2743 }
2744 }
2745 }
2746
2747 // If all kernels do not have metadata for reqd_work_group_size, generate
2748 // OpSpecConstants for x/y/z dimension.
2749 if (!HasMD) {
2750 //
2751 // Generate OpSpecConstants for x/y/z dimension.
2752 //
2753 // Ops[0] : Result Type ID
2754 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
2755 uint32_t XDimCstID = 0;
2756 uint32_t YDimCstID = 0;
2757 uint32_t ZDimCstID = 0;
2758
David Neto22f144c2017-06-12 14:26:21 -04002759 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04002760 uint32_t result_type_id =
2761 lookupType(Ty->getPointerElementType()->getSequentialElementType());
David Neto22f144c2017-06-12 14:26:21 -04002762
David Neto257c3892018-04-11 13:19:45 -04002763 // X Dimension
2764 Ops << MkId(result_type_id) << MkNum(1);
2765 XDimCstID = nextID++;
2766 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002767 new SPIRVInstruction(spv::OpSpecConstant, XDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002768
2769 // Y Dimension
2770 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002771 Ops << MkId(result_type_id) << MkNum(1);
2772 YDimCstID = nextID++;
2773 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002774 new SPIRVInstruction(spv::OpSpecConstant, YDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002775
2776 // Z Dimension
2777 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002778 Ops << MkId(result_type_id) << MkNum(1);
2779 ZDimCstID = nextID++;
2780 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002781 new SPIRVInstruction(spv::OpSpecConstant, ZDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002782
David Neto22f144c2017-06-12 14:26:21 -04002783
David Neto257c3892018-04-11 13:19:45 -04002784 BuiltinDimVec.push_back(XDimCstID);
2785 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002786 BuiltinDimVec.push_back(ZDimCstID);
2787
David Neto22f144c2017-06-12 14:26:21 -04002788
2789 //
2790 // Generate OpSpecConstantComposite.
2791 //
2792 // Ops[0] : Result Type ID
2793 // Ops[1] : Constant size for x dimension.
2794 // Ops[2] : Constant size for y dimension.
2795 // Ops[3] : Constant size for z dimension.
2796 InitializerID = nextID;
2797
2798 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002799 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2800 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002801
David Neto87846742018-04-11 17:36:22 -04002802 auto *Inst =
2803 new SPIRVInstruction(spv::OpSpecConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002804 SPIRVInstList.push_back(Inst);
2805 }
2806 }
2807
David Neto22f144c2017-06-12 14:26:21 -04002808 VMap[&GV] = nextID;
2809
2810 //
2811 // Generate OpVariable.
2812 //
2813 // GIDOps[0] : Result Type ID
2814 // GIDOps[1] : Storage Class
2815 SPIRVOperandList Ops;
2816
David Neto85082642018-03-24 06:55:20 -07002817 const auto AS = PTy->getAddressSpace();
David Netoc6f3ab22018-04-06 18:02:31 -04002818 Ops << MkId(lookupType(Ty)) << MkNum(GetStorageClass(AS));
David Neto22f144c2017-06-12 14:26:21 -04002819
David Neto85082642018-03-24 06:55:20 -07002820 if (GV.hasInitializer()) {
2821 InitializerID = VMap[GV.getInitializer()];
David Neto22f144c2017-06-12 14:26:21 -04002822 }
2823
David Neto85082642018-03-24 06:55:20 -07002824 const bool module_scope_constant_external_init =
David Neto862b7d82018-06-14 18:48:37 -04002825 (AS == AddressSpace::Constant) && GV.hasInitializer() &&
David Neto85082642018-03-24 06:55:20 -07002826 clspv::Option::ModuleConstantsInStorageBuffer();
2827
2828 if (0 != InitializerID) {
2829 if (!module_scope_constant_external_init) {
2830 // Emit the ID of the intiializer as part of the variable definition.
David Netoc6f3ab22018-04-06 18:02:31 -04002831 Ops << MkId(InitializerID);
David Neto85082642018-03-24 06:55:20 -07002832 }
2833 }
2834 const uint32_t var_id = nextID++;
2835
David Neto87846742018-04-11 17:36:22 -04002836 auto *Inst = new SPIRVInstruction(spv::OpVariable, var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002837 SPIRVInstList.push_back(Inst);
2838
2839 // If we have a builtin.
2840 if (spv::BuiltInMax != BuiltinType) {
2841 // Find Insert Point for OpDecorate.
2842 auto DecoInsertPoint =
2843 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2844 [](SPIRVInstruction *Inst) -> bool {
2845 return Inst->getOpcode() != spv::OpDecorate &&
2846 Inst->getOpcode() != spv::OpMemberDecorate &&
2847 Inst->getOpcode() != spv::OpExtInstImport;
2848 });
2849 //
2850 // Generate OpDecorate.
2851 //
2852 // DOps[0] = Target ID
2853 // DOps[1] = Decoration (Builtin)
2854 // DOps[2] = BuiltIn ID
2855 uint32_t ResultID;
2856
2857 // WorkgroupSize is different, we decorate the constant composite that has
2858 // its value, rather than the variable that we use to access the value.
2859 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2860 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04002861 // Save both the value and variable IDs for later.
2862 WorkgroupSizeValueID = InitializerID;
2863 WorkgroupSizeVarID = VMap[&GV];
David Neto22f144c2017-06-12 14:26:21 -04002864 } else {
2865 ResultID = VMap[&GV];
2866 }
2867
2868 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002869 DOps << MkId(ResultID) << MkNum(spv::DecorationBuiltIn)
2870 << MkNum(BuiltinType);
David Neto22f144c2017-06-12 14:26:21 -04002871
David Neto87846742018-04-11 17:36:22 -04002872 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, DOps);
David Neto22f144c2017-06-12 14:26:21 -04002873 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
David Neto85082642018-03-24 06:55:20 -07002874 } else if (module_scope_constant_external_init) {
2875 // This module scope constant is initialized from a storage buffer with data
2876 // provided by the host at binding 0 of the next descriptor set.
David Neto78383442018-06-15 20:31:56 -04002877 const uint32_t descriptor_set = TakeDescriptorIndex(&M);
David Neto85082642018-03-24 06:55:20 -07002878
David Neto862b7d82018-06-14 18:48:37 -04002879 // Emit the intializer to the descriptor map file.
David Neto85082642018-03-24 06:55:20 -07002880 // Use "kind,buffer" to indicate storage buffer. We might want to expand
2881 // that later to other types, like uniform buffer.
2882 descriptorMapOut << "constant,descriptorSet," << descriptor_set
2883 << ",binding,0,kind,buffer,hexbytes,";
2884 clspv::ConstantEmitter(DL, descriptorMapOut).Emit(GV.getInitializer());
2885 descriptorMapOut << "\n";
2886
2887 // Find Insert Point for OpDecorate.
2888 auto DecoInsertPoint =
2889 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2890 [](SPIRVInstruction *Inst) -> bool {
2891 return Inst->getOpcode() != spv::OpDecorate &&
2892 Inst->getOpcode() != spv::OpMemberDecorate &&
2893 Inst->getOpcode() != spv::OpExtInstImport;
2894 });
2895
David Neto257c3892018-04-11 13:19:45 -04002896 // OpDecorate %var Binding <binding>
David Neto85082642018-03-24 06:55:20 -07002897 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002898 DOps << MkId(var_id) << MkNum(spv::DecorationBinding) << MkNum(0);
2899 DecoInsertPoint = SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04002900 DecoInsertPoint, new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto85082642018-03-24 06:55:20 -07002901
2902 // OpDecorate %var DescriptorSet <descriptor_set>
2903 DOps.clear();
David Neto257c3892018-04-11 13:19:45 -04002904 DOps << MkId(var_id) << MkNum(spv::DecorationDescriptorSet)
2905 << MkNum(descriptor_set);
David Netoc6f3ab22018-04-06 18:02:31 -04002906 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04002907 new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto22f144c2017-06-12 14:26:21 -04002908 }
2909}
2910
David Netoc6f3ab22018-04-06 18:02:31 -04002911void SPIRVProducerPass::GenerateWorkgroupVars() {
2912 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
Alan Baker202c8c72018-08-13 13:47:44 -04002913 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2914 ++spec_id) {
2915 LocalArgInfo& info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002916
2917 // Generate OpVariable.
2918 //
2919 // GIDOps[0] : Result Type ID
2920 // GIDOps[1] : Storage Class
2921 SPIRVOperandList Ops;
2922 Ops << MkId(info.ptr_array_type_id) << MkNum(spv::StorageClassWorkgroup);
2923
2924 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002925 new SPIRVInstruction(spv::OpVariable, info.variable_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002926 }
2927}
2928
David Neto862b7d82018-06-14 18:48:37 -04002929void SPIRVProducerPass::GenerateDescriptorMapInfo(const DataLayout &DL,
2930 Function &F) {
David Netoc5fb5242018-07-30 13:28:31 -04002931 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2932 return;
2933 }
David Neto862b7d82018-06-14 18:48:37 -04002934 // Gather the list of resources that are used by this function's arguments.
2935 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
2936
2937 auto remap_arg_kind = [](StringRef argKind) {
2938 return clspv::Option::PodArgsInUniformBuffer() && argKind.equals("pod")
2939 ? "pod_ubo"
2940 : argKind;
2941 };
2942
2943 auto *fty = F.getType()->getPointerElementType();
2944 auto *func_ty = dyn_cast<FunctionType>(fty);
2945
2946 // If we've clustereed POD arguments, then argument details are in metadata.
2947 // If an argument maps to a resource variable, then get descriptor set and
2948 // binding from the resoure variable. Other info comes from the metadata.
2949 const auto *arg_map = F.getMetadata("kernel_arg_map");
2950 if (arg_map) {
2951 for (const auto &arg : arg_map->operands()) {
2952 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
2953 assert(arg_node->getNumOperands() == 6);
2954 const auto name =
2955 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
2956 const auto old_index =
2957 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
2958 // Remapped argument index
2959 const auto new_index =
2960 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getZExtValue();
2961 const auto offset =
2962 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
2963 const auto argKind = remap_arg_kind(
2964 dyn_cast<MDString>(arg_node->getOperand(4))->getString());
2965 const auto spec_id =
2966 dyn_extract<ConstantInt>(arg_node->getOperand(5))->getSExtValue();
2967 if (spec_id > 0) {
2968 // This was a pointer-to-local argument. It is not associated with a
2969 // resource variable.
2970 descriptorMapOut << "kernel," << F.getName() << ",arg," << name
2971 << ",argOrdinal," << old_index << ",argKind,"
2972 << argKind << ",arrayElemSize,"
2973 << DL.getTypeAllocSize(
2974 func_ty->getParamType(unsigned(new_index))
2975 ->getPointerElementType())
2976 << ",arrayNumElemSpecId," << spec_id << "\n";
2977 } else {
2978 auto *info = resource_var_at_index[new_index];
2979 assert(info);
2980 descriptorMapOut << "kernel," << F.getName() << ",arg," << name
2981 << ",argOrdinal," << old_index << ",descriptorSet,"
2982 << info->descriptor_set << ",binding," << info->binding
2983 << ",offset," << offset << ",argKind," << argKind
2984 << "\n";
2985 }
2986 }
2987 } else {
2988 // There is no argument map.
2989 // Take descriptor info from the resource variable calls.
2990 // Take argument name from the arguments list.
2991
2992 SmallVector<Argument *, 4> arguments;
2993 for (auto &arg : F.args()) {
2994 arguments.push_back(&arg);
2995 }
2996
2997 unsigned arg_index = 0;
2998 for (auto *info : resource_var_at_index) {
2999 if (info) {
3000 descriptorMapOut << "kernel," << F.getName() << ",arg,"
3001 << arguments[arg_index]->getName() << ",argOrdinal,"
3002 << arg_index << ",descriptorSet,"
3003 << info->descriptor_set << ",binding," << info->binding
3004 << ",offset," << 0 << ",argKind,"
3005 << remap_arg_kind(
3006 clspv::GetArgKindName(info->arg_kind))
3007 << "\n";
3008 }
3009 arg_index++;
3010 }
3011 // Generate mappings for pointer-to-local arguments.
3012 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
3013 Argument *arg = arguments[arg_index];
Alan Baker202c8c72018-08-13 13:47:44 -04003014 auto where = LocalArgSpecIds.find(arg);
3015 if (where != LocalArgSpecIds.end()) {
3016 auto &local_arg_info = LocalSpecIdInfoMap[where->second];
David Neto862b7d82018-06-14 18:48:37 -04003017 descriptorMapOut << "kernel," << F.getName() << ",arg,"
3018 << arg->getName() << ",argOrdinal," << arg_index
3019 << ",argKind,"
3020 << "local"
3021 << ",arrayElemSize,"
3022 << DL.getTypeAllocSize(local_arg_info.elem_type)
3023 << ",arrayNumElemSpecId," << local_arg_info.spec_id
3024 << "\n";
3025 }
3026 }
3027 }
3028}
3029
David Neto22f144c2017-06-12 14:26:21 -04003030void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
David Neto78383442018-06-15 20:31:56 -04003031 Module& M = *F.getParent();
3032 const DataLayout &DL = M.getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04003033 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3034 ValueMapType &VMap = getValueMap();
3035 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04003036 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
3037 auto &GlobalConstArgSet = getGlobalConstArgSet();
3038
3039 FunctionType *FTy = F.getFunctionType();
3040
3041 //
David Neto22f144c2017-06-12 14:26:21 -04003042 // Generate OPFunction.
3043 //
3044
3045 // FOps[0] : Result Type ID
3046 // FOps[1] : Function Control
3047 // FOps[2] : Function Type ID
3048 SPIRVOperandList FOps;
3049
3050 // Find SPIRV instruction for return type.
David Neto257c3892018-04-11 13:19:45 -04003051 FOps << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04003052
3053 // Check function attributes for SPIRV Function Control.
3054 uint32_t FuncControl = spv::FunctionControlMaskNone;
3055 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
3056 FuncControl |= spv::FunctionControlInlineMask;
3057 }
3058 if (F.hasFnAttribute(Attribute::NoInline)) {
3059 FuncControl |= spv::FunctionControlDontInlineMask;
3060 }
3061 // TODO: Check llvm attribute for Function Control Pure.
3062 if (F.hasFnAttribute(Attribute::ReadOnly)) {
3063 FuncControl |= spv::FunctionControlPureMask;
3064 }
3065 // TODO: Check llvm attribute for Function Control Const.
3066 if (F.hasFnAttribute(Attribute::ReadNone)) {
3067 FuncControl |= spv::FunctionControlConstMask;
3068 }
3069
David Neto257c3892018-04-11 13:19:45 -04003070 FOps << MkNum(FuncControl);
David Neto22f144c2017-06-12 14:26:21 -04003071
3072 uint32_t FTyID;
3073 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3074 SmallVector<Type *, 4> NewFuncParamTys;
3075 FunctionType *NewFTy =
3076 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
3077 FTyID = lookupType(NewFTy);
3078 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07003079 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04003080 if (GlobalConstFuncTyMap.count(FTy)) {
3081 FTyID = lookupType(GlobalConstFuncTyMap[FTy].first);
3082 } else {
3083 FTyID = lookupType(FTy);
3084 }
3085 }
3086
David Neto257c3892018-04-11 13:19:45 -04003087 FOps << MkId(FTyID);
David Neto22f144c2017-06-12 14:26:21 -04003088
3089 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3090 EntryPoints.push_back(std::make_pair(&F, nextID));
3091 }
3092
3093 VMap[&F] = nextID;
3094
David Neto482550a2018-03-24 05:21:07 -07003095 if (clspv::Option::ShowIDs()) {
David Netob05675d2018-02-16 12:37:49 -05003096 errs() << "Function " << F.getName() << " is " << nextID << "\n";
3097 }
David Neto22f144c2017-06-12 14:26:21 -04003098 // Generate SPIRV instruction for function.
David Neto87846742018-04-11 17:36:22 -04003099 auto *FuncInst = new SPIRVInstruction(spv::OpFunction, nextID++, FOps);
David Neto22f144c2017-06-12 14:26:21 -04003100 SPIRVInstList.push_back(FuncInst);
3101
3102 //
3103 // Generate OpFunctionParameter for Normal function.
3104 //
3105
3106 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3107 // Iterate Argument for name instead of param type from function type.
3108 unsigned ArgIdx = 0;
3109 for (Argument &Arg : F.args()) {
3110 VMap[&Arg] = nextID;
3111
3112 // ParamOps[0] : Result Type ID
3113 SPIRVOperandList ParamOps;
3114
3115 // Find SPIRV instruction for parameter type.
3116 uint32_t ParamTyID = lookupType(Arg.getType());
3117 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
3118 if (GlobalConstFuncTyMap.count(FTy)) {
3119 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
3120 Type *EleTy = PTy->getPointerElementType();
3121 Type *ArgTy =
3122 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
3123 ParamTyID = lookupType(ArgTy);
3124 GlobalConstArgSet.insert(&Arg);
3125 }
3126 }
3127 }
David Neto257c3892018-04-11 13:19:45 -04003128 ParamOps << MkId(ParamTyID);
David Neto22f144c2017-06-12 14:26:21 -04003129
3130 // Generate SPIRV instruction for parameter.
David Neto87846742018-04-11 17:36:22 -04003131 auto *ParamInst =
3132 new SPIRVInstruction(spv::OpFunctionParameter, nextID++, ParamOps);
David Neto22f144c2017-06-12 14:26:21 -04003133 SPIRVInstList.push_back(ParamInst);
3134
3135 ArgIdx++;
3136 }
3137 }
3138}
3139
David Neto5c22a252018-03-15 16:07:41 -04003140void SPIRVProducerPass::GenerateModuleInfo(Module& module) {
David Neto22f144c2017-06-12 14:26:21 -04003141 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3142 EntryPointVecType &EntryPoints = getEntryPointVec();
3143 ValueMapType &VMap = getValueMap();
3144 ValueList &EntryPointInterfaces = getEntryPointInterfacesVec();
3145 uint32_t &ExtInstImportID = getOpExtInstImportID();
3146 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
3147
3148 // Set up insert point.
3149 auto InsertPoint = SPIRVInstList.begin();
3150
3151 //
3152 // Generate OpCapability
3153 //
3154 // TODO: Which llvm information is mapped to SPIRV Capapbility?
3155
3156 // Ops[0] = Capability
3157 SPIRVOperandList Ops;
3158
David Neto87846742018-04-11 17:36:22 -04003159 auto *CapInst =
3160 new SPIRVInstruction(spv::OpCapability, {MkNum(spv::CapabilityShader)});
David Neto22f144c2017-06-12 14:26:21 -04003161 SPIRVInstList.insert(InsertPoint, CapInst);
3162
3163 for (Type *Ty : getTypeList()) {
3164 // Find the i16 type.
3165 if (Ty->isIntegerTy(16)) {
3166 // Generate OpCapability for i16 type.
David Neto87846742018-04-11 17:36:22 -04003167 SPIRVInstList.insert(InsertPoint,
3168 new SPIRVInstruction(spv::OpCapability,
3169 {MkNum(spv::CapabilityInt16)}));
David Neto22f144c2017-06-12 14:26:21 -04003170 } else if (Ty->isIntegerTy(64)) {
3171 // Generate OpCapability for i64 type.
David Neto87846742018-04-11 17:36:22 -04003172 SPIRVInstList.insert(InsertPoint,
3173 new SPIRVInstruction(spv::OpCapability,
3174 {MkNum(spv::CapabilityInt64)}));
David Neto22f144c2017-06-12 14:26:21 -04003175 } else if (Ty->isHalfTy()) {
3176 // Generate OpCapability for half type.
3177 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003178 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3179 {MkNum(spv::CapabilityFloat16)}));
David Neto22f144c2017-06-12 14:26:21 -04003180 } else if (Ty->isDoubleTy()) {
3181 // Generate OpCapability for double type.
3182 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003183 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3184 {MkNum(spv::CapabilityFloat64)}));
David Neto22f144c2017-06-12 14:26:21 -04003185 } else if (auto *STy = dyn_cast<StructType>(Ty)) {
3186 if (STy->isOpaque()) {
David Neto565571c2017-08-21 12:00:05 -04003187 if (STy->getName().equals("opencl.image2d_wo_t") ||
3188 STy->getName().equals("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04003189 // Generate OpCapability for write only image type.
3190 SPIRVInstList.insert(
3191 InsertPoint,
3192 new SPIRVInstruction(
David Neto87846742018-04-11 17:36:22 -04003193 spv::OpCapability,
3194 {MkNum(spv::CapabilityStorageImageWriteWithoutFormat)}));
David Neto22f144c2017-06-12 14:26:21 -04003195 }
3196 }
3197 }
3198 }
3199
David Neto5c22a252018-03-15 16:07:41 -04003200 { // OpCapability ImageQuery
3201 bool hasImageQuery = false;
3202 for (const char *imageQuery : {
3203 "_Z15get_image_width14ocl_image2d_ro",
3204 "_Z15get_image_width14ocl_image2d_wo",
3205 "_Z16get_image_height14ocl_image2d_ro",
3206 "_Z16get_image_height14ocl_image2d_wo",
3207 }) {
3208 if (module.getFunction(imageQuery)) {
3209 hasImageQuery = true;
3210 break;
3211 }
3212 }
3213 if (hasImageQuery) {
David Neto87846742018-04-11 17:36:22 -04003214 auto *ImageQueryCapInst = new SPIRVInstruction(
3215 spv::OpCapability, {MkNum(spv::CapabilityImageQuery)});
David Neto5c22a252018-03-15 16:07:41 -04003216 SPIRVInstList.insert(InsertPoint, ImageQueryCapInst);
3217 }
3218 }
3219
David Neto22f144c2017-06-12 14:26:21 -04003220 if (hasVariablePointers()) {
3221 //
3222 // Generate OpCapability and OpExtension
3223 //
3224
3225 //
3226 // Generate OpCapability.
3227 //
3228 // Ops[0] = Capability
3229 //
3230 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003231 Ops << MkNum(spv::CapabilityVariablePointers);
David Neto22f144c2017-06-12 14:26:21 -04003232
David Neto87846742018-04-11 17:36:22 -04003233 SPIRVInstList.insert(InsertPoint,
3234 new SPIRVInstruction(spv::OpCapability, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003235
3236 //
3237 // Generate OpExtension.
3238 //
3239 // Ops[0] = Name (Literal String)
3240 //
David Netoa772fd12017-08-04 14:17:33 -04003241 for (auto extension : {"SPV_KHR_storage_buffer_storage_class",
3242 "SPV_KHR_variable_pointers"}) {
David Neto22f144c2017-06-12 14:26:21 -04003243
David Neto87846742018-04-11 17:36:22 -04003244 auto *ExtensionInst =
3245 new SPIRVInstruction(spv::OpExtension, {MkString(extension)});
David Netoa772fd12017-08-04 14:17:33 -04003246 SPIRVInstList.insert(InsertPoint, ExtensionInst);
David Neto22f144c2017-06-12 14:26:21 -04003247 }
David Neto22f144c2017-06-12 14:26:21 -04003248 }
3249
3250 if (ExtInstImportID) {
3251 ++InsertPoint;
3252 }
3253
3254 //
3255 // Generate OpMemoryModel
3256 //
3257 // Memory model for Vulkan will always be GLSL450.
3258
3259 // Ops[0] = Addressing Model
3260 // Ops[1] = Memory Model
3261 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003262 Ops << MkNum(spv::AddressingModelLogical) << MkNum(spv::MemoryModelGLSL450);
David Neto22f144c2017-06-12 14:26:21 -04003263
David Neto87846742018-04-11 17:36:22 -04003264 auto *MemModelInst = new SPIRVInstruction(spv::OpMemoryModel, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003265 SPIRVInstList.insert(InsertPoint, MemModelInst);
3266
3267 //
3268 // Generate OpEntryPoint
3269 //
3270 for (auto EntryPoint : EntryPoints) {
3271 // Ops[0] = Execution Model
3272 // Ops[1] = EntryPoint ID
3273 // Ops[2] = Name (Literal String)
3274 // ...
3275 //
3276 // TODO: Do we need to consider Interface ID for forward references???
3277 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003278 const StringRef& name = EntryPoint.first->getName();
3279 Ops << MkNum(spv::ExecutionModelGLCompute) << MkId(EntryPoint.second)
3280 << MkString(name);
David Neto22f144c2017-06-12 14:26:21 -04003281
David Neto22f144c2017-06-12 14:26:21 -04003282 for (Value *Interface : EntryPointInterfaces) {
David Neto257c3892018-04-11 13:19:45 -04003283 Ops << MkId(VMap[Interface]);
David Neto22f144c2017-06-12 14:26:21 -04003284 }
3285
David Neto87846742018-04-11 17:36:22 -04003286 auto *EntryPointInst = new SPIRVInstruction(spv::OpEntryPoint, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003287 SPIRVInstList.insert(InsertPoint, EntryPointInst);
3288 }
3289
3290 for (auto EntryPoint : EntryPoints) {
3291 if (const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
3292 ->getMetadata("reqd_work_group_size")) {
3293
3294 if (!BuiltinDimVec.empty()) {
3295 llvm_unreachable(
3296 "Kernels should have consistent work group size definition");
3297 }
3298
3299 //
3300 // Generate OpExecutionMode
3301 //
3302
3303 // Ops[0] = Entry Point ID
3304 // Ops[1] = Execution Mode
3305 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
3306 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003307 Ops << MkId(EntryPoint.second)
3308 << MkNum(spv::ExecutionModeLocalSize);
David Neto22f144c2017-06-12 14:26:21 -04003309
3310 uint32_t XDim = static_cast<uint32_t>(
3311 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3312 uint32_t YDim = static_cast<uint32_t>(
3313 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3314 uint32_t ZDim = static_cast<uint32_t>(
3315 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3316
David Neto257c3892018-04-11 13:19:45 -04003317 Ops << MkNum(XDim) << MkNum(YDim) << MkNum(ZDim);
David Neto22f144c2017-06-12 14:26:21 -04003318
David Neto87846742018-04-11 17:36:22 -04003319 auto *ExecModeInst = new SPIRVInstruction(spv::OpExecutionMode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003320 SPIRVInstList.insert(InsertPoint, ExecModeInst);
3321 }
3322 }
3323
3324 //
3325 // Generate OpSource.
3326 //
3327 // Ops[0] = SourceLanguage ID
3328 // Ops[1] = Version (LiteralNum)
3329 //
3330 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003331 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(120);
David Neto22f144c2017-06-12 14:26:21 -04003332
David Neto87846742018-04-11 17:36:22 -04003333 auto *OpenSourceInst = new SPIRVInstruction(spv::OpSource, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003334 SPIRVInstList.insert(InsertPoint, OpenSourceInst);
3335
3336 if (!BuiltinDimVec.empty()) {
3337 //
3338 // Generate OpDecorates for x/y/z dimension.
3339 //
3340 // Ops[0] = Target ID
3341 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04003342 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04003343
3344 // X Dimension
3345 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003346 Ops << MkId(BuiltinDimVec[0]) << MkNum(spv::DecorationSpecId) << MkNum(0);
David Neto87846742018-04-11 17:36:22 -04003347 SPIRVInstList.insert(InsertPoint,
3348 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003349
3350 // Y Dimension
3351 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003352 Ops << MkId(BuiltinDimVec[1]) << MkNum(spv::DecorationSpecId) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04003353 SPIRVInstList.insert(InsertPoint,
3354 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003355
3356 // Z Dimension
3357 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003358 Ops << MkId(BuiltinDimVec[2]) << MkNum(spv::DecorationSpecId) << MkNum(2);
David Neto87846742018-04-11 17:36:22 -04003359 SPIRVInstList.insert(InsertPoint,
3360 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003361 }
3362}
3363
David Netob6e2e062018-04-25 10:32:06 -04003364void SPIRVProducerPass::GenerateEntryPointInitialStores() {
3365 // Work around a driver bug. Initializers on Private variables might not
3366 // work. So the start of the kernel should store the initializer value to the
3367 // variables. Yes, *every* entry point pays this cost if *any* entry point
3368 // uses this builtin. At this point I judge this to be an acceptable tradeoff
3369 // of complexity vs. runtime, for a broken driver.
3370 // TODO(dneto): Remove this at some point once fixed drivers are widely available.
3371 if (WorkgroupSizeVarID) {
3372 assert(WorkgroupSizeValueID);
3373
3374 SPIRVOperandList Ops;
3375 Ops << MkId(WorkgroupSizeVarID) << MkId(WorkgroupSizeValueID);
3376
3377 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
3378 getSPIRVInstList().push_back(Inst);
3379 }
3380}
3381
David Neto22f144c2017-06-12 14:26:21 -04003382void SPIRVProducerPass::GenerateFuncBody(Function &F) {
3383 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3384 ValueMapType &VMap = getValueMap();
3385
David Netob6e2e062018-04-25 10:32:06 -04003386 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04003387
3388 for (BasicBlock &BB : F) {
3389 // Register BasicBlock to ValueMap.
3390 VMap[&BB] = nextID;
3391
3392 //
3393 // Generate OpLabel for Basic Block.
3394 //
3395 SPIRVOperandList Ops;
David Neto87846742018-04-11 17:36:22 -04003396 auto *Inst = new SPIRVInstruction(spv::OpLabel, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003397 SPIRVInstList.push_back(Inst);
3398
David Neto6dcd4712017-06-23 11:06:47 -04003399 // OpVariable instructions must come first.
3400 for (Instruction &I : BB) {
3401 if (isa<AllocaInst>(I)) {
3402 GenerateInstruction(I);
3403 }
3404 }
3405
David Neto22f144c2017-06-12 14:26:21 -04003406 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04003407 if (clspv::Option::HackInitializers()) {
3408 GenerateEntryPointInitialStores();
3409 }
David Neto22f144c2017-06-12 14:26:21 -04003410 }
3411
3412 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003413 if (!isa<AllocaInst>(I)) {
3414 GenerateInstruction(I);
3415 }
David Neto22f144c2017-06-12 14:26:21 -04003416 }
3417 }
3418}
3419
3420spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3421 const std::map<CmpInst::Predicate, spv::Op> Map = {
3422 {CmpInst::ICMP_EQ, spv::OpIEqual},
3423 {CmpInst::ICMP_NE, spv::OpINotEqual},
3424 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3425 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3426 {CmpInst::ICMP_ULT, spv::OpULessThan},
3427 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3428 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3429 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3430 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3431 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3432 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3433 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3434 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3435 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3436 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3437 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3438 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3439 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3440 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3441 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3442 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3443 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3444
3445 assert(0 != Map.count(I->getPredicate()));
3446
3447 return Map.at(I->getPredicate());
3448}
3449
3450spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3451 const std::map<unsigned, spv::Op> Map{
3452 {Instruction::Trunc, spv::OpUConvert},
3453 {Instruction::ZExt, spv::OpUConvert},
3454 {Instruction::SExt, spv::OpSConvert},
3455 {Instruction::FPToUI, spv::OpConvertFToU},
3456 {Instruction::FPToSI, spv::OpConvertFToS},
3457 {Instruction::UIToFP, spv::OpConvertUToF},
3458 {Instruction::SIToFP, spv::OpConvertSToF},
3459 {Instruction::FPTrunc, spv::OpFConvert},
3460 {Instruction::FPExt, spv::OpFConvert},
3461 {Instruction::BitCast, spv::OpBitcast}};
3462
3463 assert(0 != Map.count(I.getOpcode()));
3464
3465 return Map.at(I.getOpcode());
3466}
3467
3468spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
3469 if (I.getType()->isIntegerTy(1)) {
3470 switch (I.getOpcode()) {
3471 default:
3472 break;
3473 case Instruction::Or:
3474 return spv::OpLogicalOr;
3475 case Instruction::And:
3476 return spv::OpLogicalAnd;
3477 case Instruction::Xor:
3478 return spv::OpLogicalNotEqual;
3479 }
3480 }
3481
3482 const std::map<unsigned, spv::Op> Map {
3483 {Instruction::Add, spv::OpIAdd},
3484 {Instruction::FAdd, spv::OpFAdd},
3485 {Instruction::Sub, spv::OpISub},
3486 {Instruction::FSub, spv::OpFSub},
3487 {Instruction::Mul, spv::OpIMul},
3488 {Instruction::FMul, spv::OpFMul},
3489 {Instruction::UDiv, spv::OpUDiv},
3490 {Instruction::SDiv, spv::OpSDiv},
3491 {Instruction::FDiv, spv::OpFDiv},
3492 {Instruction::URem, spv::OpUMod},
3493 {Instruction::SRem, spv::OpSRem},
3494 {Instruction::FRem, spv::OpFRem},
3495 {Instruction::Or, spv::OpBitwiseOr},
3496 {Instruction::Xor, spv::OpBitwiseXor},
3497 {Instruction::And, spv::OpBitwiseAnd},
3498 {Instruction::Shl, spv::OpShiftLeftLogical},
3499 {Instruction::LShr, spv::OpShiftRightLogical},
3500 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3501
3502 assert(0 != Map.count(I.getOpcode()));
3503
3504 return Map.at(I.getOpcode());
3505}
3506
3507void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
3508 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3509 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04003510 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
3511 LLVMContext &Context = I.getParent()->getParent()->getParent()->getContext();
3512
3513 // Register Instruction to ValueMap.
3514 if (0 == VMap[&I]) {
3515 VMap[&I] = nextID;
3516 }
3517
3518 switch (I.getOpcode()) {
3519 default: {
3520 if (Instruction::isCast(I.getOpcode())) {
3521 //
3522 // Generate SPIRV instructions for cast operators.
3523 //
3524
David Netod2de94a2017-08-28 17:27:47 -04003525
3526 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003527 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003528 auto toI8 = Ty == Type::getInt8Ty(Context);
3529 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003530 // Handle zext, sext and uitofp with i1 type specially.
3531 if ((I.getOpcode() == Instruction::ZExt ||
3532 I.getOpcode() == Instruction::SExt ||
3533 I.getOpcode() == Instruction::UIToFP) &&
3534 (OpTy->isIntegerTy(1) ||
3535 (OpTy->isVectorTy() &&
3536 OpTy->getVectorElementType()->isIntegerTy(1)))) {
3537 //
3538 // Generate OpSelect.
3539 //
3540
3541 // Ops[0] = Result Type ID
3542 // Ops[1] = Condition ID
3543 // Ops[2] = True Constant ID
3544 // Ops[3] = False Constant ID
3545 SPIRVOperandList Ops;
3546
David Neto257c3892018-04-11 13:19:45 -04003547 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003548
David Neto22f144c2017-06-12 14:26:21 -04003549 uint32_t CondID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003550 Ops << MkId(CondID);
David Neto22f144c2017-06-12 14:26:21 -04003551
3552 uint32_t TrueID = 0;
3553 if (I.getOpcode() == Instruction::ZExt) {
3554 APInt One(32, 1);
3555 TrueID = VMap[Constant::getIntegerValue(I.getType(), One)];
3556 } else if (I.getOpcode() == Instruction::SExt) {
3557 APInt MinusOne(32, UINT64_MAX, true);
3558 TrueID = VMap[Constant::getIntegerValue(I.getType(), MinusOne)];
3559 } else {
3560 TrueID = VMap[ConstantFP::get(Context, APFloat(1.0f))];
3561 }
David Neto257c3892018-04-11 13:19:45 -04003562 Ops << MkId(TrueID);
David Neto22f144c2017-06-12 14:26:21 -04003563
3564 uint32_t FalseID = 0;
3565 if (I.getOpcode() == Instruction::ZExt) {
3566 FalseID = VMap[Constant::getNullValue(I.getType())];
3567 } else if (I.getOpcode() == Instruction::SExt) {
3568 FalseID = VMap[Constant::getNullValue(I.getType())];
3569 } else {
3570 FalseID = VMap[ConstantFP::get(Context, APFloat(0.0f))];
3571 }
David Neto257c3892018-04-11 13:19:45 -04003572 Ops << MkId(FalseID);
David Neto22f144c2017-06-12 14:26:21 -04003573
David Neto87846742018-04-11 17:36:22 -04003574 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003575 SPIRVInstList.push_back(Inst);
David Netod2de94a2017-08-28 17:27:47 -04003576 } else if (I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
3577 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3578 // 8 bits.
3579 // Before:
3580 // %result = trunc i32 %a to i8
3581 // After
3582 // %result = OpBitwiseAnd %uint %a %uint_255
3583
3584 SPIRVOperandList Ops;
3585
David Neto257c3892018-04-11 13:19:45 -04003586 Ops << MkId(lookupType(OpTy)) << MkId(VMap[I.getOperand(0)]);
David Netod2de94a2017-08-28 17:27:47 -04003587
3588 Type *UintTy = Type::getInt32Ty(Context);
3589 uint32_t MaskID = VMap[ConstantInt::get(UintTy, 255)];
David Neto257c3892018-04-11 13:19:45 -04003590 Ops << MkId(MaskID);
David Netod2de94a2017-08-28 17:27:47 -04003591
David Neto87846742018-04-11 17:36:22 -04003592 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Netod2de94a2017-08-28 17:27:47 -04003593 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003594 } else {
3595 // Ops[0] = Result Type ID
3596 // Ops[1] = Source Value ID
3597 SPIRVOperandList Ops;
3598
David Neto257c3892018-04-11 13:19:45 -04003599 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003600
David Neto87846742018-04-11 17:36:22 -04003601 auto *Inst = new SPIRVInstruction(GetSPIRVCastOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003602 SPIRVInstList.push_back(Inst);
3603 }
3604 } else if (isa<BinaryOperator>(I)) {
3605 //
3606 // Generate SPIRV instructions for binary operators.
3607 //
3608
3609 // Handle xor with i1 type specially.
3610 if (I.getOpcode() == Instruction::Xor &&
3611 I.getType() == Type::getInt1Ty(Context) &&
3612 (isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
3613 //
3614 // Generate OpLogicalNot.
3615 //
3616 // Ops[0] = Result Type ID
3617 // Ops[1] = Operand
3618 SPIRVOperandList Ops;
3619
David Neto257c3892018-04-11 13:19:45 -04003620 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003621
3622 Value *CondV = I.getOperand(0);
3623 if (isa<Constant>(I.getOperand(0))) {
3624 CondV = I.getOperand(1);
3625 }
David Neto257c3892018-04-11 13:19:45 -04003626 Ops << MkId(VMap[CondV]);
David Neto22f144c2017-06-12 14:26:21 -04003627
David Neto87846742018-04-11 17:36:22 -04003628 auto *Inst = new SPIRVInstruction(spv::OpLogicalNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003629 SPIRVInstList.push_back(Inst);
3630 } else {
3631 // Ops[0] = Result Type ID
3632 // Ops[1] = Operand 0
3633 // Ops[2] = Operand 1
3634 SPIRVOperandList Ops;
3635
David Neto257c3892018-04-11 13:19:45 -04003636 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
3637 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003638
David Neto87846742018-04-11 17:36:22 -04003639 auto *Inst =
3640 new SPIRVInstruction(GetSPIRVBinaryOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003641 SPIRVInstList.push_back(Inst);
3642 }
3643 } else {
3644 I.print(errs());
3645 llvm_unreachable("Unsupported instruction???");
3646 }
3647 break;
3648 }
3649 case Instruction::GetElementPtr: {
3650 auto &GlobalConstArgSet = getGlobalConstArgSet();
3651
3652 //
3653 // Generate OpAccessChain.
3654 //
3655 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
3656
3657 //
3658 // Generate OpAccessChain.
3659 //
3660
3661 // Ops[0] = Result Type ID
3662 // Ops[1] = Base ID
3663 // Ops[2] ... Ops[n] = Indexes ID
3664 SPIRVOperandList Ops;
3665
David Neto1a1a0582017-07-07 12:01:44 -04003666 PointerType* ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04003667 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
3668 GlobalConstArgSet.count(GEP->getPointerOperand())) {
3669 // Use pointer type with private address space for global constant.
3670 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04003671 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04003672 }
David Neto257c3892018-04-11 13:19:45 -04003673
3674 Ops << MkId(lookupType(ResultType));
David Neto22f144c2017-06-12 14:26:21 -04003675
David Neto862b7d82018-06-14 18:48:37 -04003676 // Generate the base pointer.
3677 Ops << MkId(VMap[GEP->getPointerOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04003678
David Neto862b7d82018-06-14 18:48:37 -04003679 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04003680
3681 //
3682 // Follows below rules for gep.
3683 //
David Neto862b7d82018-06-14 18:48:37 -04003684 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
3685 // first index.
David Neto22f144c2017-06-12 14:26:21 -04003686 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
3687 // first index.
3688 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
3689 // use gep's first index.
3690 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
3691 // gep's first index.
3692 //
3693 spv::Op Opcode = spv::OpAccessChain;
3694 unsigned offset = 0;
3695 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04003696 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04003697 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04003698 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04003699 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04003700 }
David Neto862b7d82018-06-14 18:48:37 -04003701 } else {
David Neto22f144c2017-06-12 14:26:21 -04003702 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04003703 }
3704
3705 if (Opcode == spv::OpPtrAccessChain) {
David Neto22f144c2017-06-12 14:26:21 -04003706 setVariablePointers(true);
David Neto1a1a0582017-07-07 12:01:44 -04003707 // Do we need to generate ArrayStride? Check against the GEP result type
3708 // rather than the pointer type of the base because when indexing into
3709 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
3710 // for something else in the SPIR-V.
3711 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
3712 if (GetStorageClass(ResultType->getAddressSpace()) ==
3713 spv::StorageClassStorageBuffer) {
3714 // Save the need to generate an ArrayStride decoration. But defer
3715 // generation until later, so we only make one decoration.
David Neto85082642018-03-24 06:55:20 -07003716 getTypesNeedingArrayStride().insert(ResultType);
David Neto1a1a0582017-07-07 12:01:44 -04003717 }
David Neto22f144c2017-06-12 14:26:21 -04003718 }
3719
3720 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
David Neto257c3892018-04-11 13:19:45 -04003721 Ops << MkId(VMap[*II]);
David Neto22f144c2017-06-12 14:26:21 -04003722 }
3723
David Neto87846742018-04-11 17:36:22 -04003724 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003725 SPIRVInstList.push_back(Inst);
3726 break;
3727 }
3728 case Instruction::ExtractValue: {
3729 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3730 // Ops[0] = Result Type ID
3731 // Ops[1] = Composite ID
3732 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3733 SPIRVOperandList Ops;
3734
David Neto257c3892018-04-11 13:19:45 -04003735 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003736
3737 uint32_t CompositeID = VMap[EVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003738 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003739
3740 for (auto &Index : EVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003741 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003742 }
3743
David Neto87846742018-04-11 17:36:22 -04003744 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003745 SPIRVInstList.push_back(Inst);
3746 break;
3747 }
3748 case Instruction::InsertValue: {
3749 InsertValueInst *IVI = cast<InsertValueInst>(&I);
3750 // Ops[0] = Result Type ID
3751 // Ops[1] = Object ID
3752 // Ops[2] = Composite ID
3753 // Ops[3] ... Ops[n] = Indexes (Literal Number)
3754 SPIRVOperandList Ops;
3755
3756 uint32_t ResTyID = lookupType(I.getType());
David Neto257c3892018-04-11 13:19:45 -04003757 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04003758
3759 uint32_t ObjectID = VMap[IVI->getInsertedValueOperand()];
David Neto257c3892018-04-11 13:19:45 -04003760 Ops << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04003761
3762 uint32_t CompositeID = VMap[IVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003763 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003764
3765 for (auto &Index : IVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003766 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003767 }
3768
David Neto87846742018-04-11 17:36:22 -04003769 auto *Inst = new SPIRVInstruction(spv::OpCompositeInsert, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003770 SPIRVInstList.push_back(Inst);
3771 break;
3772 }
3773 case Instruction::Select: {
3774 //
3775 // Generate OpSelect.
3776 //
3777
3778 // Ops[0] = Result Type ID
3779 // Ops[1] = Condition ID
3780 // Ops[2] = True Constant ID
3781 // Ops[3] = False Constant ID
3782 SPIRVOperandList Ops;
3783
3784 // Find SPIRV instruction for parameter type.
3785 auto Ty = I.getType();
3786 if (Ty->isPointerTy()) {
3787 auto PointeeTy = Ty->getPointerElementType();
3788 if (PointeeTy->isStructTy() &&
3789 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
3790 Ty = PointeeTy;
3791 }
3792 }
3793
David Neto257c3892018-04-11 13:19:45 -04003794 Ops << MkId(lookupType(Ty)) << MkId(VMap[I.getOperand(0)])
3795 << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003796
David Neto87846742018-04-11 17:36:22 -04003797 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003798 SPIRVInstList.push_back(Inst);
3799 break;
3800 }
3801 case Instruction::ExtractElement: {
3802 // Handle <4 x i8> type manually.
3803 Type *CompositeTy = I.getOperand(0)->getType();
3804 if (is4xi8vec(CompositeTy)) {
3805 //
3806 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
3807 // <4 x i8>.
3808 //
3809
3810 //
3811 // Generate OpShiftRightLogical
3812 //
3813 // Ops[0] = Result Type ID
3814 // Ops[1] = Operand 0
3815 // Ops[2] = Operand 1
3816 //
3817 SPIRVOperandList Ops;
3818
David Neto257c3892018-04-11 13:19:45 -04003819 Ops << MkId(lookupType(CompositeTy));
David Neto22f144c2017-06-12 14:26:21 -04003820
3821 uint32_t Op0ID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003822 Ops << MkId(Op0ID);
David Neto22f144c2017-06-12 14:26:21 -04003823
3824 uint32_t Op1ID = 0;
3825 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
3826 // Handle constant index.
3827 uint64_t Idx = CI->getZExtValue();
3828 Value *ShiftAmount =
3829 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3830 Op1ID = VMap[ShiftAmount];
3831 } else {
3832 // Handle variable index.
3833 SPIRVOperandList TmpOps;
3834
David Neto257c3892018-04-11 13:19:45 -04003835 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3836 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003837
3838 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003839 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003840
3841 Op1ID = nextID;
3842
David Neto87846742018-04-11 17:36:22 -04003843 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003844 SPIRVInstList.push_back(TmpInst);
3845 }
David Neto257c3892018-04-11 13:19:45 -04003846 Ops << MkId(Op1ID);
David Neto22f144c2017-06-12 14:26:21 -04003847
3848 uint32_t ShiftID = nextID;
3849
David Neto87846742018-04-11 17:36:22 -04003850 auto *Inst =
3851 new SPIRVInstruction(spv::OpShiftRightLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003852 SPIRVInstList.push_back(Inst);
3853
3854 //
3855 // Generate OpBitwiseAnd
3856 //
3857 // Ops[0] = Result Type ID
3858 // Ops[1] = Operand 0
3859 // Ops[2] = Operand 1
3860 //
3861 Ops.clear();
3862
David Neto257c3892018-04-11 13:19:45 -04003863 Ops << MkId(lookupType(CompositeTy)) << MkId(ShiftID);
David Neto22f144c2017-06-12 14:26:21 -04003864
3865 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
David Neto257c3892018-04-11 13:19:45 -04003866 Ops << MkId(VMap[CstFF]);
David Neto22f144c2017-06-12 14:26:21 -04003867
David Neto9b2d6252017-09-06 15:47:37 -04003868 // Reset mapping for this value to the result of the bitwise and.
3869 VMap[&I] = nextID;
3870
David Neto87846742018-04-11 17:36:22 -04003871 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003872 SPIRVInstList.push_back(Inst);
3873 break;
3874 }
3875
3876 // Ops[0] = Result Type ID
3877 // Ops[1] = Composite ID
3878 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3879 SPIRVOperandList Ops;
3880
David Neto257c3892018-04-11 13:19:45 -04003881 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003882
3883 spv::Op Opcode = spv::OpCompositeExtract;
3884 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
David Neto257c3892018-04-11 13:19:45 -04003885 Ops << MkNum(static_cast<uint32_t>(CI->getZExtValue()));
David Neto22f144c2017-06-12 14:26:21 -04003886 } else {
David Neto257c3892018-04-11 13:19:45 -04003887 Ops << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003888 Opcode = spv::OpVectorExtractDynamic;
3889 }
3890
David Neto87846742018-04-11 17:36:22 -04003891 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003892 SPIRVInstList.push_back(Inst);
3893 break;
3894 }
3895 case Instruction::InsertElement: {
3896 // Handle <4 x i8> type manually.
3897 Type *CompositeTy = I.getOperand(0)->getType();
3898 if (is4xi8vec(CompositeTy)) {
3899 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
3900 uint32_t CstFFID = VMap[CstFF];
3901
3902 uint32_t ShiftAmountID = 0;
3903 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
3904 // Handle constant index.
3905 uint64_t Idx = CI->getZExtValue();
3906 Value *ShiftAmount =
3907 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3908 ShiftAmountID = VMap[ShiftAmount];
3909 } else {
3910 // Handle variable index.
3911 SPIRVOperandList TmpOps;
3912
David Neto257c3892018-04-11 13:19:45 -04003913 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3914 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003915
3916 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003917 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003918
3919 ShiftAmountID = nextID;
3920
David Neto87846742018-04-11 17:36:22 -04003921 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003922 SPIRVInstList.push_back(TmpInst);
3923 }
3924
3925 //
3926 // Generate mask operations.
3927 //
3928
3929 // ShiftLeft mask according to index of insertelement.
3930 SPIRVOperandList Ops;
3931
David Neto257c3892018-04-11 13:19:45 -04003932 const uint32_t ResTyID = lookupType(CompositeTy);
3933 Ops << MkId(ResTyID) << MkId(CstFFID) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04003934
3935 uint32_t MaskID = nextID;
3936
David Neto87846742018-04-11 17:36:22 -04003937 auto *Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003938 SPIRVInstList.push_back(Inst);
3939
3940 // Inverse mask.
3941 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003942 Ops << MkId(ResTyID) << MkId(MaskID);
David Neto22f144c2017-06-12 14:26:21 -04003943
3944 uint32_t InvMaskID = nextID;
3945
David Neto87846742018-04-11 17:36:22 -04003946 Inst = new SPIRVInstruction(spv::OpNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003947 SPIRVInstList.push_back(Inst);
3948
3949 // Apply mask.
3950 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003951 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(0)]) << MkId(InvMaskID);
David Neto22f144c2017-06-12 14:26:21 -04003952
3953 uint32_t OrgValID = nextID;
3954
David Neto87846742018-04-11 17:36:22 -04003955 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003956 SPIRVInstList.push_back(Inst);
3957
3958 // Create correct value according to index of insertelement.
3959 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003960 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(1)]) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04003961
3962 uint32_t InsertValID = nextID;
3963
David Neto87846742018-04-11 17:36:22 -04003964 Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003965 SPIRVInstList.push_back(Inst);
3966
3967 // Insert value to original value.
3968 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003969 Ops << MkId(ResTyID) << MkId(OrgValID) << MkId(InsertValID);
David Neto22f144c2017-06-12 14:26:21 -04003970
David Netoa394f392017-08-26 20:45:29 -04003971 VMap[&I] = nextID;
3972
David Neto87846742018-04-11 17:36:22 -04003973 Inst = new SPIRVInstruction(spv::OpBitwiseOr, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003974 SPIRVInstList.push_back(Inst);
3975
3976 break;
3977 }
3978
David Neto22f144c2017-06-12 14:26:21 -04003979 SPIRVOperandList Ops;
3980
James Priced26efea2018-06-09 23:28:32 +01003981 // Ops[0] = Result Type ID
3982 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003983
3984 spv::Op Opcode = spv::OpCompositeInsert;
3985 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04003986 const auto value = CI->getZExtValue();
3987 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01003988 // Ops[1] = Object ID
3989 // Ops[2] = Composite ID
3990 // Ops[3] ... Ops[n] = Indexes (Literal Number)
3991 Ops << MkId(VMap[I.getOperand(1)])
3992 << MkId(VMap[I.getOperand(0)])
3993 << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04003994 } else {
James Priced26efea2018-06-09 23:28:32 +01003995 // Ops[1] = Composite ID
3996 // Ops[2] = Object ID
3997 // Ops[3] ... Ops[n] = Indexes (Literal Number)
3998 Ops << MkId(VMap[I.getOperand(0)])
3999 << MkId(VMap[I.getOperand(1)])
4000 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004001 Opcode = spv::OpVectorInsertDynamic;
4002 }
4003
David Neto87846742018-04-11 17:36:22 -04004004 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004005 SPIRVInstList.push_back(Inst);
4006 break;
4007 }
4008 case Instruction::ShuffleVector: {
4009 // Ops[0] = Result Type ID
4010 // Ops[1] = Vector 1 ID
4011 // Ops[2] = Vector 2 ID
4012 // Ops[3] ... Ops[n] = Components (Literal Number)
4013 SPIRVOperandList Ops;
4014
David Neto257c3892018-04-11 13:19:45 -04004015 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4016 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004017
4018 uint64_t NumElements = 0;
4019 if (Constant *Cst = dyn_cast<Constant>(I.getOperand(2))) {
4020 NumElements = cast<VectorType>(Cst->getType())->getNumElements();
4021
4022 if (Cst->isNullValue()) {
4023 for (unsigned i = 0; i < NumElements; i++) {
David Neto257c3892018-04-11 13:19:45 -04004024 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04004025 }
4026 } else if (const ConstantDataSequential *CDS =
4027 dyn_cast<ConstantDataSequential>(Cst)) {
4028 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
4029 std::vector<uint32_t> LiteralNum;
David Neto257c3892018-04-11 13:19:45 -04004030 const auto value = CDS->getElementAsInteger(i);
4031 assert(value <= UINT32_MAX);
4032 Ops << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004033 }
4034 } else if (const ConstantVector *CV = dyn_cast<ConstantVector>(Cst)) {
4035 for (unsigned i = 0; i < CV->getNumOperands(); i++) {
4036 auto Op = CV->getOperand(i);
4037
4038 uint32_t literal = 0;
4039
4040 if (auto CI = dyn_cast<ConstantInt>(Op)) {
4041 literal = static_cast<uint32_t>(CI->getZExtValue());
4042 } else if (auto UI = dyn_cast<UndefValue>(Op)) {
4043 literal = 0xFFFFFFFFu;
4044 } else {
4045 Op->print(errs());
4046 llvm_unreachable("Unsupported element in ConstantVector!");
4047 }
4048
David Neto257c3892018-04-11 13:19:45 -04004049 Ops << MkNum(literal);
David Neto22f144c2017-06-12 14:26:21 -04004050 }
4051 } else {
4052 Cst->print(errs());
4053 llvm_unreachable("Unsupported constant mask in ShuffleVector!");
4054 }
4055 }
4056
David Neto87846742018-04-11 17:36:22 -04004057 auto *Inst = new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004058 SPIRVInstList.push_back(Inst);
4059 break;
4060 }
4061 case Instruction::ICmp:
4062 case Instruction::FCmp: {
4063 CmpInst *CmpI = cast<CmpInst>(&I);
4064
David Netod4ca2e62017-07-06 18:47:35 -04004065 // Pointer equality is invalid.
4066 Type* ArgTy = CmpI->getOperand(0)->getType();
4067 if (isa<PointerType>(ArgTy)) {
4068 CmpI->print(errs());
4069 std::string name = I.getParent()->getParent()->getName();
4070 errs()
4071 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4072 << "in function " << name << "\n";
4073 llvm_unreachable("Pointer equality check is invalid");
4074 break;
4075 }
4076
David Neto257c3892018-04-11 13:19:45 -04004077 // Ops[0] = Result Type ID
4078 // Ops[1] = Operand 1 ID
4079 // Ops[2] = Operand 2 ID
4080 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004081
David Neto257c3892018-04-11 13:19:45 -04004082 Ops << MkId(lookupType(CmpI->getType())) << MkId(VMap[CmpI->getOperand(0)])
4083 << MkId(VMap[CmpI->getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004084
4085 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
David Neto87846742018-04-11 17:36:22 -04004086 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004087 SPIRVInstList.push_back(Inst);
4088 break;
4089 }
4090 case Instruction::Br: {
4091 // Branch instrucion is deferred because it needs label's ID. Record slot's
4092 // location on SPIRVInstructionList.
4093 DeferredInsts.push_back(
4094 std::make_tuple(&I, --SPIRVInstList.end(), 0 /* No id */));
4095 break;
4096 }
4097 case Instruction::Switch: {
4098 I.print(errs());
4099 llvm_unreachable("Unsupported instruction???");
4100 break;
4101 }
4102 case Instruction::IndirectBr: {
4103 I.print(errs());
4104 llvm_unreachable("Unsupported instruction???");
4105 break;
4106 }
4107 case Instruction::PHI: {
4108 // Branch instrucion is deferred because it needs label's ID. Record slot's
4109 // location on SPIRVInstructionList.
4110 DeferredInsts.push_back(
4111 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4112 break;
4113 }
4114 case Instruction::Alloca: {
4115 //
4116 // Generate OpVariable.
4117 //
4118 // Ops[0] : Result Type ID
4119 // Ops[1] : Storage Class
4120 SPIRVOperandList Ops;
4121
David Neto257c3892018-04-11 13:19:45 -04004122 Ops << MkId(lookupType(I.getType())) << MkNum(spv::StorageClassFunction);
David Neto22f144c2017-06-12 14:26:21 -04004123
David Neto87846742018-04-11 17:36:22 -04004124 auto *Inst = new SPIRVInstruction(spv::OpVariable, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004125 SPIRVInstList.push_back(Inst);
4126 break;
4127 }
4128 case Instruction::Load: {
4129 LoadInst *LD = cast<LoadInst>(&I);
4130 //
4131 // Generate OpLoad.
4132 //
4133
David Neto0a2f98d2017-09-15 19:38:40 -04004134 uint32_t ResTyID = lookupType(LD->getType());
David Netoa60b00b2017-09-15 16:34:09 -04004135 uint32_t PointerID = VMap[LD->getPointerOperand()];
4136
4137 // This is a hack to work around what looks like a driver bug.
4138 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004139 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4140 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004141 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004142 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004143 // Generate a bitwise-and of the original value with itself.
4144 // We should have been able to get away with just an OpCopyObject,
4145 // but we need something more complex to get past certain driver bugs.
4146 // This is ridiculous, but necessary.
4147 // TODO(dneto): Revisit this once drivers fix their bugs.
4148
4149 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004150 Ops << MkId(ResTyID) << MkId(WorkgroupSizeValueID)
4151 << MkId(WorkgroupSizeValueID);
David Neto0a2f98d2017-09-15 19:38:40 -04004152
David Neto87846742018-04-11 17:36:22 -04004153 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto0a2f98d2017-09-15 19:38:40 -04004154 SPIRVInstList.push_back(Inst);
David Netoa60b00b2017-09-15 16:34:09 -04004155 break;
4156 }
4157
4158 // This is the normal path. Generate a load.
4159
David Neto22f144c2017-06-12 14:26:21 -04004160 // Ops[0] = Result Type ID
4161 // Ops[1] = Pointer ID
4162 // Ops[2] ... Ops[n] = Optional Memory Access
4163 //
4164 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004165
David Neto22f144c2017-06-12 14:26:21 -04004166 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004167 Ops << MkId(ResTyID) << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04004168
David Neto87846742018-04-11 17:36:22 -04004169 auto *Inst = new SPIRVInstruction(spv::OpLoad, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004170 SPIRVInstList.push_back(Inst);
4171 break;
4172 }
4173 case Instruction::Store: {
4174 StoreInst *ST = cast<StoreInst>(&I);
4175 //
4176 // Generate OpStore.
4177 //
4178
4179 // Ops[0] = Pointer ID
4180 // Ops[1] = Object ID
4181 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4182 //
4183 // TODO: Do we need to implement Optional Memory Access???
David Neto257c3892018-04-11 13:19:45 -04004184 SPIRVOperandList Ops;
4185 Ops << MkId(VMap[ST->getPointerOperand()])
4186 << MkId(VMap[ST->getValueOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004187
David Neto87846742018-04-11 17:36:22 -04004188 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004189 SPIRVInstList.push_back(Inst);
4190 break;
4191 }
4192 case Instruction::AtomicCmpXchg: {
4193 I.print(errs());
4194 llvm_unreachable("Unsupported instruction???");
4195 break;
4196 }
4197 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004198 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4199
4200 spv::Op opcode;
4201
4202 switch (AtomicRMW->getOperation()) {
4203 default:
4204 I.print(errs());
4205 llvm_unreachable("Unsupported instruction???");
4206 case llvm::AtomicRMWInst::Add:
4207 opcode = spv::OpAtomicIAdd;
4208 break;
4209 case llvm::AtomicRMWInst::Sub:
4210 opcode = spv::OpAtomicISub;
4211 break;
4212 case llvm::AtomicRMWInst::Xchg:
4213 opcode = spv::OpAtomicExchange;
4214 break;
4215 case llvm::AtomicRMWInst::Min:
4216 opcode = spv::OpAtomicSMin;
4217 break;
4218 case llvm::AtomicRMWInst::Max:
4219 opcode = spv::OpAtomicSMax;
4220 break;
4221 case llvm::AtomicRMWInst::UMin:
4222 opcode = spv::OpAtomicUMin;
4223 break;
4224 case llvm::AtomicRMWInst::UMax:
4225 opcode = spv::OpAtomicUMax;
4226 break;
4227 case llvm::AtomicRMWInst::And:
4228 opcode = spv::OpAtomicAnd;
4229 break;
4230 case llvm::AtomicRMWInst::Or:
4231 opcode = spv::OpAtomicOr;
4232 break;
4233 case llvm::AtomicRMWInst::Xor:
4234 opcode = spv::OpAtomicXor;
4235 break;
4236 }
4237
4238 //
4239 // Generate OpAtomic*.
4240 //
4241 SPIRVOperandList Ops;
4242
David Neto257c3892018-04-11 13:19:45 -04004243 Ops << MkId(lookupType(I.getType()))
4244 << MkId(VMap[AtomicRMW->getPointerOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004245
4246 auto IntTy = Type::getInt32Ty(I.getContext());
Neil Henning39672102017-09-29 14:33:13 +01004247 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
David Neto257c3892018-04-11 13:19:45 -04004248 Ops << MkId(VMap[ConstantScopeDevice]);
Neil Henning39672102017-09-29 14:33:13 +01004249
4250 const auto ConstantMemorySemantics = ConstantInt::get(
4251 IntTy, spv::MemorySemanticsUniformMemoryMask |
4252 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto257c3892018-04-11 13:19:45 -04004253 Ops << MkId(VMap[ConstantMemorySemantics]);
Neil Henning39672102017-09-29 14:33:13 +01004254
David Neto257c3892018-04-11 13:19:45 -04004255 Ops << MkId(VMap[AtomicRMW->getValOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004256
4257 VMap[&I] = nextID;
4258
David Neto87846742018-04-11 17:36:22 -04004259 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
Neil Henning39672102017-09-29 14:33:13 +01004260 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004261 break;
4262 }
4263 case Instruction::Fence: {
4264 I.print(errs());
4265 llvm_unreachable("Unsupported instruction???");
4266 break;
4267 }
4268 case Instruction::Call: {
4269 CallInst *Call = dyn_cast<CallInst>(&I);
4270 Function *Callee = Call->getCalledFunction();
4271
Alan Baker202c8c72018-08-13 13:47:44 -04004272 if (Callee->getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004273 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
4274 // Generate an OpLoad
4275 SPIRVOperandList Ops;
4276 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004277
David Neto862b7d82018-06-14 18:48:37 -04004278 Ops << MkId(lookupType(Call->getType()->getPointerElementType()))
4279 << MkId(ResourceVarDeferredLoadCalls[Call]);
4280
4281 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
4282 SPIRVInstList.push_back(Inst);
4283 VMap[Call] = load_id;
4284 break;
4285
4286 } else {
4287 // This maps to an OpVariable we've already generated.
4288 // No code is generated for the call.
4289 }
4290 break;
Alan Baker202c8c72018-08-13 13:47:44 -04004291 } else if (Callee->getName().startswith(clspv::WorkgroupAccessorFunction())) {
4292 // Don't codegen an instruction here, but instead map this call directly
4293 // to the workgroup variable id.
4294 int spec_id = cast<ConstantInt>(Call->getOperand(0))->getSExtValue();
4295 const auto &info = LocalSpecIdInfoMap[spec_id];
4296 VMap[Call] = info.variable_id;
4297 break;
David Neto862b7d82018-06-14 18:48:37 -04004298 }
4299
4300 // Sampler initializers become a load of the corresponding sampler.
4301
4302 if (Callee->getName().equals("clspv.sampler.var.literal")) {
4303 // Map this to a load from the variable.
4304 const auto index_into_sampler_map =
4305 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4306
4307 // Generate an OpLoad
David Neto22f144c2017-06-12 14:26:21 -04004308 SPIRVOperandList Ops;
David Neto862b7d82018-06-14 18:48:37 -04004309 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004310
David Neto257c3892018-04-11 13:19:45 -04004311 Ops << MkId(lookupType(SamplerTy->getPointerElementType()))
David Neto862b7d82018-06-14 18:48:37 -04004312 << MkId(SamplerMapIndexToIDMap[index_into_sampler_map]);
David Neto22f144c2017-06-12 14:26:21 -04004313
David Neto862b7d82018-06-14 18:48:37 -04004314 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004315 SPIRVInstList.push_back(Inst);
David Neto862b7d82018-06-14 18:48:37 -04004316 VMap[Call] = load_id;
David Neto22f144c2017-06-12 14:26:21 -04004317 break;
4318 }
4319
4320 if (Callee->getName().startswith("spirv.atomic")) {
4321 spv::Op opcode = StringSwitch<spv::Op>(Callee->getName())
4322 .Case("spirv.atomic_add", spv::OpAtomicIAdd)
4323 .Case("spirv.atomic_sub", spv::OpAtomicISub)
4324 .Case("spirv.atomic_exchange", spv::OpAtomicExchange)
4325 .Case("spirv.atomic_inc", spv::OpAtomicIIncrement)
4326 .Case("spirv.atomic_dec", spv::OpAtomicIDecrement)
4327 .Case("spirv.atomic_compare_exchange",
4328 spv::OpAtomicCompareExchange)
4329 .Case("spirv.atomic_umin", spv::OpAtomicUMin)
4330 .Case("spirv.atomic_smin", spv::OpAtomicSMin)
4331 .Case("spirv.atomic_umax", spv::OpAtomicUMax)
4332 .Case("spirv.atomic_smax", spv::OpAtomicSMax)
4333 .Case("spirv.atomic_and", spv::OpAtomicAnd)
4334 .Case("spirv.atomic_or", spv::OpAtomicOr)
4335 .Case("spirv.atomic_xor", spv::OpAtomicXor)
4336 .Default(spv::OpNop);
4337
4338 //
4339 // Generate OpAtomic*.
4340 //
4341 SPIRVOperandList Ops;
4342
David Neto257c3892018-04-11 13:19:45 -04004343 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004344
4345 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004346 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004347 }
4348
4349 VMap[&I] = nextID;
4350
David Neto87846742018-04-11 17:36:22 -04004351 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004352 SPIRVInstList.push_back(Inst);
4353 break;
4354 }
4355
4356 if (Callee->getName().startswith("_Z3dot")) {
4357 // If the argument is a vector type, generate OpDot
4358 if (Call->getArgOperand(0)->getType()->isVectorTy()) {
4359 //
4360 // Generate OpDot.
4361 //
4362 SPIRVOperandList Ops;
4363
David Neto257c3892018-04-11 13:19:45 -04004364 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004365
4366 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004367 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004368 }
4369
4370 VMap[&I] = nextID;
4371
David Neto87846742018-04-11 17:36:22 -04004372 auto *Inst = new SPIRVInstruction(spv::OpDot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004373 SPIRVInstList.push_back(Inst);
4374 } else {
4375 //
4376 // Generate OpFMul.
4377 //
4378 SPIRVOperandList Ops;
4379
David Neto257c3892018-04-11 13:19:45 -04004380 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004381
4382 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004383 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004384 }
4385
4386 VMap[&I] = nextID;
4387
David Neto87846742018-04-11 17:36:22 -04004388 auto *Inst = new SPIRVInstruction(spv::OpFMul, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004389 SPIRVInstList.push_back(Inst);
4390 }
4391 break;
4392 }
4393
David Neto8505ebf2017-10-13 18:50:50 -04004394 if (Callee->getName().startswith("_Z4fmod")) {
4395 // OpenCL fmod(x,y) is x - y * trunc(x/y)
4396 // The sign for a non-zero result is taken from x.
4397 // (Try an example.)
4398 // So translate to OpFRem
4399
4400 SPIRVOperandList Ops;
4401
David Neto257c3892018-04-11 13:19:45 -04004402 Ops << MkId(lookupType(I.getType()));
David Neto8505ebf2017-10-13 18:50:50 -04004403
4404 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004405 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto8505ebf2017-10-13 18:50:50 -04004406 }
4407
4408 VMap[&I] = nextID;
4409
David Neto87846742018-04-11 17:36:22 -04004410 auto *Inst = new SPIRVInstruction(spv::OpFRem, nextID++, Ops);
David Neto8505ebf2017-10-13 18:50:50 -04004411 SPIRVInstList.push_back(Inst);
4412 break;
4413 }
4414
David Neto22f144c2017-06-12 14:26:21 -04004415 // spirv.store_null.* intrinsics become OpStore's.
4416 if (Callee->getName().startswith("spirv.store_null")) {
4417 //
4418 // Generate OpStore.
4419 //
4420
4421 // Ops[0] = Pointer ID
4422 // Ops[1] = Object ID
4423 // Ops[2] ... Ops[n]
4424 SPIRVOperandList Ops;
4425
4426 uint32_t PointerID = VMap[Call->getArgOperand(0)];
David Neto22f144c2017-06-12 14:26:21 -04004427 uint32_t ObjectID = VMap[Call->getArgOperand(1)];
David Neto257c3892018-04-11 13:19:45 -04004428 Ops << MkId(PointerID) << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04004429
David Neto87846742018-04-11 17:36:22 -04004430 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpStore, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004431
4432 break;
4433 }
4434
4435 // spirv.copy_memory.* intrinsics become OpMemoryMemory's.
4436 if (Callee->getName().startswith("spirv.copy_memory")) {
4437 //
4438 // Generate OpCopyMemory.
4439 //
4440
4441 // Ops[0] = Dst ID
4442 // Ops[1] = Src ID
4443 // Ops[2] = Memory Access
4444 // Ops[3] = Alignment
4445
4446 auto IsVolatile =
4447 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
4448
4449 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
4450 : spv::MemoryAccessMaskNone;
4451
4452 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
4453
4454 auto Alignment =
4455 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4456
David Neto257c3892018-04-11 13:19:45 -04004457 SPIRVOperandList Ops;
4458 Ops << MkId(VMap[Call->getArgOperand(0)])
4459 << MkId(VMap[Call->getArgOperand(1)]) << MkNum(MemoryAccess)
4460 << MkNum(static_cast<uint32_t>(Alignment));
David Neto22f144c2017-06-12 14:26:21 -04004461
David Neto87846742018-04-11 17:36:22 -04004462 auto *Inst = new SPIRVInstruction(spv::OpCopyMemory, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004463
4464 SPIRVInstList.push_back(Inst);
4465
4466 break;
4467 }
4468
4469 // Nothing to do for abs with uint. Map abs's operand ID to VMap for abs
4470 // with unit.
4471 if (Callee->getName().equals("_Z3absj") ||
4472 Callee->getName().equals("_Z3absDv2_j") ||
4473 Callee->getName().equals("_Z3absDv3_j") ||
4474 Callee->getName().equals("_Z3absDv4_j")) {
4475 VMap[&I] = VMap[Call->getOperand(0)];
4476 break;
4477 }
4478
4479 // barrier is converted to OpControlBarrier
4480 if (Callee->getName().equals("__spirv_control_barrier")) {
4481 //
4482 // Generate OpControlBarrier.
4483 //
4484 // Ops[0] = Execution Scope ID
4485 // Ops[1] = Memory Scope ID
4486 // Ops[2] = Memory Semantics ID
4487 //
4488 Value *ExecutionScope = Call->getArgOperand(0);
4489 Value *MemoryScope = Call->getArgOperand(1);
4490 Value *MemorySemantics = Call->getArgOperand(2);
4491
David Neto257c3892018-04-11 13:19:45 -04004492 SPIRVOperandList Ops;
4493 Ops << MkId(VMap[ExecutionScope]) << MkId(VMap[MemoryScope])
4494 << MkId(VMap[MemorySemantics]);
David Neto22f144c2017-06-12 14:26:21 -04004495
David Neto87846742018-04-11 17:36:22 -04004496 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpControlBarrier, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004497 break;
4498 }
4499
4500 // memory barrier is converted to OpMemoryBarrier
4501 if (Callee->getName().equals("__spirv_memory_barrier")) {
4502 //
4503 // Generate OpMemoryBarrier.
4504 //
4505 // Ops[0] = Memory Scope ID
4506 // Ops[1] = Memory Semantics ID
4507 //
4508 SPIRVOperandList Ops;
4509
David Neto257c3892018-04-11 13:19:45 -04004510 uint32_t MemoryScopeID = VMap[Call->getArgOperand(0)];
4511 uint32_t MemorySemanticsID = VMap[Call->getArgOperand(1)];
David Neto22f144c2017-06-12 14:26:21 -04004512
David Neto257c3892018-04-11 13:19:45 -04004513 Ops << MkId(MemoryScopeID) << MkId(MemorySemanticsID);
David Neto22f144c2017-06-12 14:26:21 -04004514
David Neto87846742018-04-11 17:36:22 -04004515 auto *Inst = new SPIRVInstruction(spv::OpMemoryBarrier, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004516 SPIRVInstList.push_back(Inst);
4517 break;
4518 }
4519
4520 // isinf is converted to OpIsInf
4521 if (Callee->getName().equals("__spirv_isinff") ||
4522 Callee->getName().equals("__spirv_isinfDv2_f") ||
4523 Callee->getName().equals("__spirv_isinfDv3_f") ||
4524 Callee->getName().equals("__spirv_isinfDv4_f")) {
4525 //
4526 // Generate OpIsInf.
4527 //
4528 // Ops[0] = Result Type ID
4529 // Ops[1] = X ID
4530 //
4531 SPIRVOperandList Ops;
4532
David Neto257c3892018-04-11 13:19:45 -04004533 Ops << MkId(lookupType(I.getType()))
4534 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004535
4536 VMap[&I] = nextID;
4537
David Neto87846742018-04-11 17:36:22 -04004538 auto *Inst = new SPIRVInstruction(spv::OpIsInf, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004539 SPIRVInstList.push_back(Inst);
4540 break;
4541 }
4542
4543 // isnan is converted to OpIsNan
4544 if (Callee->getName().equals("__spirv_isnanf") ||
4545 Callee->getName().equals("__spirv_isnanDv2_f") ||
4546 Callee->getName().equals("__spirv_isnanDv3_f") ||
4547 Callee->getName().equals("__spirv_isnanDv4_f")) {
4548 //
4549 // Generate OpIsInf.
4550 //
4551 // Ops[0] = Result Type ID
4552 // Ops[1] = X ID
4553 //
4554 SPIRVOperandList Ops;
4555
David Neto257c3892018-04-11 13:19:45 -04004556 Ops << MkId(lookupType(I.getType()))
4557 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004558
4559 VMap[&I] = nextID;
4560
David Neto87846742018-04-11 17:36:22 -04004561 auto *Inst = new SPIRVInstruction(spv::OpIsNan, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004562 SPIRVInstList.push_back(Inst);
4563 break;
4564 }
4565
4566 // all is converted to OpAll
4567 if (Callee->getName().equals("__spirv_allDv2_i") ||
4568 Callee->getName().equals("__spirv_allDv3_i") ||
4569 Callee->getName().equals("__spirv_allDv4_i")) {
4570 //
4571 // Generate OpAll.
4572 //
4573 // Ops[0] = Result Type ID
4574 // Ops[1] = Vector ID
4575 //
4576 SPIRVOperandList Ops;
4577
David Neto257c3892018-04-11 13:19:45 -04004578 Ops << MkId(lookupType(I.getType()))
4579 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004580
4581 VMap[&I] = nextID;
4582
David Neto87846742018-04-11 17:36:22 -04004583 auto *Inst = new SPIRVInstruction(spv::OpAll, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004584 SPIRVInstList.push_back(Inst);
4585 break;
4586 }
4587
4588 // any is converted to OpAny
4589 if (Callee->getName().equals("__spirv_anyDv2_i") ||
4590 Callee->getName().equals("__spirv_anyDv3_i") ||
4591 Callee->getName().equals("__spirv_anyDv4_i")) {
4592 //
4593 // Generate OpAny.
4594 //
4595 // Ops[0] = Result Type ID
4596 // Ops[1] = Vector ID
4597 //
4598 SPIRVOperandList Ops;
4599
David Neto257c3892018-04-11 13:19:45 -04004600 Ops << MkId(lookupType(I.getType()))
4601 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004602
4603 VMap[&I] = nextID;
4604
David Neto87846742018-04-11 17:36:22 -04004605 auto *Inst = new SPIRVInstruction(spv::OpAny, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004606 SPIRVInstList.push_back(Inst);
4607 break;
4608 }
4609
4610 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
4611 // Additionally, OpTypeSampledImage is generated.
4612 if (Callee->getName().equals(
4613 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
4614 Callee->getName().equals(
4615 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
4616 //
4617 // Generate OpSampledImage.
4618 //
4619 // Ops[0] = Result Type ID
4620 // Ops[1] = Image ID
4621 // Ops[2] = Sampler ID
4622 //
4623 SPIRVOperandList Ops;
4624
4625 Value *Image = Call->getArgOperand(0);
4626 Value *Sampler = Call->getArgOperand(1);
4627 Value *Coordinate = Call->getArgOperand(2);
4628
4629 TypeMapType &OpImageTypeMap = getImageTypeMap();
4630 Type *ImageTy = Image->getType()->getPointerElementType();
4631 uint32_t ImageTyID = OpImageTypeMap[ImageTy];
David Neto22f144c2017-06-12 14:26:21 -04004632 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004633 uint32_t SamplerID = VMap[Sampler];
David Neto257c3892018-04-11 13:19:45 -04004634
4635 Ops << MkId(ImageTyID) << MkId(ImageID) << MkId(SamplerID);
David Neto22f144c2017-06-12 14:26:21 -04004636
4637 uint32_t SampledImageID = nextID;
4638
David Neto87846742018-04-11 17:36:22 -04004639 auto *Inst = new SPIRVInstruction(spv::OpSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004640 SPIRVInstList.push_back(Inst);
4641
4642 //
4643 // Generate OpImageSampleExplicitLod.
4644 //
4645 // Ops[0] = Result Type ID
4646 // Ops[1] = Sampled Image ID
4647 // Ops[2] = Coordinate ID
4648 // Ops[3] = Image Operands Type ID
4649 // Ops[4] ... Ops[n] = Operands ID
4650 //
4651 Ops.clear();
4652
David Neto257c3892018-04-11 13:19:45 -04004653 Ops << MkId(lookupType(Call->getType())) << MkId(SampledImageID)
4654 << MkId(VMap[Coordinate]) << MkNum(spv::ImageOperandsLodMask);
David Neto22f144c2017-06-12 14:26:21 -04004655
4656 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
David Neto257c3892018-04-11 13:19:45 -04004657 Ops << MkId(VMap[CstFP0]);
David Neto22f144c2017-06-12 14:26:21 -04004658
4659 VMap[&I] = nextID;
4660
David Neto87846742018-04-11 17:36:22 -04004661 Inst = new SPIRVInstruction(spv::OpImageSampleExplicitLod, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004662 SPIRVInstList.push_back(Inst);
4663 break;
4664 }
4665
4666 // write_imagef is mapped to OpImageWrite.
4667 if (Callee->getName().equals(
4668 "_Z12write_imagef14ocl_image2d_woDv2_iDv4_f") ||
4669 Callee->getName().equals(
4670 "_Z12write_imagef14ocl_image3d_woDv4_iDv4_f")) {
4671 //
4672 // Generate OpImageWrite.
4673 //
4674 // Ops[0] = Image ID
4675 // Ops[1] = Coordinate ID
4676 // Ops[2] = Texel ID
4677 // Ops[3] = (Optional) Image Operands Type (Literal Number)
4678 // Ops[4] ... Ops[n] = (Optional) Operands ID
4679 //
4680 SPIRVOperandList Ops;
4681
4682 Value *Image = Call->getArgOperand(0);
4683 Value *Coordinate = Call->getArgOperand(1);
4684 Value *Texel = Call->getArgOperand(2);
4685
4686 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004687 uint32_t CoordinateID = VMap[Coordinate];
David Neto22f144c2017-06-12 14:26:21 -04004688 uint32_t TexelID = VMap[Texel];
David Neto257c3892018-04-11 13:19:45 -04004689 Ops << MkId(ImageID) << MkId(CoordinateID) << MkId(TexelID);
David Neto22f144c2017-06-12 14:26:21 -04004690
David Neto87846742018-04-11 17:36:22 -04004691 auto *Inst = new SPIRVInstruction(spv::OpImageWrite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004692 SPIRVInstList.push_back(Inst);
4693 break;
4694 }
4695
David Neto5c22a252018-03-15 16:07:41 -04004696 // get_image_width is mapped to OpImageQuerySize
4697 if (Callee->getName().equals("_Z15get_image_width14ocl_image2d_ro") ||
4698 Callee->getName().equals("_Z15get_image_width14ocl_image2d_wo") ||
4699 Callee->getName().equals("_Z16get_image_height14ocl_image2d_ro") ||
4700 Callee->getName().equals("_Z16get_image_height14ocl_image2d_wo")) {
4701 //
4702 // Generate OpImageQuerySize, then pull out the right component.
4703 // Assume 2D image for now.
4704 //
4705 // Ops[0] = Image ID
4706 //
4707 // %sizes = OpImageQuerySizes %uint2 %im
4708 // %result = OpCompositeExtract %uint %sizes 0-or-1
4709 SPIRVOperandList Ops;
4710
4711 // Implement:
4712 // %sizes = OpImageQuerySizes %uint2 %im
4713 uint32_t SizesTypeID =
4714 TypeMap[VectorType::get(Type::getInt32Ty(Context), 2)];
David Neto5c22a252018-03-15 16:07:41 -04004715 Value *Image = Call->getArgOperand(0);
4716 uint32_t ImageID = VMap[Image];
David Neto257c3892018-04-11 13:19:45 -04004717 Ops << MkId(SizesTypeID) << MkId(ImageID);
David Neto5c22a252018-03-15 16:07:41 -04004718
4719 uint32_t SizesID = nextID++;
David Neto87846742018-04-11 17:36:22 -04004720 auto *QueryInst =
4721 new SPIRVInstruction(spv::OpImageQuerySize, SizesID, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004722 SPIRVInstList.push_back(QueryInst);
4723
4724 // Reset value map entry since we generated an intermediate instruction.
4725 VMap[&I] = nextID;
4726
4727 // Implement:
4728 // %result = OpCompositeExtract %uint %sizes 0-or-1
4729 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004730 Ops << MkId(TypeMap[I.getType()]) << MkId(SizesID);
David Neto5c22a252018-03-15 16:07:41 -04004731
4732 uint32_t component = Callee->getName().contains("height") ? 1 : 0;
David Neto257c3892018-04-11 13:19:45 -04004733 Ops << MkNum(component);
David Neto5c22a252018-03-15 16:07:41 -04004734
David Neto87846742018-04-11 17:36:22 -04004735 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004736 SPIRVInstList.push_back(Inst);
4737 break;
4738 }
4739
David Neto22f144c2017-06-12 14:26:21 -04004740 // Call instrucion is deferred because it needs function's ID. Record
4741 // slot's location on SPIRVInstructionList.
4742 DeferredInsts.push_back(
4743 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4744
David Neto3fbb4072017-10-16 11:28:14 -04004745 // Check whether the implementation of this call uses an extended
4746 // instruction plus one more value-producing instruction. If so, then
4747 // reserve the id for the extra value-producing slot.
4748 glsl::ExtInst EInst = getIndirectExtInstEnum(Callee->getName());
4749 if (EInst != kGlslExtInstBad) {
4750 // Reserve a spot for the extra value.
David Neto4d02a532017-09-17 12:57:44 -04004751 // Increase nextID.
David Neto22f144c2017-06-12 14:26:21 -04004752 VMap[&I] = nextID;
4753 nextID++;
4754 }
4755 break;
4756 }
4757 case Instruction::Ret: {
4758 unsigned NumOps = I.getNumOperands();
4759 if (NumOps == 0) {
4760 //
4761 // Generate OpReturn.
4762 //
David Neto87846742018-04-11 17:36:22 -04004763 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpReturn, {}));
David Neto22f144c2017-06-12 14:26:21 -04004764 } else {
4765 //
4766 // Generate OpReturnValue.
4767 //
4768
4769 // Ops[0] = Return Value ID
4770 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004771
4772 Ops << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004773
David Neto87846742018-04-11 17:36:22 -04004774 auto *Inst = new SPIRVInstruction(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004775 SPIRVInstList.push_back(Inst);
4776 break;
4777 }
4778 break;
4779 }
4780 }
4781}
4782
4783void SPIRVProducerPass::GenerateFuncEpilogue() {
4784 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4785
4786 //
4787 // Generate OpFunctionEnd
4788 //
4789
David Neto87846742018-04-11 17:36:22 -04004790 auto *Inst = new SPIRVInstruction(spv::OpFunctionEnd, {});
David Neto22f144c2017-06-12 14:26:21 -04004791 SPIRVInstList.push_back(Inst);
4792}
4793
4794bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
4795 LLVMContext &Context = Ty->getContext();
4796 if (Ty->isVectorTy()) {
4797 if (Ty->getVectorElementType() == Type::getInt8Ty(Context) &&
4798 Ty->getVectorNumElements() == 4) {
4799 return true;
4800 }
4801 }
4802
4803 return false;
4804}
4805
David Neto257c3892018-04-11 13:19:45 -04004806uint32_t SPIRVProducerPass::GetI32Zero() {
4807 if (0 == constant_i32_zero_id_) {
4808 llvm_unreachable("Requesting a 32-bit integer constant but it is not "
4809 "defined in the SPIR-V module");
4810 }
4811 return constant_i32_zero_id_;
4812}
4813
David Neto22f144c2017-06-12 14:26:21 -04004814void SPIRVProducerPass::HandleDeferredInstruction() {
4815 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4816 ValueMapType &VMap = getValueMap();
4817 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4818
4819 for (auto DeferredInst = DeferredInsts.rbegin();
4820 DeferredInst != DeferredInsts.rend(); ++DeferredInst) {
4821 Value *Inst = std::get<0>(*DeferredInst);
4822 SPIRVInstructionList::iterator InsertPoint = ++std::get<1>(*DeferredInst);
4823 if (InsertPoint != SPIRVInstList.end()) {
4824 while ((*InsertPoint)->getOpcode() == spv::OpPhi) {
4825 ++InsertPoint;
4826 }
4827 }
4828
4829 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
4830 // Check whether basic block, which has this branch instruction, is loop
4831 // header or not. If it is loop header, generate OpLoopMerge and
4832 // OpBranchConditional.
4833 Function *Func = Br->getParent()->getParent();
4834 DominatorTree &DT =
4835 getAnalysis<DominatorTreeWrapperPass>(*Func).getDomTree();
4836 const LoopInfo &LI =
4837 getAnalysis<LoopInfoWrapperPass>(*Func).getLoopInfo();
4838
4839 BasicBlock *BrBB = Br->getParent();
4840 if (LI.isLoopHeader(BrBB)) {
4841 Value *ContinueBB = nullptr;
4842 Value *MergeBB = nullptr;
4843
4844 Loop *L = LI.getLoopFor(BrBB);
4845 MergeBB = L->getExitBlock();
4846 if (!MergeBB) {
4847 // StructurizeCFG pass converts CFG into triangle shape and the cfg
4848 // has regions with single entry/exit. As a result, loop should not
4849 // have multiple exits.
4850 llvm_unreachable("Loop has multiple exits???");
4851 }
4852
4853 if (L->isLoopLatch(BrBB)) {
4854 ContinueBB = BrBB;
4855 } else {
4856 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
4857 // block.
4858 BasicBlock *Header = L->getHeader();
4859 BasicBlock *Latch = L->getLoopLatch();
4860 for (BasicBlock *BB : L->blocks()) {
4861 if (BB == Header) {
4862 continue;
4863 }
4864
4865 // Check whether block dominates block with back-edge.
4866 if (DT.dominates(BB, Latch)) {
4867 ContinueBB = BB;
4868 }
4869 }
4870
4871 if (!ContinueBB) {
4872 llvm_unreachable("Wrong continue block from loop");
4873 }
4874 }
4875
4876 //
4877 // Generate OpLoopMerge.
4878 //
4879 // Ops[0] = Merge Block ID
4880 // Ops[1] = Continue Target ID
4881 // Ops[2] = Selection Control
4882 SPIRVOperandList Ops;
4883
4884 // StructurizeCFG pass already manipulated CFG. Just use false block of
4885 // branch instruction as merge block.
4886 uint32_t MergeBBID = VMap[MergeBB];
David Neto22f144c2017-06-12 14:26:21 -04004887 uint32_t ContinueBBID = VMap[ContinueBB];
David Neto257c3892018-04-11 13:19:45 -04004888 Ops << MkId(MergeBBID) << MkId(ContinueBBID)
4889 << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004890
David Neto87846742018-04-11 17:36:22 -04004891 auto *MergeInst = new SPIRVInstruction(spv::OpLoopMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004892 SPIRVInstList.insert(InsertPoint, MergeInst);
4893
4894 } else if (Br->isConditional()) {
4895 bool HasBackEdge = false;
4896
4897 for (unsigned i = 0; i < Br->getNumSuccessors(); i++) {
4898 if (LI.isLoopHeader(Br->getSuccessor(i))) {
4899 HasBackEdge = true;
4900 }
4901 }
4902 if (!HasBackEdge) {
4903 //
4904 // Generate OpSelectionMerge.
4905 //
4906 // Ops[0] = Merge Block ID
4907 // Ops[1] = Selection Control
4908 SPIRVOperandList Ops;
4909
4910 // StructurizeCFG pass already manipulated CFG. Just use false block
4911 // of branch instruction as merge block.
4912 uint32_t MergeBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004913 Ops << MkId(MergeBBID) << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004914
David Neto87846742018-04-11 17:36:22 -04004915 auto *MergeInst = new SPIRVInstruction(spv::OpSelectionMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004916 SPIRVInstList.insert(InsertPoint, MergeInst);
4917 }
4918 }
4919
4920 if (Br->isConditional()) {
4921 //
4922 // Generate OpBranchConditional.
4923 //
4924 // Ops[0] = Condition ID
4925 // Ops[1] = True Label ID
4926 // Ops[2] = False Label ID
4927 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
4928 SPIRVOperandList Ops;
4929
4930 uint32_t CondID = VMap[Br->getCondition()];
David Neto22f144c2017-06-12 14:26:21 -04004931 uint32_t TrueBBID = VMap[Br->getSuccessor(0)];
David Neto22f144c2017-06-12 14:26:21 -04004932 uint32_t FalseBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004933
4934 Ops << MkId(CondID) << MkId(TrueBBID) << MkId(FalseBBID);
David Neto22f144c2017-06-12 14:26:21 -04004935
David Neto87846742018-04-11 17:36:22 -04004936 auto *BrInst = new SPIRVInstruction(spv::OpBranchConditional, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004937 SPIRVInstList.insert(InsertPoint, BrInst);
4938 } else {
4939 //
4940 // Generate OpBranch.
4941 //
4942 // Ops[0] = Target Label ID
4943 SPIRVOperandList Ops;
4944
4945 uint32_t TargetID = VMap[Br->getSuccessor(0)];
David Neto257c3892018-04-11 13:19:45 -04004946 Ops << MkId(TargetID);
David Neto22f144c2017-06-12 14:26:21 -04004947
David Neto87846742018-04-11 17:36:22 -04004948 SPIRVInstList.insert(InsertPoint,
4949 new SPIRVInstruction(spv::OpBranch, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004950 }
4951 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
4952 //
4953 // Generate OpPhi.
4954 //
4955 // Ops[0] = Result Type ID
4956 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
4957 SPIRVOperandList Ops;
4958
David Neto257c3892018-04-11 13:19:45 -04004959 Ops << MkId(lookupType(PHI->getType()));
David Neto22f144c2017-06-12 14:26:21 -04004960
David Neto22f144c2017-06-12 14:26:21 -04004961 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
4962 uint32_t VarID = VMap[PHI->getIncomingValue(i)];
David Neto22f144c2017-06-12 14:26:21 -04004963 uint32_t ParentID = VMap[PHI->getIncomingBlock(i)];
David Neto257c3892018-04-11 13:19:45 -04004964 Ops << MkId(VarID) << MkId(ParentID);
David Neto22f144c2017-06-12 14:26:21 -04004965 }
4966
4967 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04004968 InsertPoint,
4969 new SPIRVInstruction(spv::OpPhi, std::get<2>(*DeferredInst), Ops));
David Neto22f144c2017-06-12 14:26:21 -04004970 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
4971 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04004972 auto callee_name = Callee->getName();
4973 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04004974
4975 if (EInst) {
4976 uint32_t &ExtInstImportID = getOpExtInstImportID();
4977
4978 //
4979 // Generate OpExtInst.
4980 //
4981
4982 // Ops[0] = Result Type ID
4983 // Ops[1] = Set ID (OpExtInstImport ID)
4984 // Ops[2] = Instruction Number (Literal Number)
4985 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
4986 SPIRVOperandList Ops;
4987
David Neto862b7d82018-06-14 18:48:37 -04004988 Ops << MkId(lookupType(Call->getType())) << MkId(ExtInstImportID)
4989 << MkNum(EInst);
David Neto22f144c2017-06-12 14:26:21 -04004990
David Neto22f144c2017-06-12 14:26:21 -04004991 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
4992 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004993 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004994 }
4995
David Neto87846742018-04-11 17:36:22 -04004996 auto *ExtInst = new SPIRVInstruction(spv::OpExtInst,
4997 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04004998 SPIRVInstList.insert(InsertPoint, ExtInst);
4999
David Neto3fbb4072017-10-16 11:28:14 -04005000 const auto IndirectExtInst = getIndirectExtInstEnum(callee_name);
5001 if (IndirectExtInst != kGlslExtInstBad) {
5002 // Generate one more instruction that uses the result of the extended
5003 // instruction. Its result id is one more than the id of the
5004 // extended instruction.
David Neto22f144c2017-06-12 14:26:21 -04005005 LLVMContext &Context =
5006 Call->getParent()->getParent()->getParent()->getContext();
David Neto22f144c2017-06-12 14:26:21 -04005007
David Neto3fbb4072017-10-16 11:28:14 -04005008 auto generate_extra_inst = [this, &Context, &Call, &DeferredInst,
5009 &VMap, &SPIRVInstList, &InsertPoint](
5010 spv::Op opcode, Constant *constant) {
5011 //
5012 // Generate instruction like:
5013 // result = opcode constant <extinst-result>
5014 //
5015 // Ops[0] = Result Type ID
5016 // Ops[1] = Operand 0 ;; the constant, suitably splatted
5017 // Ops[2] = Operand 1 ;; the result of the extended instruction
5018 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04005019
David Neto3fbb4072017-10-16 11:28:14 -04005020 Type *resultTy = Call->getType();
David Neto257c3892018-04-11 13:19:45 -04005021 Ops << MkId(lookupType(resultTy));
David Neto3fbb4072017-10-16 11:28:14 -04005022
5023 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
5024 constant = ConstantVector::getSplat(
5025 static_cast<unsigned>(vectorTy->getNumElements()), constant);
5026 }
David Neto257c3892018-04-11 13:19:45 -04005027 Ops << MkId(VMap[constant]) << MkId(std::get<2>(*DeferredInst));
David Neto3fbb4072017-10-16 11:28:14 -04005028
5029 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005030 InsertPoint, new SPIRVInstruction(
5031 opcode, std::get<2>(*DeferredInst) + 1, Ops));
David Neto3fbb4072017-10-16 11:28:14 -04005032 };
5033
5034 switch (IndirectExtInst) {
5035 case glsl::ExtInstFindUMsb: // Implementing clz
5036 generate_extra_inst(
5037 spv::OpISub, ConstantInt::get(Type::getInt32Ty(Context), 31));
5038 break;
5039 case glsl::ExtInstAcos: // Implementing acospi
5040 case glsl::ExtInstAsin: // Implementing asinpi
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005041 case glsl::ExtInstAtan: // Implementing atanpi
David Neto3fbb4072017-10-16 11:28:14 -04005042 case glsl::ExtInstAtan2: // Implementing atan2pi
5043 generate_extra_inst(
5044 spv::OpFMul,
5045 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
5046 break;
5047
5048 default:
5049 assert(false && "internally inconsistent");
David Neto4d02a532017-09-17 12:57:44 -04005050 }
David Neto22f144c2017-06-12 14:26:21 -04005051 }
David Neto3fbb4072017-10-16 11:28:14 -04005052
David Neto862b7d82018-06-14 18:48:37 -04005053 } else if (callee_name.equals("_Z8popcounti") ||
5054 callee_name.equals("_Z8popcountj") ||
5055 callee_name.equals("_Z8popcountDv2_i") ||
5056 callee_name.equals("_Z8popcountDv3_i") ||
5057 callee_name.equals("_Z8popcountDv4_i") ||
5058 callee_name.equals("_Z8popcountDv2_j") ||
5059 callee_name.equals("_Z8popcountDv3_j") ||
5060 callee_name.equals("_Z8popcountDv4_j")) {
David Neto22f144c2017-06-12 14:26:21 -04005061 //
5062 // Generate OpBitCount
5063 //
5064 // Ops[0] = Result Type ID
5065 // Ops[1] = Base ID
David Neto257c3892018-04-11 13:19:45 -04005066 SPIRVOperandList Ops;
5067 Ops << MkId(lookupType(Call->getType()))
5068 << MkId(VMap[Call->getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04005069
5070 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005071 InsertPoint, new SPIRVInstruction(spv::OpBitCount,
David Neto22f144c2017-06-12 14:26:21 -04005072 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005073
David Neto862b7d82018-06-14 18:48:37 -04005074 } else if (callee_name.startswith(kCompositeConstructFunctionPrefix)) {
David Netoab03f432017-11-03 17:00:44 -04005075
5076 // Generate an OpCompositeConstruct
5077 SPIRVOperandList Ops;
5078
5079 // The result type.
David Neto257c3892018-04-11 13:19:45 -04005080 Ops << MkId(lookupType(Call->getType()));
David Netoab03f432017-11-03 17:00:44 -04005081
5082 for (Use &use : Call->arg_operands()) {
David Neto257c3892018-04-11 13:19:45 -04005083 Ops << MkId(VMap[use.get()]);
David Netoab03f432017-11-03 17:00:44 -04005084 }
5085
5086 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005087 InsertPoint, new SPIRVInstruction(spv::OpCompositeConstruct,
5088 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005089
Alan Baker202c8c72018-08-13 13:47:44 -04005090 } else if (callee_name.startswith(clspv::ResourceAccessorFunction())) {
5091
5092 // We have already mapped the call's result value to an ID.
5093 // Don't generate any code now.
5094
5095 } else if (callee_name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04005096
5097 // We have already mapped the call's result value to an ID.
5098 // Don't generate any code now.
5099
David Neto22f144c2017-06-12 14:26:21 -04005100 } else {
5101 //
5102 // Generate OpFunctionCall.
5103 //
5104
5105 // Ops[0] = Result Type ID
5106 // Ops[1] = Callee Function ID
5107 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
5108 SPIRVOperandList Ops;
5109
David Neto862b7d82018-06-14 18:48:37 -04005110 Ops << MkId(lookupType(Call->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005111
5112 uint32_t CalleeID = VMap[Callee];
David Neto43568eb2017-10-13 18:25:25 -04005113 if (CalleeID == 0) {
5114 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04005115 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04005116 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
5117 // causes an infinite loop. Instead, go ahead and generate
5118 // the bad function call. A validator will catch the 0-Id.
5119 // llvm_unreachable("Can't translate function call");
5120 }
David Neto22f144c2017-06-12 14:26:21 -04005121
David Neto257c3892018-04-11 13:19:45 -04005122 Ops << MkId(CalleeID);
David Neto22f144c2017-06-12 14:26:21 -04005123
David Neto22f144c2017-06-12 14:26:21 -04005124 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5125 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04005126 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04005127 }
5128
David Neto87846742018-04-11 17:36:22 -04005129 auto *CallInst = new SPIRVInstruction(spv::OpFunctionCall,
5130 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005131 SPIRVInstList.insert(InsertPoint, CallInst);
5132 }
5133 }
5134 }
5135}
5136
David Neto1a1a0582017-07-07 12:01:44 -04005137void SPIRVProducerPass::HandleDeferredDecorations(const DataLayout &DL) {
Alan Baker202c8c72018-08-13 13:47:44 -04005138 if (getTypesNeedingArrayStride().empty() && LocalArgSpecIds.empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04005139 return;
David Netoc6f3ab22018-04-06 18:02:31 -04005140 }
David Neto1a1a0582017-07-07 12:01:44 -04005141
5142 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto1a1a0582017-07-07 12:01:44 -04005143
5144 // Find an iterator pointing just past the last decoration.
5145 bool seen_decorations = false;
5146 auto DecoInsertPoint =
5147 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
5148 [&seen_decorations](SPIRVInstruction *Inst) -> bool {
5149 const bool is_decoration =
5150 Inst->getOpcode() == spv::OpDecorate ||
5151 Inst->getOpcode() == spv::OpMemberDecorate;
5152 if (is_decoration) {
5153 seen_decorations = true;
5154 return false;
5155 } else {
5156 return seen_decorations;
5157 }
5158 });
5159
David Netoc6f3ab22018-04-06 18:02:31 -04005160 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
5161 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07005162 for (auto *type : getTypesNeedingArrayStride()) {
5163 Type *elemTy = nullptr;
5164 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
5165 elemTy = ptrTy->getElementType();
5166 } else if (auto* arrayTy = dyn_cast<ArrayType>(type)) {
5167 elemTy = arrayTy->getArrayElementType();
5168 } else if (auto* seqTy = dyn_cast<SequentialType>(type)) {
5169 elemTy = seqTy->getSequentialElementType();
5170 } else {
5171 errs() << "Unhandled strided type " << *type << "\n";
5172 llvm_unreachable("Unhandled strided type");
5173 }
David Neto1a1a0582017-07-07 12:01:44 -04005174
5175 // Ops[0] = Target ID
5176 // Ops[1] = Decoration (ArrayStride)
5177 // Ops[2] = Stride number (Literal Number)
5178 SPIRVOperandList Ops;
5179
David Neto85082642018-03-24 06:55:20 -07005180 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Neil Henning39672102017-09-29 14:33:13 +01005181 const uint32_t stride = static_cast<uint32_t>(DL.getTypeAllocSize(elemTy));
David Neto257c3892018-04-11 13:19:45 -04005182
5183 Ops << MkId(lookupType(type)) << MkNum(spv::DecorationArrayStride)
5184 << MkNum(stride);
David Neto1a1a0582017-07-07 12:01:44 -04005185
David Neto87846742018-04-11 17:36:22 -04005186 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto1a1a0582017-07-07 12:01:44 -04005187 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
5188 }
David Netoc6f3ab22018-04-06 18:02:31 -04005189
5190 // Emit SpecId decorations targeting the array size value.
Alan Baker202c8c72018-08-13 13:47:44 -04005191 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
5192 ++spec_id) {
5193 LocalArgInfo& arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04005194 SPIRVOperandList Ops;
5195 Ops << MkId(arg_info.array_size_id) << MkNum(spv::DecorationSpecId)
5196 << MkNum(arg_info.spec_id);
5197 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04005198 new SPIRVInstruction(spv::OpDecorate, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04005199 }
David Neto1a1a0582017-07-07 12:01:44 -04005200}
5201
David Neto22f144c2017-06-12 14:26:21 -04005202glsl::ExtInst SPIRVProducerPass::getExtInstEnum(StringRef Name) {
5203 return StringSwitch<glsl::ExtInst>(Name)
5204 .Case("_Z3absi", glsl::ExtInst::ExtInstSAbs)
5205 .Case("_Z3absDv2_i", glsl::ExtInst::ExtInstSAbs)
5206 .Case("_Z3absDv3_i", glsl::ExtInst::ExtInstSAbs)
5207 .Case("_Z3absDv4_i", glsl::ExtInst::ExtInstSAbs)
5208 .Case("_Z5clampiii", glsl::ExtInst::ExtInstSClamp)
5209 .Case("_Z5clampDv2_iS_S_", glsl::ExtInst::ExtInstSClamp)
5210 .Case("_Z5clampDv3_iS_S_", glsl::ExtInst::ExtInstSClamp)
5211 .Case("_Z5clampDv4_iS_S_", glsl::ExtInst::ExtInstSClamp)
5212 .Case("_Z5clampjjj", glsl::ExtInst::ExtInstUClamp)
5213 .Case("_Z5clampDv2_jS_S_", glsl::ExtInst::ExtInstUClamp)
5214 .Case("_Z5clampDv3_jS_S_", glsl::ExtInst::ExtInstUClamp)
5215 .Case("_Z5clampDv4_jS_S_", glsl::ExtInst::ExtInstUClamp)
5216 .Case("_Z5clampfff", glsl::ExtInst::ExtInstFClamp)
5217 .Case("_Z5clampDv2_fS_S_", glsl::ExtInst::ExtInstFClamp)
5218 .Case("_Z5clampDv3_fS_S_", glsl::ExtInst::ExtInstFClamp)
5219 .Case("_Z5clampDv4_fS_S_", glsl::ExtInst::ExtInstFClamp)
David Neto22f144c2017-06-12 14:26:21 -04005220 .Case("_Z3maxii", glsl::ExtInst::ExtInstSMax)
5221 .Case("_Z3maxDv2_iS_", glsl::ExtInst::ExtInstSMax)
5222 .Case("_Z3maxDv3_iS_", glsl::ExtInst::ExtInstSMax)
5223 .Case("_Z3maxDv4_iS_", glsl::ExtInst::ExtInstSMax)
5224 .Case("_Z3maxjj", glsl::ExtInst::ExtInstUMax)
5225 .Case("_Z3maxDv2_jS_", glsl::ExtInst::ExtInstUMax)
5226 .Case("_Z3maxDv3_jS_", glsl::ExtInst::ExtInstUMax)
5227 .Case("_Z3maxDv4_jS_", glsl::ExtInst::ExtInstUMax)
5228 .Case("_Z3maxff", glsl::ExtInst::ExtInstFMax)
5229 .Case("_Z3maxDv2_fS_", glsl::ExtInst::ExtInstFMax)
5230 .Case("_Z3maxDv3_fS_", glsl::ExtInst::ExtInstFMax)
5231 .Case("_Z3maxDv4_fS_", glsl::ExtInst::ExtInstFMax)
5232 .StartsWith("_Z4fmax", glsl::ExtInst::ExtInstFMax)
5233 .Case("_Z3minii", glsl::ExtInst::ExtInstSMin)
5234 .Case("_Z3minDv2_iS_", glsl::ExtInst::ExtInstSMin)
5235 .Case("_Z3minDv3_iS_", glsl::ExtInst::ExtInstSMin)
5236 .Case("_Z3minDv4_iS_", glsl::ExtInst::ExtInstSMin)
5237 .Case("_Z3minjj", glsl::ExtInst::ExtInstUMin)
5238 .Case("_Z3minDv2_jS_", glsl::ExtInst::ExtInstUMin)
5239 .Case("_Z3minDv3_jS_", glsl::ExtInst::ExtInstUMin)
5240 .Case("_Z3minDv4_jS_", glsl::ExtInst::ExtInstUMin)
5241 .Case("_Z3minff", glsl::ExtInst::ExtInstFMin)
5242 .Case("_Z3minDv2_fS_", glsl::ExtInst::ExtInstFMin)
5243 .Case("_Z3minDv3_fS_", glsl::ExtInst::ExtInstFMin)
5244 .Case("_Z3minDv4_fS_", glsl::ExtInst::ExtInstFMin)
5245 .StartsWith("_Z4fmin", glsl::ExtInst::ExtInstFMin)
5246 .StartsWith("_Z7degrees", glsl::ExtInst::ExtInstDegrees)
5247 .StartsWith("_Z7radians", glsl::ExtInst::ExtInstRadians)
5248 .StartsWith("_Z3mix", glsl::ExtInst::ExtInstFMix)
5249 .StartsWith("_Z4acos", glsl::ExtInst::ExtInstAcos)
5250 .StartsWith("_Z5acosh", glsl::ExtInst::ExtInstAcosh)
5251 .StartsWith("_Z4asin", glsl::ExtInst::ExtInstAsin)
5252 .StartsWith("_Z5asinh", glsl::ExtInst::ExtInstAsinh)
5253 .StartsWith("_Z4atan", glsl::ExtInst::ExtInstAtan)
5254 .StartsWith("_Z5atan2", glsl::ExtInst::ExtInstAtan2)
5255 .StartsWith("_Z5atanh", glsl::ExtInst::ExtInstAtanh)
5256 .StartsWith("_Z4ceil", glsl::ExtInst::ExtInstCeil)
5257 .StartsWith("_Z3sin", glsl::ExtInst::ExtInstSin)
5258 .StartsWith("_Z4sinh", glsl::ExtInst::ExtInstSinh)
5259 .StartsWith("_Z8half_sin", glsl::ExtInst::ExtInstSin)
5260 .StartsWith("_Z10native_sin", glsl::ExtInst::ExtInstSin)
5261 .StartsWith("_Z3cos", glsl::ExtInst::ExtInstCos)
5262 .StartsWith("_Z4cosh", glsl::ExtInst::ExtInstCosh)
5263 .StartsWith("_Z8half_cos", glsl::ExtInst::ExtInstCos)
5264 .StartsWith("_Z10native_cos", glsl::ExtInst::ExtInstCos)
5265 .StartsWith("_Z3tan", glsl::ExtInst::ExtInstTan)
5266 .StartsWith("_Z4tanh", glsl::ExtInst::ExtInstTanh)
5267 .StartsWith("_Z8half_tan", glsl::ExtInst::ExtInstTan)
5268 .StartsWith("_Z10native_tan", glsl::ExtInst::ExtInstTan)
5269 .StartsWith("_Z3exp", glsl::ExtInst::ExtInstExp)
5270 .StartsWith("_Z8half_exp", glsl::ExtInst::ExtInstExp)
5271 .StartsWith("_Z10native_exp", glsl::ExtInst::ExtInstExp)
5272 .StartsWith("_Z4exp2", glsl::ExtInst::ExtInstExp2)
5273 .StartsWith("_Z9half_exp2", glsl::ExtInst::ExtInstExp2)
5274 .StartsWith("_Z11native_exp2", glsl::ExtInst::ExtInstExp2)
5275 .StartsWith("_Z3log", glsl::ExtInst::ExtInstLog)
5276 .StartsWith("_Z8half_log", glsl::ExtInst::ExtInstLog)
5277 .StartsWith("_Z10native_log", glsl::ExtInst::ExtInstLog)
5278 .StartsWith("_Z4log2", glsl::ExtInst::ExtInstLog2)
5279 .StartsWith("_Z9half_log2", glsl::ExtInst::ExtInstLog2)
5280 .StartsWith("_Z11native_log2", glsl::ExtInst::ExtInstLog2)
5281 .StartsWith("_Z4fabs", glsl::ExtInst::ExtInstFAbs)
5282 .StartsWith("_Z5floor", glsl::ExtInst::ExtInstFloor)
5283 .StartsWith("_Z5ldexp", glsl::ExtInst::ExtInstLdexp)
5284 .StartsWith("_Z3pow", glsl::ExtInst::ExtInstPow)
5285 .StartsWith("_Z4powr", glsl::ExtInst::ExtInstPow)
5286 .StartsWith("_Z9half_powr", glsl::ExtInst::ExtInstPow)
5287 .StartsWith("_Z11native_powr", glsl::ExtInst::ExtInstPow)
5288 .StartsWith("_Z5round", glsl::ExtInst::ExtInstRound)
5289 .StartsWith("_Z4sqrt", glsl::ExtInst::ExtInstSqrt)
5290 .StartsWith("_Z9half_sqrt", glsl::ExtInst::ExtInstSqrt)
5291 .StartsWith("_Z11native_sqrt", glsl::ExtInst::ExtInstSqrt)
5292 .StartsWith("_Z5rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5293 .StartsWith("_Z10half_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5294 .StartsWith("_Z12native_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5295 .StartsWith("_Z5trunc", glsl::ExtInst::ExtInstTrunc)
5296 .StartsWith("_Z5frexp", glsl::ExtInst::ExtInstFrexp)
5297 .StartsWith("_Z4sign", glsl::ExtInst::ExtInstFSign)
5298 .StartsWith("_Z6length", glsl::ExtInst::ExtInstLength)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005299 .StartsWith("_Z11fast_length", glsl::ExtInst::ExtInstLength)
David Neto22f144c2017-06-12 14:26:21 -04005300 .StartsWith("_Z8distance", glsl::ExtInst::ExtInstDistance)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005301 .StartsWith("_Z13fast_distance", glsl::ExtInst::ExtInstDistance)
David Netoe9a03512017-10-16 10:08:27 -04005302 .StartsWith("_Z4step", glsl::ExtInst::ExtInstStep)
David Neto22f144c2017-06-12 14:26:21 -04005303 .Case("_Z5crossDv3_fS_", glsl::ExtInst::ExtInstCross)
5304 .StartsWith("_Z9normalize", glsl::ExtInst::ExtInstNormalize)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005305 .StartsWith("_Z14fast_normalize", glsl::ExtInst::ExtInstNormalize)
David Neto22f144c2017-06-12 14:26:21 -04005306 .StartsWith("llvm.fmuladd.", glsl::ExtInst::ExtInstFma)
5307 .Case("spirv.unpack.v2f16", glsl::ExtInst::ExtInstUnpackHalf2x16)
5308 .Case("spirv.pack.v2f16", glsl::ExtInst::ExtInstPackHalf2x16)
David Neto62653202017-10-16 19:05:18 -04005309 .Case("clspv.fract.f", glsl::ExtInst::ExtInstFract)
5310 .Case("clspv.fract.v2f", glsl::ExtInst::ExtInstFract)
5311 .Case("clspv.fract.v3f", glsl::ExtInst::ExtInstFract)
5312 .Case("clspv.fract.v4f", glsl::ExtInst::ExtInstFract)
David Neto3fbb4072017-10-16 11:28:14 -04005313 .Default(kGlslExtInstBad);
5314}
5315
5316glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(StringRef Name) {
5317 // Check indirect cases.
5318 return StringSwitch<glsl::ExtInst>(Name)
5319 .StartsWith("_Z3clz", glsl::ExtInst::ExtInstFindUMsb)
5320 // Use exact match on float arg because these need a multiply
5321 // of a constant of the right floating point type.
5322 .Case("_Z6acospif", glsl::ExtInst::ExtInstAcos)
5323 .Case("_Z6acospiDv2_f", glsl::ExtInst::ExtInstAcos)
5324 .Case("_Z6acospiDv3_f", glsl::ExtInst::ExtInstAcos)
5325 .Case("_Z6acospiDv4_f", glsl::ExtInst::ExtInstAcos)
5326 .Case("_Z6asinpif", glsl::ExtInst::ExtInstAsin)
5327 .Case("_Z6asinpiDv2_f", glsl::ExtInst::ExtInstAsin)
5328 .Case("_Z6asinpiDv3_f", glsl::ExtInst::ExtInstAsin)
5329 .Case("_Z6asinpiDv4_f", glsl::ExtInst::ExtInstAsin)
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005330 .Case("_Z6atanpif", glsl::ExtInst::ExtInstAtan)
5331 .Case("_Z6atanpiDv2_f", glsl::ExtInst::ExtInstAtan)
5332 .Case("_Z6atanpiDv3_f", glsl::ExtInst::ExtInstAtan)
5333 .Case("_Z6atanpiDv4_f", glsl::ExtInst::ExtInstAtan)
David Neto3fbb4072017-10-16 11:28:14 -04005334 .Case("_Z7atan2piff", glsl::ExtInst::ExtInstAtan2)
5335 .Case("_Z7atan2piDv2_fS_", glsl::ExtInst::ExtInstAtan2)
5336 .Case("_Z7atan2piDv3_fS_", glsl::ExtInst::ExtInstAtan2)
5337 .Case("_Z7atan2piDv4_fS_", glsl::ExtInst::ExtInstAtan2)
5338 .Default(kGlslExtInstBad);
5339}
5340
5341glsl::ExtInst SPIRVProducerPass::getDirectOrIndirectExtInstEnum(StringRef Name) {
5342 auto direct = getExtInstEnum(Name);
5343 if (direct != kGlslExtInstBad)
5344 return direct;
5345 return getIndirectExtInstEnum(Name);
David Neto22f144c2017-06-12 14:26:21 -04005346}
5347
5348void SPIRVProducerPass::PrintResID(SPIRVInstruction *Inst) {
5349 out << "%" << Inst->getResultID();
5350}
5351
5352void SPIRVProducerPass::PrintOpcode(SPIRVInstruction *Inst) {
5353 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5354 out << "\t" << spv::getOpName(Opcode);
5355}
5356
5357void SPIRVProducerPass::PrintOperand(SPIRVOperand *Op) {
5358 SPIRVOperandType OpTy = Op->getType();
5359 switch (OpTy) {
5360 default: {
5361 llvm_unreachable("Unsupported SPIRV Operand Type???");
5362 break;
5363 }
5364 case SPIRVOperandType::NUMBERID: {
5365 out << "%" << Op->getNumID();
5366 break;
5367 }
5368 case SPIRVOperandType::LITERAL_STRING: {
5369 out << "\"" << Op->getLiteralStr() << "\"";
5370 break;
5371 }
5372 case SPIRVOperandType::LITERAL_INTEGER: {
5373 // TODO: Handle LiteralNum carefully.
5374 for (auto Word : Op->getLiteralNum()) {
5375 out << Word;
5376 }
5377 break;
5378 }
5379 case SPIRVOperandType::LITERAL_FLOAT: {
5380 // TODO: Handle LiteralNum carefully.
5381 for (auto Word : Op->getLiteralNum()) {
5382 APFloat APF = APFloat(APFloat::IEEEsingle(), APInt(32, Word));
5383 SmallString<8> Str;
5384 APF.toString(Str, 6, 2);
5385 out << Str;
5386 }
5387 break;
5388 }
5389 }
5390}
5391
5392void SPIRVProducerPass::PrintCapability(SPIRVOperand *Op) {
5393 spv::Capability Cap = static_cast<spv::Capability>(Op->getNumID());
5394 out << spv::getCapabilityName(Cap);
5395}
5396
5397void SPIRVProducerPass::PrintExtInst(SPIRVOperand *Op) {
5398 auto LiteralNum = Op->getLiteralNum();
5399 glsl::ExtInst Ext = static_cast<glsl::ExtInst>(LiteralNum[0]);
5400 out << glsl::getExtInstName(Ext);
5401}
5402
5403void SPIRVProducerPass::PrintAddrModel(SPIRVOperand *Op) {
5404 spv::AddressingModel AddrModel =
5405 static_cast<spv::AddressingModel>(Op->getNumID());
5406 out << spv::getAddressingModelName(AddrModel);
5407}
5408
5409void SPIRVProducerPass::PrintMemModel(SPIRVOperand *Op) {
5410 spv::MemoryModel MemModel = static_cast<spv::MemoryModel>(Op->getNumID());
5411 out << spv::getMemoryModelName(MemModel);
5412}
5413
5414void SPIRVProducerPass::PrintExecModel(SPIRVOperand *Op) {
5415 spv::ExecutionModel ExecModel =
5416 static_cast<spv::ExecutionModel>(Op->getNumID());
5417 out << spv::getExecutionModelName(ExecModel);
5418}
5419
5420void SPIRVProducerPass::PrintExecMode(SPIRVOperand *Op) {
5421 spv::ExecutionMode ExecMode = static_cast<spv::ExecutionMode>(Op->getNumID());
5422 out << spv::getExecutionModeName(ExecMode);
5423}
5424
5425void SPIRVProducerPass::PrintSourceLanguage(SPIRVOperand *Op) {
5426 spv::SourceLanguage SourceLang = static_cast<spv::SourceLanguage>(Op->getNumID());
5427 out << spv::getSourceLanguageName(SourceLang);
5428}
5429
5430void SPIRVProducerPass::PrintFuncCtrl(SPIRVOperand *Op) {
5431 spv::FunctionControlMask FuncCtrl =
5432 static_cast<spv::FunctionControlMask>(Op->getNumID());
5433 out << spv::getFunctionControlName(FuncCtrl);
5434}
5435
5436void SPIRVProducerPass::PrintStorageClass(SPIRVOperand *Op) {
5437 spv::StorageClass StClass = static_cast<spv::StorageClass>(Op->getNumID());
5438 out << getStorageClassName(StClass);
5439}
5440
5441void SPIRVProducerPass::PrintDecoration(SPIRVOperand *Op) {
5442 spv::Decoration Deco = static_cast<spv::Decoration>(Op->getNumID());
5443 out << getDecorationName(Deco);
5444}
5445
5446void SPIRVProducerPass::PrintBuiltIn(SPIRVOperand *Op) {
5447 spv::BuiltIn BIn = static_cast<spv::BuiltIn>(Op->getNumID());
5448 out << getBuiltInName(BIn);
5449}
5450
5451void SPIRVProducerPass::PrintSelectionControl(SPIRVOperand *Op) {
5452 spv::SelectionControlMask BIn =
5453 static_cast<spv::SelectionControlMask>(Op->getNumID());
5454 out << getSelectionControlName(BIn);
5455}
5456
5457void SPIRVProducerPass::PrintLoopControl(SPIRVOperand *Op) {
5458 spv::LoopControlMask BIn = static_cast<spv::LoopControlMask>(Op->getNumID());
5459 out << getLoopControlName(BIn);
5460}
5461
5462void SPIRVProducerPass::PrintDimensionality(SPIRVOperand *Op) {
5463 spv::Dim DIM = static_cast<spv::Dim>(Op->getNumID());
5464 out << getDimName(DIM);
5465}
5466
5467void SPIRVProducerPass::PrintImageFormat(SPIRVOperand *Op) {
5468 spv::ImageFormat Format = static_cast<spv::ImageFormat>(Op->getNumID());
5469 out << getImageFormatName(Format);
5470}
5471
5472void SPIRVProducerPass::PrintMemoryAccess(SPIRVOperand *Op) {
5473 out << spv::getMemoryAccessName(
5474 static_cast<spv::MemoryAccessMask>(Op->getNumID()));
5475}
5476
5477void SPIRVProducerPass::PrintImageOperandsType(SPIRVOperand *Op) {
5478 auto LiteralNum = Op->getLiteralNum();
5479 spv::ImageOperandsMask Type =
5480 static_cast<spv::ImageOperandsMask>(LiteralNum[0]);
5481 out << getImageOperandsName(Type);
5482}
5483
5484void SPIRVProducerPass::WriteSPIRVAssembly() {
5485 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5486
5487 for (auto Inst : SPIRVInstList) {
5488 SPIRVOperandList Ops = Inst->getOperands();
5489 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5490
5491 switch (Opcode) {
5492 default: {
5493 llvm_unreachable("Unsupported SPIRV instruction");
5494 break;
5495 }
5496 case spv::OpCapability: {
5497 // Ops[0] = Capability
5498 PrintOpcode(Inst);
5499 out << " ";
5500 PrintCapability(Ops[0]);
5501 out << "\n";
5502 break;
5503 }
5504 case spv::OpMemoryModel: {
5505 // Ops[0] = Addressing Model
5506 // Ops[1] = Memory Model
5507 PrintOpcode(Inst);
5508 out << " ";
5509 PrintAddrModel(Ops[0]);
5510 out << " ";
5511 PrintMemModel(Ops[1]);
5512 out << "\n";
5513 break;
5514 }
5515 case spv::OpEntryPoint: {
5516 // Ops[0] = Execution Model
5517 // Ops[1] = EntryPoint ID
5518 // Ops[2] = Name (Literal String)
5519 // Ops[3] ... Ops[n] = Interface ID
5520 PrintOpcode(Inst);
5521 out << " ";
5522 PrintExecModel(Ops[0]);
5523 for (uint32_t i = 1; i < Ops.size(); i++) {
5524 out << " ";
5525 PrintOperand(Ops[i]);
5526 }
5527 out << "\n";
5528 break;
5529 }
5530 case spv::OpExecutionMode: {
5531 // Ops[0] = Entry Point ID
5532 // Ops[1] = Execution Mode
5533 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
5534 PrintOpcode(Inst);
5535 out << " ";
5536 PrintOperand(Ops[0]);
5537 out << " ";
5538 PrintExecMode(Ops[1]);
5539 for (uint32_t i = 2; i < Ops.size(); i++) {
5540 out << " ";
5541 PrintOperand(Ops[i]);
5542 }
5543 out << "\n";
5544 break;
5545 }
5546 case spv::OpSource: {
5547 // Ops[0] = SourceLanguage ID
5548 // Ops[1] = Version (LiteralNum)
5549 PrintOpcode(Inst);
5550 out << " ";
5551 PrintSourceLanguage(Ops[0]);
5552 out << " ";
5553 PrintOperand(Ops[1]);
5554 out << "\n";
5555 break;
5556 }
5557 case spv::OpDecorate: {
5558 // Ops[0] = Target ID
5559 // Ops[1] = Decoration (Block or BufferBlock)
5560 // Ops[2] ... Ops[n] = Optional literals according to Decoration
5561 PrintOpcode(Inst);
5562 out << " ";
5563 PrintOperand(Ops[0]);
5564 out << " ";
5565 PrintDecoration(Ops[1]);
5566 // Handle BuiltIn OpDecorate specially.
5567 if (Ops[1]->getNumID() == spv::DecorationBuiltIn) {
5568 out << " ";
5569 PrintBuiltIn(Ops[2]);
5570 } else {
5571 for (uint32_t i = 2; i < Ops.size(); i++) {
5572 out << " ";
5573 PrintOperand(Ops[i]);
5574 }
5575 }
5576 out << "\n";
5577 break;
5578 }
5579 case spv::OpMemberDecorate: {
5580 // Ops[0] = Structure Type ID
5581 // Ops[1] = Member Index(Literal Number)
5582 // Ops[2] = Decoration
5583 // Ops[3] ... Ops[n] = Optional literals according to Decoration
5584 PrintOpcode(Inst);
5585 out << " ";
5586 PrintOperand(Ops[0]);
5587 out << " ";
5588 PrintOperand(Ops[1]);
5589 out << " ";
5590 PrintDecoration(Ops[2]);
5591 for (uint32_t i = 3; i < Ops.size(); i++) {
5592 out << " ";
5593 PrintOperand(Ops[i]);
5594 }
5595 out << "\n";
5596 break;
5597 }
5598 case spv::OpTypePointer: {
5599 // Ops[0] = Storage Class
5600 // Ops[1] = Element Type ID
5601 PrintResID(Inst);
5602 out << " = ";
5603 PrintOpcode(Inst);
5604 out << " ";
5605 PrintStorageClass(Ops[0]);
5606 out << " ";
5607 PrintOperand(Ops[1]);
5608 out << "\n";
5609 break;
5610 }
5611 case spv::OpTypeImage: {
5612 // Ops[0] = Sampled Type ID
5613 // Ops[1] = Dim ID
5614 // Ops[2] = Depth (Literal Number)
5615 // Ops[3] = Arrayed (Literal Number)
5616 // Ops[4] = MS (Literal Number)
5617 // Ops[5] = Sampled (Literal Number)
5618 // Ops[6] = Image Format ID
5619 PrintResID(Inst);
5620 out << " = ";
5621 PrintOpcode(Inst);
5622 out << " ";
5623 PrintOperand(Ops[0]);
5624 out << " ";
5625 PrintDimensionality(Ops[1]);
5626 out << " ";
5627 PrintOperand(Ops[2]);
5628 out << " ";
5629 PrintOperand(Ops[3]);
5630 out << " ";
5631 PrintOperand(Ops[4]);
5632 out << " ";
5633 PrintOperand(Ops[5]);
5634 out << " ";
5635 PrintImageFormat(Ops[6]);
5636 out << "\n";
5637 break;
5638 }
5639 case spv::OpFunction: {
5640 // Ops[0] : Result Type ID
5641 // Ops[1] : Function Control
5642 // Ops[2] : Function Type ID
5643 PrintResID(Inst);
5644 out << " = ";
5645 PrintOpcode(Inst);
5646 out << " ";
5647 PrintOperand(Ops[0]);
5648 out << " ";
5649 PrintFuncCtrl(Ops[1]);
5650 out << " ";
5651 PrintOperand(Ops[2]);
5652 out << "\n";
5653 break;
5654 }
5655 case spv::OpSelectionMerge: {
5656 // Ops[0] = Merge Block ID
5657 // Ops[1] = Selection Control
5658 PrintOpcode(Inst);
5659 out << " ";
5660 PrintOperand(Ops[0]);
5661 out << " ";
5662 PrintSelectionControl(Ops[1]);
5663 out << "\n";
5664 break;
5665 }
5666 case spv::OpLoopMerge: {
5667 // Ops[0] = Merge Block ID
5668 // Ops[1] = Continue Target ID
5669 // Ops[2] = Selection Control
5670 PrintOpcode(Inst);
5671 out << " ";
5672 PrintOperand(Ops[0]);
5673 out << " ";
5674 PrintOperand(Ops[1]);
5675 out << " ";
5676 PrintLoopControl(Ops[2]);
5677 out << "\n";
5678 break;
5679 }
5680 case spv::OpImageSampleExplicitLod: {
5681 // Ops[0] = Result Type ID
5682 // Ops[1] = Sampled Image ID
5683 // Ops[2] = Coordinate ID
5684 // Ops[3] = Image Operands Type ID
5685 // Ops[4] ... Ops[n] = Operands ID
5686 PrintResID(Inst);
5687 out << " = ";
5688 PrintOpcode(Inst);
5689 for (uint32_t i = 0; i < 3; i++) {
5690 out << " ";
5691 PrintOperand(Ops[i]);
5692 }
5693 out << " ";
5694 PrintImageOperandsType(Ops[3]);
5695 for (uint32_t i = 4; i < Ops.size(); i++) {
5696 out << " ";
5697 PrintOperand(Ops[i]);
5698 }
5699 out << "\n";
5700 break;
5701 }
5702 case spv::OpVariable: {
5703 // Ops[0] : Result Type ID
5704 // Ops[1] : Storage Class
5705 // Ops[2] ... Ops[n] = Initializer IDs
5706 PrintResID(Inst);
5707 out << " = ";
5708 PrintOpcode(Inst);
5709 out << " ";
5710 PrintOperand(Ops[0]);
5711 out << " ";
5712 PrintStorageClass(Ops[1]);
5713 for (uint32_t i = 2; i < Ops.size(); i++) {
5714 out << " ";
5715 PrintOperand(Ops[i]);
5716 }
5717 out << "\n";
5718 break;
5719 }
5720 case spv::OpExtInst: {
5721 // Ops[0] = Result Type ID
5722 // Ops[1] = Set ID (OpExtInstImport ID)
5723 // Ops[2] = Instruction Number (Literal Number)
5724 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5725 PrintResID(Inst);
5726 out << " = ";
5727 PrintOpcode(Inst);
5728 out << " ";
5729 PrintOperand(Ops[0]);
5730 out << " ";
5731 PrintOperand(Ops[1]);
5732 out << " ";
5733 PrintExtInst(Ops[2]);
5734 for (uint32_t i = 3; i < Ops.size(); i++) {
5735 out << " ";
5736 PrintOperand(Ops[i]);
5737 }
5738 out << "\n";
5739 break;
5740 }
5741 case spv::OpCopyMemory: {
5742 // Ops[0] = Addressing Model
5743 // Ops[1] = Memory Model
5744 PrintOpcode(Inst);
5745 out << " ";
5746 PrintOperand(Ops[0]);
5747 out << " ";
5748 PrintOperand(Ops[1]);
5749 out << " ";
5750 PrintMemoryAccess(Ops[2]);
5751 out << " ";
5752 PrintOperand(Ops[3]);
5753 out << "\n";
5754 break;
5755 }
5756 case spv::OpExtension:
5757 case spv::OpControlBarrier:
5758 case spv::OpMemoryBarrier:
5759 case spv::OpBranch:
5760 case spv::OpBranchConditional:
5761 case spv::OpStore:
5762 case spv::OpImageWrite:
5763 case spv::OpReturnValue:
5764 case spv::OpReturn:
5765 case spv::OpFunctionEnd: {
5766 PrintOpcode(Inst);
5767 for (uint32_t i = 0; i < Ops.size(); i++) {
5768 out << " ";
5769 PrintOperand(Ops[i]);
5770 }
5771 out << "\n";
5772 break;
5773 }
5774 case spv::OpExtInstImport:
5775 case spv::OpTypeRuntimeArray:
5776 case spv::OpTypeStruct:
5777 case spv::OpTypeSampler:
5778 case spv::OpTypeSampledImage:
5779 case spv::OpTypeInt:
5780 case spv::OpTypeFloat:
5781 case spv::OpTypeArray:
5782 case spv::OpTypeVector:
5783 case spv::OpTypeBool:
5784 case spv::OpTypeVoid:
5785 case spv::OpTypeFunction:
5786 case spv::OpFunctionParameter:
5787 case spv::OpLabel:
5788 case spv::OpPhi:
5789 case spv::OpLoad:
5790 case spv::OpSelect:
5791 case spv::OpAccessChain:
5792 case spv::OpPtrAccessChain:
5793 case spv::OpInBoundsAccessChain:
5794 case spv::OpUConvert:
5795 case spv::OpSConvert:
5796 case spv::OpConvertFToU:
5797 case spv::OpConvertFToS:
5798 case spv::OpConvertUToF:
5799 case spv::OpConvertSToF:
5800 case spv::OpFConvert:
5801 case spv::OpConvertPtrToU:
5802 case spv::OpConvertUToPtr:
5803 case spv::OpBitcast:
5804 case spv::OpIAdd:
5805 case spv::OpFAdd:
5806 case spv::OpISub:
5807 case spv::OpFSub:
5808 case spv::OpIMul:
5809 case spv::OpFMul:
5810 case spv::OpUDiv:
5811 case spv::OpSDiv:
5812 case spv::OpFDiv:
5813 case spv::OpUMod:
5814 case spv::OpSRem:
5815 case spv::OpFRem:
5816 case spv::OpBitwiseOr:
5817 case spv::OpBitwiseXor:
5818 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005819 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005820 case spv::OpShiftLeftLogical:
5821 case spv::OpShiftRightLogical:
5822 case spv::OpShiftRightArithmetic:
5823 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04005824 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04005825 case spv::OpCompositeExtract:
5826 case spv::OpVectorExtractDynamic:
5827 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04005828 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04005829 case spv::OpVectorInsertDynamic:
5830 case spv::OpVectorShuffle:
5831 case spv::OpIEqual:
5832 case spv::OpINotEqual:
5833 case spv::OpUGreaterThan:
5834 case spv::OpUGreaterThanEqual:
5835 case spv::OpULessThan:
5836 case spv::OpULessThanEqual:
5837 case spv::OpSGreaterThan:
5838 case spv::OpSGreaterThanEqual:
5839 case spv::OpSLessThan:
5840 case spv::OpSLessThanEqual:
5841 case spv::OpFOrdEqual:
5842 case spv::OpFOrdGreaterThan:
5843 case spv::OpFOrdGreaterThanEqual:
5844 case spv::OpFOrdLessThan:
5845 case spv::OpFOrdLessThanEqual:
5846 case spv::OpFOrdNotEqual:
5847 case spv::OpFUnordEqual:
5848 case spv::OpFUnordGreaterThan:
5849 case spv::OpFUnordGreaterThanEqual:
5850 case spv::OpFUnordLessThan:
5851 case spv::OpFUnordLessThanEqual:
5852 case spv::OpFUnordNotEqual:
5853 case spv::OpSampledImage:
5854 case spv::OpFunctionCall:
5855 case spv::OpConstantTrue:
5856 case spv::OpConstantFalse:
5857 case spv::OpConstant:
5858 case spv::OpSpecConstant:
5859 case spv::OpConstantComposite:
5860 case spv::OpSpecConstantComposite:
5861 case spv::OpConstantNull:
5862 case spv::OpLogicalOr:
5863 case spv::OpLogicalAnd:
5864 case spv::OpLogicalNot:
5865 case spv::OpLogicalNotEqual:
5866 case spv::OpUndef:
5867 case spv::OpIsInf:
5868 case spv::OpIsNan:
5869 case spv::OpAny:
5870 case spv::OpAll:
David Neto5c22a252018-03-15 16:07:41 -04005871 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04005872 case spv::OpAtomicIAdd:
5873 case spv::OpAtomicISub:
5874 case spv::OpAtomicExchange:
5875 case spv::OpAtomicIIncrement:
5876 case spv::OpAtomicIDecrement:
5877 case spv::OpAtomicCompareExchange:
5878 case spv::OpAtomicUMin:
5879 case spv::OpAtomicSMin:
5880 case spv::OpAtomicUMax:
5881 case spv::OpAtomicSMax:
5882 case spv::OpAtomicAnd:
5883 case spv::OpAtomicOr:
5884 case spv::OpAtomicXor:
5885 case spv::OpDot: {
5886 PrintResID(Inst);
5887 out << " = ";
5888 PrintOpcode(Inst);
5889 for (uint32_t i = 0; i < Ops.size(); i++) {
5890 out << " ";
5891 PrintOperand(Ops[i]);
5892 }
5893 out << "\n";
5894 break;
5895 }
5896 }
5897 }
5898}
5899
5900void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04005901 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04005902}
5903
5904void SPIRVProducerPass::WriteResultID(SPIRVInstruction *Inst) {
5905 WriteOneWord(Inst->getResultID());
5906}
5907
5908void SPIRVProducerPass::WriteWordCountAndOpcode(SPIRVInstruction *Inst) {
5909 // High 16 bit : Word Count
5910 // Low 16 bit : Opcode
5911 uint32_t Word = Inst->getOpcode();
David Netoee2660d2018-06-28 16:31:29 -04005912 const uint32_t count = Inst->getWordCount();
5913 if (count > 65535) {
5914 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
5915 llvm_unreachable("Word count too high");
5916 }
David Neto22f144c2017-06-12 14:26:21 -04005917 Word |= Inst->getWordCount() << 16;
5918 WriteOneWord(Word);
5919}
5920
5921void SPIRVProducerPass::WriteOperand(SPIRVOperand *Op) {
5922 SPIRVOperandType OpTy = Op->getType();
5923 switch (OpTy) {
5924 default: {
5925 llvm_unreachable("Unsupported SPIRV Operand Type???");
5926 break;
5927 }
5928 case SPIRVOperandType::NUMBERID: {
5929 WriteOneWord(Op->getNumID());
5930 break;
5931 }
5932 case SPIRVOperandType::LITERAL_STRING: {
5933 std::string Str = Op->getLiteralStr();
5934 const char *Data = Str.c_str();
5935 size_t WordSize = Str.size() / 4;
5936 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
5937 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
5938 }
5939
5940 uint32_t Remainder = Str.size() % 4;
5941 uint32_t LastWord = 0;
5942 if (Remainder) {
5943 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
5944 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
5945 }
5946 }
5947
5948 WriteOneWord(LastWord);
5949 break;
5950 }
5951 case SPIRVOperandType::LITERAL_INTEGER:
5952 case SPIRVOperandType::LITERAL_FLOAT: {
5953 auto LiteralNum = Op->getLiteralNum();
5954 // TODO: Handle LiteranNum carefully.
5955 for (auto Word : LiteralNum) {
5956 WriteOneWord(Word);
5957 }
5958 break;
5959 }
5960 }
5961}
5962
5963void SPIRVProducerPass::WriteSPIRVBinary() {
5964 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5965
5966 for (auto Inst : SPIRVInstList) {
David Netoc6f3ab22018-04-06 18:02:31 -04005967 SPIRVOperandList Ops{Inst->getOperands()};
David Neto22f144c2017-06-12 14:26:21 -04005968 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5969
5970 switch (Opcode) {
5971 default: {
David Neto5c22a252018-03-15 16:07:41 -04005972 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04005973 llvm_unreachable("Unsupported SPIRV instruction");
5974 break;
5975 }
5976 case spv::OpCapability:
5977 case spv::OpExtension:
5978 case spv::OpMemoryModel:
5979 case spv::OpEntryPoint:
5980 case spv::OpExecutionMode:
5981 case spv::OpSource:
5982 case spv::OpDecorate:
5983 case spv::OpMemberDecorate:
5984 case spv::OpBranch:
5985 case spv::OpBranchConditional:
5986 case spv::OpSelectionMerge:
5987 case spv::OpLoopMerge:
5988 case spv::OpStore:
5989 case spv::OpImageWrite:
5990 case spv::OpReturnValue:
5991 case spv::OpControlBarrier:
5992 case spv::OpMemoryBarrier:
5993 case spv::OpReturn:
5994 case spv::OpFunctionEnd:
5995 case spv::OpCopyMemory: {
5996 WriteWordCountAndOpcode(Inst);
5997 for (uint32_t i = 0; i < Ops.size(); i++) {
5998 WriteOperand(Ops[i]);
5999 }
6000 break;
6001 }
6002 case spv::OpTypeBool:
6003 case spv::OpTypeVoid:
6004 case spv::OpTypeSampler:
6005 case spv::OpLabel:
6006 case spv::OpExtInstImport:
6007 case spv::OpTypePointer:
6008 case spv::OpTypeRuntimeArray:
6009 case spv::OpTypeStruct:
6010 case spv::OpTypeImage:
6011 case spv::OpTypeSampledImage:
6012 case spv::OpTypeInt:
6013 case spv::OpTypeFloat:
6014 case spv::OpTypeArray:
6015 case spv::OpTypeVector:
6016 case spv::OpTypeFunction: {
6017 WriteWordCountAndOpcode(Inst);
6018 WriteResultID(Inst);
6019 for (uint32_t i = 0; i < Ops.size(); i++) {
6020 WriteOperand(Ops[i]);
6021 }
6022 break;
6023 }
6024 case spv::OpFunction:
6025 case spv::OpFunctionParameter:
6026 case spv::OpAccessChain:
6027 case spv::OpPtrAccessChain:
6028 case spv::OpInBoundsAccessChain:
6029 case spv::OpUConvert:
6030 case spv::OpSConvert:
6031 case spv::OpConvertFToU:
6032 case spv::OpConvertFToS:
6033 case spv::OpConvertUToF:
6034 case spv::OpConvertSToF:
6035 case spv::OpFConvert:
6036 case spv::OpConvertPtrToU:
6037 case spv::OpConvertUToPtr:
6038 case spv::OpBitcast:
6039 case spv::OpIAdd:
6040 case spv::OpFAdd:
6041 case spv::OpISub:
6042 case spv::OpFSub:
6043 case spv::OpIMul:
6044 case spv::OpFMul:
6045 case spv::OpUDiv:
6046 case spv::OpSDiv:
6047 case spv::OpFDiv:
6048 case spv::OpUMod:
6049 case spv::OpSRem:
6050 case spv::OpFRem:
6051 case spv::OpBitwiseOr:
6052 case spv::OpBitwiseXor:
6053 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04006054 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04006055 case spv::OpShiftLeftLogical:
6056 case spv::OpShiftRightLogical:
6057 case spv::OpShiftRightArithmetic:
6058 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04006059 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04006060 case spv::OpCompositeExtract:
6061 case spv::OpVectorExtractDynamic:
6062 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04006063 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04006064 case spv::OpVectorInsertDynamic:
6065 case spv::OpVectorShuffle:
6066 case spv::OpIEqual:
6067 case spv::OpINotEqual:
6068 case spv::OpUGreaterThan:
6069 case spv::OpUGreaterThanEqual:
6070 case spv::OpULessThan:
6071 case spv::OpULessThanEqual:
6072 case spv::OpSGreaterThan:
6073 case spv::OpSGreaterThanEqual:
6074 case spv::OpSLessThan:
6075 case spv::OpSLessThanEqual:
6076 case spv::OpFOrdEqual:
6077 case spv::OpFOrdGreaterThan:
6078 case spv::OpFOrdGreaterThanEqual:
6079 case spv::OpFOrdLessThan:
6080 case spv::OpFOrdLessThanEqual:
6081 case spv::OpFOrdNotEqual:
6082 case spv::OpFUnordEqual:
6083 case spv::OpFUnordGreaterThan:
6084 case spv::OpFUnordGreaterThanEqual:
6085 case spv::OpFUnordLessThan:
6086 case spv::OpFUnordLessThanEqual:
6087 case spv::OpFUnordNotEqual:
6088 case spv::OpExtInst:
6089 case spv::OpIsInf:
6090 case spv::OpIsNan:
6091 case spv::OpAny:
6092 case spv::OpAll:
6093 case spv::OpUndef:
6094 case spv::OpConstantNull:
6095 case spv::OpLogicalOr:
6096 case spv::OpLogicalAnd:
6097 case spv::OpLogicalNot:
6098 case spv::OpLogicalNotEqual:
6099 case spv::OpConstantComposite:
6100 case spv::OpSpecConstantComposite:
6101 case spv::OpConstantTrue:
6102 case spv::OpConstantFalse:
6103 case spv::OpConstant:
6104 case spv::OpSpecConstant:
6105 case spv::OpVariable:
6106 case spv::OpFunctionCall:
6107 case spv::OpSampledImage:
6108 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04006109 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04006110 case spv::OpSelect:
6111 case spv::OpPhi:
6112 case spv::OpLoad:
6113 case spv::OpAtomicIAdd:
6114 case spv::OpAtomicISub:
6115 case spv::OpAtomicExchange:
6116 case spv::OpAtomicIIncrement:
6117 case spv::OpAtomicIDecrement:
6118 case spv::OpAtomicCompareExchange:
6119 case spv::OpAtomicUMin:
6120 case spv::OpAtomicSMin:
6121 case spv::OpAtomicUMax:
6122 case spv::OpAtomicSMax:
6123 case spv::OpAtomicAnd:
6124 case spv::OpAtomicOr:
6125 case spv::OpAtomicXor:
6126 case spv::OpDot: {
6127 WriteWordCountAndOpcode(Inst);
6128 WriteOperand(Ops[0]);
6129 WriteResultID(Inst);
6130 for (uint32_t i = 1; i < Ops.size(); i++) {
6131 WriteOperand(Ops[i]);
6132 }
6133 break;
6134 }
6135 }
6136 }
6137}
Alan Baker9bf93fb2018-08-28 16:59:26 -04006138
6139bool SPIRVProducerPass::IsTypeNullable(const Type* type) const {
6140 switch (type->getTypeID()) {
6141 case Type::HalfTyID:
6142 case Type::FloatTyID:
6143 case Type::DoubleTyID:
6144 case Type::IntegerTyID:
6145 case Type::VectorTyID:
6146 return true;
6147 case Type::PointerTyID: {
6148 const PointerType *pointer_type = cast<PointerType>(type);
6149 if (pointer_type->getPointerAddressSpace() !=
6150 AddressSpace::UniformConstant) {
6151 auto pointee_type = pointer_type->getPointerElementType();
6152 if (pointee_type->isStructTy() &&
6153 cast<StructType>(pointee_type)->isOpaque()) {
6154 // Images and samplers are not nullable.
6155 return false;
6156 }
6157 }
6158 return true;
6159 }
6160 case Type::ArrayTyID:
6161 return IsTypeNullable(cast<CompositeType>(type)->getTypeAtIndex(0u));
6162 case Type::StructTyID: {
6163 const StructType* struct_type = cast<StructType>(type);
6164 // Images and samplers are not nullable.
6165 if (struct_type->isOpaque()) return false;
6166 for (const auto element : struct_type->elements()) {
6167 if (!IsTypeNullable(element)) return false;
6168 }
6169 return true;
6170 }
6171 default:
6172 return false;
6173 }
6174}