blob: f07a3b8c32ccd64591bd69a8afab90dc28f7fd3f [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());
Kévin PETITa353c832018-03-20 23:21:21 +00002953 assert(arg_node->getNumOperands() == 7);
David Neto862b7d82018-06-14 18:48:37 -04002954 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();
Kévin PETITa353c832018-03-20 23:21:21 +00002963 const auto arg_size =
2964 dyn_extract<ConstantInt>(arg_node->getOperand(4))->getZExtValue();
David Neto862b7d82018-06-14 18:48:37 -04002965 const auto argKind = remap_arg_kind(
Kévin PETITa353c832018-03-20 23:21:21 +00002966 dyn_cast<MDString>(arg_node->getOperand(5))->getString());
David Neto862b7d82018-06-14 18:48:37 -04002967 const auto spec_id =
Kévin PETITa353c832018-03-20 23:21:21 +00002968 dyn_extract<ConstantInt>(arg_node->getOperand(6))->getSExtValue();
David Neto862b7d82018-06-14 18:48:37 -04002969 if (spec_id > 0) {
2970 // This was a pointer-to-local argument. It is not associated with a
2971 // resource variable.
2972 descriptorMapOut << "kernel," << F.getName() << ",arg," << name
2973 << ",argOrdinal," << old_index << ",argKind,"
2974 << argKind << ",arrayElemSize,"
2975 << DL.getTypeAllocSize(
2976 func_ty->getParamType(unsigned(new_index))
2977 ->getPointerElementType())
2978 << ",arrayNumElemSpecId," << spec_id << "\n";
2979 } else {
2980 auto *info = resource_var_at_index[new_index];
2981 assert(info);
2982 descriptorMapOut << "kernel," << F.getName() << ",arg," << name
2983 << ",argOrdinal," << old_index << ",descriptorSet,"
2984 << info->descriptor_set << ",binding," << info->binding
Kévin PETITa353c832018-03-20 23:21:21 +00002985 << ",offset," << offset << ",argKind," << argKind;
2986 if (argKind.startswith("pod")) {
2987 descriptorMapOut << ",argSize," << arg_size;
2988 }
2989 descriptorMapOut << "\n";
David Neto862b7d82018-06-14 18:48:37 -04002990 }
2991 }
2992 } else {
2993 // There is no argument map.
2994 // Take descriptor info from the resource variable calls.
Kévin PETITa353c832018-03-20 23:21:21 +00002995 // Take argument name and size from the arguments list.
David Neto862b7d82018-06-14 18:48:37 -04002996
2997 SmallVector<Argument *, 4> arguments;
2998 for (auto &arg : F.args()) {
2999 arguments.push_back(&arg);
3000 }
3001
3002 unsigned arg_index = 0;
3003 for (auto *info : resource_var_at_index) {
3004 if (info) {
Kévin PETITa353c832018-03-20 23:21:21 +00003005 auto arg = arguments[arg_index];
3006 unsigned arg_size;
3007 if (info->arg_kind == clspv::ArgKind::Pod) {
3008 arg_size = DL.getTypeStoreSize(arg->getType());
3009 }
3010
David Neto862b7d82018-06-14 18:48:37 -04003011 descriptorMapOut << "kernel," << F.getName() << ",arg,"
Kévin PETITa353c832018-03-20 23:21:21 +00003012 << arg->getName() << ",argOrdinal,"
David Neto862b7d82018-06-14 18:48:37 -04003013 << arg_index << ",descriptorSet,"
3014 << info->descriptor_set << ",binding," << info->binding
3015 << ",offset," << 0 << ",argKind,"
3016 << remap_arg_kind(
Kévin PETITa353c832018-03-20 23:21:21 +00003017 clspv::GetArgKindName(info->arg_kind));
3018 if (info->arg_kind == clspv::ArgKind::Pod) {
3019 descriptorMapOut << ",argSize," << arg_size;
3020 }
3021 descriptorMapOut << "\n";
David Neto862b7d82018-06-14 18:48:37 -04003022 }
3023 arg_index++;
3024 }
3025 // Generate mappings for pointer-to-local arguments.
3026 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
3027 Argument *arg = arguments[arg_index];
Alan Baker202c8c72018-08-13 13:47:44 -04003028 auto where = LocalArgSpecIds.find(arg);
3029 if (where != LocalArgSpecIds.end()) {
3030 auto &local_arg_info = LocalSpecIdInfoMap[where->second];
David Neto862b7d82018-06-14 18:48:37 -04003031 descriptorMapOut << "kernel," << F.getName() << ",arg,"
3032 << arg->getName() << ",argOrdinal," << arg_index
3033 << ",argKind,"
3034 << "local"
3035 << ",arrayElemSize,"
3036 << DL.getTypeAllocSize(local_arg_info.elem_type)
3037 << ",arrayNumElemSpecId," << local_arg_info.spec_id
3038 << "\n";
3039 }
3040 }
3041 }
3042}
3043
David Neto22f144c2017-06-12 14:26:21 -04003044void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
David Neto78383442018-06-15 20:31:56 -04003045 Module& M = *F.getParent();
3046 const DataLayout &DL = M.getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04003047 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3048 ValueMapType &VMap = getValueMap();
3049 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04003050 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
3051 auto &GlobalConstArgSet = getGlobalConstArgSet();
3052
3053 FunctionType *FTy = F.getFunctionType();
3054
3055 //
David Neto22f144c2017-06-12 14:26:21 -04003056 // Generate OPFunction.
3057 //
3058
3059 // FOps[0] : Result Type ID
3060 // FOps[1] : Function Control
3061 // FOps[2] : Function Type ID
3062 SPIRVOperandList FOps;
3063
3064 // Find SPIRV instruction for return type.
David Neto257c3892018-04-11 13:19:45 -04003065 FOps << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04003066
3067 // Check function attributes for SPIRV Function Control.
3068 uint32_t FuncControl = spv::FunctionControlMaskNone;
3069 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
3070 FuncControl |= spv::FunctionControlInlineMask;
3071 }
3072 if (F.hasFnAttribute(Attribute::NoInline)) {
3073 FuncControl |= spv::FunctionControlDontInlineMask;
3074 }
3075 // TODO: Check llvm attribute for Function Control Pure.
3076 if (F.hasFnAttribute(Attribute::ReadOnly)) {
3077 FuncControl |= spv::FunctionControlPureMask;
3078 }
3079 // TODO: Check llvm attribute for Function Control Const.
3080 if (F.hasFnAttribute(Attribute::ReadNone)) {
3081 FuncControl |= spv::FunctionControlConstMask;
3082 }
3083
David Neto257c3892018-04-11 13:19:45 -04003084 FOps << MkNum(FuncControl);
David Neto22f144c2017-06-12 14:26:21 -04003085
3086 uint32_t FTyID;
3087 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3088 SmallVector<Type *, 4> NewFuncParamTys;
3089 FunctionType *NewFTy =
3090 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
3091 FTyID = lookupType(NewFTy);
3092 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07003093 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04003094 if (GlobalConstFuncTyMap.count(FTy)) {
3095 FTyID = lookupType(GlobalConstFuncTyMap[FTy].first);
3096 } else {
3097 FTyID = lookupType(FTy);
3098 }
3099 }
3100
David Neto257c3892018-04-11 13:19:45 -04003101 FOps << MkId(FTyID);
David Neto22f144c2017-06-12 14:26:21 -04003102
3103 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3104 EntryPoints.push_back(std::make_pair(&F, nextID));
3105 }
3106
3107 VMap[&F] = nextID;
3108
David Neto482550a2018-03-24 05:21:07 -07003109 if (clspv::Option::ShowIDs()) {
David Netob05675d2018-02-16 12:37:49 -05003110 errs() << "Function " << F.getName() << " is " << nextID << "\n";
3111 }
David Neto22f144c2017-06-12 14:26:21 -04003112 // Generate SPIRV instruction for function.
David Neto87846742018-04-11 17:36:22 -04003113 auto *FuncInst = new SPIRVInstruction(spv::OpFunction, nextID++, FOps);
David Neto22f144c2017-06-12 14:26:21 -04003114 SPIRVInstList.push_back(FuncInst);
3115
3116 //
3117 // Generate OpFunctionParameter for Normal function.
3118 //
3119
3120 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3121 // Iterate Argument for name instead of param type from function type.
3122 unsigned ArgIdx = 0;
3123 for (Argument &Arg : F.args()) {
3124 VMap[&Arg] = nextID;
3125
3126 // ParamOps[0] : Result Type ID
3127 SPIRVOperandList ParamOps;
3128
3129 // Find SPIRV instruction for parameter type.
3130 uint32_t ParamTyID = lookupType(Arg.getType());
3131 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
3132 if (GlobalConstFuncTyMap.count(FTy)) {
3133 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
3134 Type *EleTy = PTy->getPointerElementType();
3135 Type *ArgTy =
3136 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
3137 ParamTyID = lookupType(ArgTy);
3138 GlobalConstArgSet.insert(&Arg);
3139 }
3140 }
3141 }
David Neto257c3892018-04-11 13:19:45 -04003142 ParamOps << MkId(ParamTyID);
David Neto22f144c2017-06-12 14:26:21 -04003143
3144 // Generate SPIRV instruction for parameter.
David Neto87846742018-04-11 17:36:22 -04003145 auto *ParamInst =
3146 new SPIRVInstruction(spv::OpFunctionParameter, nextID++, ParamOps);
David Neto22f144c2017-06-12 14:26:21 -04003147 SPIRVInstList.push_back(ParamInst);
3148
3149 ArgIdx++;
3150 }
3151 }
3152}
3153
David Neto5c22a252018-03-15 16:07:41 -04003154void SPIRVProducerPass::GenerateModuleInfo(Module& module) {
David Neto22f144c2017-06-12 14:26:21 -04003155 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3156 EntryPointVecType &EntryPoints = getEntryPointVec();
3157 ValueMapType &VMap = getValueMap();
3158 ValueList &EntryPointInterfaces = getEntryPointInterfacesVec();
3159 uint32_t &ExtInstImportID = getOpExtInstImportID();
3160 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
3161
3162 // Set up insert point.
3163 auto InsertPoint = SPIRVInstList.begin();
3164
3165 //
3166 // Generate OpCapability
3167 //
3168 // TODO: Which llvm information is mapped to SPIRV Capapbility?
3169
3170 // Ops[0] = Capability
3171 SPIRVOperandList Ops;
3172
David Neto87846742018-04-11 17:36:22 -04003173 auto *CapInst =
3174 new SPIRVInstruction(spv::OpCapability, {MkNum(spv::CapabilityShader)});
David Neto22f144c2017-06-12 14:26:21 -04003175 SPIRVInstList.insert(InsertPoint, CapInst);
3176
3177 for (Type *Ty : getTypeList()) {
3178 // Find the i16 type.
3179 if (Ty->isIntegerTy(16)) {
3180 // Generate OpCapability for i16 type.
David Neto87846742018-04-11 17:36:22 -04003181 SPIRVInstList.insert(InsertPoint,
3182 new SPIRVInstruction(spv::OpCapability,
3183 {MkNum(spv::CapabilityInt16)}));
David Neto22f144c2017-06-12 14:26:21 -04003184 } else if (Ty->isIntegerTy(64)) {
3185 // Generate OpCapability for i64 type.
David Neto87846742018-04-11 17:36:22 -04003186 SPIRVInstList.insert(InsertPoint,
3187 new SPIRVInstruction(spv::OpCapability,
3188 {MkNum(spv::CapabilityInt64)}));
David Neto22f144c2017-06-12 14:26:21 -04003189 } else if (Ty->isHalfTy()) {
3190 // Generate OpCapability for half type.
3191 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003192 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3193 {MkNum(spv::CapabilityFloat16)}));
David Neto22f144c2017-06-12 14:26:21 -04003194 } else if (Ty->isDoubleTy()) {
3195 // Generate OpCapability for double type.
3196 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003197 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3198 {MkNum(spv::CapabilityFloat64)}));
David Neto22f144c2017-06-12 14:26:21 -04003199 } else if (auto *STy = dyn_cast<StructType>(Ty)) {
3200 if (STy->isOpaque()) {
David Neto565571c2017-08-21 12:00:05 -04003201 if (STy->getName().equals("opencl.image2d_wo_t") ||
3202 STy->getName().equals("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04003203 // Generate OpCapability for write only image type.
3204 SPIRVInstList.insert(
3205 InsertPoint,
3206 new SPIRVInstruction(
David Neto87846742018-04-11 17:36:22 -04003207 spv::OpCapability,
3208 {MkNum(spv::CapabilityStorageImageWriteWithoutFormat)}));
David Neto22f144c2017-06-12 14:26:21 -04003209 }
3210 }
3211 }
3212 }
3213
David Neto5c22a252018-03-15 16:07:41 -04003214 { // OpCapability ImageQuery
3215 bool hasImageQuery = false;
3216 for (const char *imageQuery : {
3217 "_Z15get_image_width14ocl_image2d_ro",
3218 "_Z15get_image_width14ocl_image2d_wo",
3219 "_Z16get_image_height14ocl_image2d_ro",
3220 "_Z16get_image_height14ocl_image2d_wo",
3221 }) {
3222 if (module.getFunction(imageQuery)) {
3223 hasImageQuery = true;
3224 break;
3225 }
3226 }
3227 if (hasImageQuery) {
David Neto87846742018-04-11 17:36:22 -04003228 auto *ImageQueryCapInst = new SPIRVInstruction(
3229 spv::OpCapability, {MkNum(spv::CapabilityImageQuery)});
David Neto5c22a252018-03-15 16:07:41 -04003230 SPIRVInstList.insert(InsertPoint, ImageQueryCapInst);
3231 }
3232 }
3233
David Neto22f144c2017-06-12 14:26:21 -04003234 if (hasVariablePointers()) {
3235 //
3236 // Generate OpCapability and OpExtension
3237 //
3238
3239 //
3240 // Generate OpCapability.
3241 //
3242 // Ops[0] = Capability
3243 //
3244 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003245 Ops << MkNum(spv::CapabilityVariablePointers);
David Neto22f144c2017-06-12 14:26:21 -04003246
David Neto87846742018-04-11 17:36:22 -04003247 SPIRVInstList.insert(InsertPoint,
3248 new SPIRVInstruction(spv::OpCapability, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003249
3250 //
3251 // Generate OpExtension.
3252 //
3253 // Ops[0] = Name (Literal String)
3254 //
David Netoa772fd12017-08-04 14:17:33 -04003255 for (auto extension : {"SPV_KHR_storage_buffer_storage_class",
3256 "SPV_KHR_variable_pointers"}) {
David Neto22f144c2017-06-12 14:26:21 -04003257
David Neto87846742018-04-11 17:36:22 -04003258 auto *ExtensionInst =
3259 new SPIRVInstruction(spv::OpExtension, {MkString(extension)});
David Netoa772fd12017-08-04 14:17:33 -04003260 SPIRVInstList.insert(InsertPoint, ExtensionInst);
David Neto22f144c2017-06-12 14:26:21 -04003261 }
David Neto22f144c2017-06-12 14:26:21 -04003262 }
3263
3264 if (ExtInstImportID) {
3265 ++InsertPoint;
3266 }
3267
3268 //
3269 // Generate OpMemoryModel
3270 //
3271 // Memory model for Vulkan will always be GLSL450.
3272
3273 // Ops[0] = Addressing Model
3274 // Ops[1] = Memory Model
3275 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003276 Ops << MkNum(spv::AddressingModelLogical) << MkNum(spv::MemoryModelGLSL450);
David Neto22f144c2017-06-12 14:26:21 -04003277
David Neto87846742018-04-11 17:36:22 -04003278 auto *MemModelInst = new SPIRVInstruction(spv::OpMemoryModel, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003279 SPIRVInstList.insert(InsertPoint, MemModelInst);
3280
3281 //
3282 // Generate OpEntryPoint
3283 //
3284 for (auto EntryPoint : EntryPoints) {
3285 // Ops[0] = Execution Model
3286 // Ops[1] = EntryPoint ID
3287 // Ops[2] = Name (Literal String)
3288 // ...
3289 //
3290 // TODO: Do we need to consider Interface ID for forward references???
3291 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003292 const StringRef& name = EntryPoint.first->getName();
3293 Ops << MkNum(spv::ExecutionModelGLCompute) << MkId(EntryPoint.second)
3294 << MkString(name);
David Neto22f144c2017-06-12 14:26:21 -04003295
David Neto22f144c2017-06-12 14:26:21 -04003296 for (Value *Interface : EntryPointInterfaces) {
David Neto257c3892018-04-11 13:19:45 -04003297 Ops << MkId(VMap[Interface]);
David Neto22f144c2017-06-12 14:26:21 -04003298 }
3299
David Neto87846742018-04-11 17:36:22 -04003300 auto *EntryPointInst = new SPIRVInstruction(spv::OpEntryPoint, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003301 SPIRVInstList.insert(InsertPoint, EntryPointInst);
3302 }
3303
3304 for (auto EntryPoint : EntryPoints) {
3305 if (const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
3306 ->getMetadata("reqd_work_group_size")) {
3307
3308 if (!BuiltinDimVec.empty()) {
3309 llvm_unreachable(
3310 "Kernels should have consistent work group size definition");
3311 }
3312
3313 //
3314 // Generate OpExecutionMode
3315 //
3316
3317 // Ops[0] = Entry Point ID
3318 // Ops[1] = Execution Mode
3319 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
3320 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003321 Ops << MkId(EntryPoint.second)
3322 << MkNum(spv::ExecutionModeLocalSize);
David Neto22f144c2017-06-12 14:26:21 -04003323
3324 uint32_t XDim = static_cast<uint32_t>(
3325 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3326 uint32_t YDim = static_cast<uint32_t>(
3327 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3328 uint32_t ZDim = static_cast<uint32_t>(
3329 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3330
David Neto257c3892018-04-11 13:19:45 -04003331 Ops << MkNum(XDim) << MkNum(YDim) << MkNum(ZDim);
David Neto22f144c2017-06-12 14:26:21 -04003332
David Neto87846742018-04-11 17:36:22 -04003333 auto *ExecModeInst = new SPIRVInstruction(spv::OpExecutionMode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003334 SPIRVInstList.insert(InsertPoint, ExecModeInst);
3335 }
3336 }
3337
3338 //
3339 // Generate OpSource.
3340 //
3341 // Ops[0] = SourceLanguage ID
3342 // Ops[1] = Version (LiteralNum)
3343 //
3344 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003345 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(120);
David Neto22f144c2017-06-12 14:26:21 -04003346
David Neto87846742018-04-11 17:36:22 -04003347 auto *OpenSourceInst = new SPIRVInstruction(spv::OpSource, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003348 SPIRVInstList.insert(InsertPoint, OpenSourceInst);
3349
3350 if (!BuiltinDimVec.empty()) {
3351 //
3352 // Generate OpDecorates for x/y/z dimension.
3353 //
3354 // Ops[0] = Target ID
3355 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04003356 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04003357
3358 // X Dimension
3359 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003360 Ops << MkId(BuiltinDimVec[0]) << MkNum(spv::DecorationSpecId) << MkNum(0);
David Neto87846742018-04-11 17:36:22 -04003361 SPIRVInstList.insert(InsertPoint,
3362 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003363
3364 // Y Dimension
3365 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003366 Ops << MkId(BuiltinDimVec[1]) << MkNum(spv::DecorationSpecId) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04003367 SPIRVInstList.insert(InsertPoint,
3368 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003369
3370 // Z Dimension
3371 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003372 Ops << MkId(BuiltinDimVec[2]) << MkNum(spv::DecorationSpecId) << MkNum(2);
David Neto87846742018-04-11 17:36:22 -04003373 SPIRVInstList.insert(InsertPoint,
3374 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003375 }
3376}
3377
David Netob6e2e062018-04-25 10:32:06 -04003378void SPIRVProducerPass::GenerateEntryPointInitialStores() {
3379 // Work around a driver bug. Initializers on Private variables might not
3380 // work. So the start of the kernel should store the initializer value to the
3381 // variables. Yes, *every* entry point pays this cost if *any* entry point
3382 // uses this builtin. At this point I judge this to be an acceptable tradeoff
3383 // of complexity vs. runtime, for a broken driver.
3384 // TODO(dneto): Remove this at some point once fixed drivers are widely available.
3385 if (WorkgroupSizeVarID) {
3386 assert(WorkgroupSizeValueID);
3387
3388 SPIRVOperandList Ops;
3389 Ops << MkId(WorkgroupSizeVarID) << MkId(WorkgroupSizeValueID);
3390
3391 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
3392 getSPIRVInstList().push_back(Inst);
3393 }
3394}
3395
David Neto22f144c2017-06-12 14:26:21 -04003396void SPIRVProducerPass::GenerateFuncBody(Function &F) {
3397 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3398 ValueMapType &VMap = getValueMap();
3399
David Netob6e2e062018-04-25 10:32:06 -04003400 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04003401
3402 for (BasicBlock &BB : F) {
3403 // Register BasicBlock to ValueMap.
3404 VMap[&BB] = nextID;
3405
3406 //
3407 // Generate OpLabel for Basic Block.
3408 //
3409 SPIRVOperandList Ops;
David Neto87846742018-04-11 17:36:22 -04003410 auto *Inst = new SPIRVInstruction(spv::OpLabel, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003411 SPIRVInstList.push_back(Inst);
3412
David Neto6dcd4712017-06-23 11:06:47 -04003413 // OpVariable instructions must come first.
3414 for (Instruction &I : BB) {
3415 if (isa<AllocaInst>(I)) {
3416 GenerateInstruction(I);
3417 }
3418 }
3419
David Neto22f144c2017-06-12 14:26:21 -04003420 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04003421 if (clspv::Option::HackInitializers()) {
3422 GenerateEntryPointInitialStores();
3423 }
David Neto22f144c2017-06-12 14:26:21 -04003424 }
3425
3426 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003427 if (!isa<AllocaInst>(I)) {
3428 GenerateInstruction(I);
3429 }
David Neto22f144c2017-06-12 14:26:21 -04003430 }
3431 }
3432}
3433
3434spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3435 const std::map<CmpInst::Predicate, spv::Op> Map = {
3436 {CmpInst::ICMP_EQ, spv::OpIEqual},
3437 {CmpInst::ICMP_NE, spv::OpINotEqual},
3438 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3439 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3440 {CmpInst::ICMP_ULT, spv::OpULessThan},
3441 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3442 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3443 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3444 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3445 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3446 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3447 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3448 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3449 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3450 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3451 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3452 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3453 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3454 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3455 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3456 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3457 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3458
3459 assert(0 != Map.count(I->getPredicate()));
3460
3461 return Map.at(I->getPredicate());
3462}
3463
3464spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3465 const std::map<unsigned, spv::Op> Map{
3466 {Instruction::Trunc, spv::OpUConvert},
3467 {Instruction::ZExt, spv::OpUConvert},
3468 {Instruction::SExt, spv::OpSConvert},
3469 {Instruction::FPToUI, spv::OpConvertFToU},
3470 {Instruction::FPToSI, spv::OpConvertFToS},
3471 {Instruction::UIToFP, spv::OpConvertUToF},
3472 {Instruction::SIToFP, spv::OpConvertSToF},
3473 {Instruction::FPTrunc, spv::OpFConvert},
3474 {Instruction::FPExt, spv::OpFConvert},
3475 {Instruction::BitCast, spv::OpBitcast}};
3476
3477 assert(0 != Map.count(I.getOpcode()));
3478
3479 return Map.at(I.getOpcode());
3480}
3481
3482spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
3483 if (I.getType()->isIntegerTy(1)) {
3484 switch (I.getOpcode()) {
3485 default:
3486 break;
3487 case Instruction::Or:
3488 return spv::OpLogicalOr;
3489 case Instruction::And:
3490 return spv::OpLogicalAnd;
3491 case Instruction::Xor:
3492 return spv::OpLogicalNotEqual;
3493 }
3494 }
3495
3496 const std::map<unsigned, spv::Op> Map {
3497 {Instruction::Add, spv::OpIAdd},
3498 {Instruction::FAdd, spv::OpFAdd},
3499 {Instruction::Sub, spv::OpISub},
3500 {Instruction::FSub, spv::OpFSub},
3501 {Instruction::Mul, spv::OpIMul},
3502 {Instruction::FMul, spv::OpFMul},
3503 {Instruction::UDiv, spv::OpUDiv},
3504 {Instruction::SDiv, spv::OpSDiv},
3505 {Instruction::FDiv, spv::OpFDiv},
3506 {Instruction::URem, spv::OpUMod},
3507 {Instruction::SRem, spv::OpSRem},
3508 {Instruction::FRem, spv::OpFRem},
3509 {Instruction::Or, spv::OpBitwiseOr},
3510 {Instruction::Xor, spv::OpBitwiseXor},
3511 {Instruction::And, spv::OpBitwiseAnd},
3512 {Instruction::Shl, spv::OpShiftLeftLogical},
3513 {Instruction::LShr, spv::OpShiftRightLogical},
3514 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3515
3516 assert(0 != Map.count(I.getOpcode()));
3517
3518 return Map.at(I.getOpcode());
3519}
3520
3521void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
3522 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3523 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04003524 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
3525 LLVMContext &Context = I.getParent()->getParent()->getParent()->getContext();
3526
3527 // Register Instruction to ValueMap.
3528 if (0 == VMap[&I]) {
3529 VMap[&I] = nextID;
3530 }
3531
3532 switch (I.getOpcode()) {
3533 default: {
3534 if (Instruction::isCast(I.getOpcode())) {
3535 //
3536 // Generate SPIRV instructions for cast operators.
3537 //
3538
David Netod2de94a2017-08-28 17:27:47 -04003539
3540 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003541 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003542 auto toI8 = Ty == Type::getInt8Ty(Context);
3543 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003544 // Handle zext, sext and uitofp with i1 type specially.
3545 if ((I.getOpcode() == Instruction::ZExt ||
3546 I.getOpcode() == Instruction::SExt ||
3547 I.getOpcode() == Instruction::UIToFP) &&
3548 (OpTy->isIntegerTy(1) ||
3549 (OpTy->isVectorTy() &&
3550 OpTy->getVectorElementType()->isIntegerTy(1)))) {
3551 //
3552 // Generate OpSelect.
3553 //
3554
3555 // Ops[0] = Result Type ID
3556 // Ops[1] = Condition ID
3557 // Ops[2] = True Constant ID
3558 // Ops[3] = False Constant ID
3559 SPIRVOperandList Ops;
3560
David Neto257c3892018-04-11 13:19:45 -04003561 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003562
David Neto22f144c2017-06-12 14:26:21 -04003563 uint32_t CondID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003564 Ops << MkId(CondID);
David Neto22f144c2017-06-12 14:26:21 -04003565
3566 uint32_t TrueID = 0;
3567 if (I.getOpcode() == Instruction::ZExt) {
3568 APInt One(32, 1);
3569 TrueID = VMap[Constant::getIntegerValue(I.getType(), One)];
3570 } else if (I.getOpcode() == Instruction::SExt) {
3571 APInt MinusOne(32, UINT64_MAX, true);
3572 TrueID = VMap[Constant::getIntegerValue(I.getType(), MinusOne)];
3573 } else {
3574 TrueID = VMap[ConstantFP::get(Context, APFloat(1.0f))];
3575 }
David Neto257c3892018-04-11 13:19:45 -04003576 Ops << MkId(TrueID);
David Neto22f144c2017-06-12 14:26:21 -04003577
3578 uint32_t FalseID = 0;
3579 if (I.getOpcode() == Instruction::ZExt) {
3580 FalseID = VMap[Constant::getNullValue(I.getType())];
3581 } else if (I.getOpcode() == Instruction::SExt) {
3582 FalseID = VMap[Constant::getNullValue(I.getType())];
3583 } else {
3584 FalseID = VMap[ConstantFP::get(Context, APFloat(0.0f))];
3585 }
David Neto257c3892018-04-11 13:19:45 -04003586 Ops << MkId(FalseID);
David Neto22f144c2017-06-12 14:26:21 -04003587
David Neto87846742018-04-11 17:36:22 -04003588 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003589 SPIRVInstList.push_back(Inst);
David Netod2de94a2017-08-28 17:27:47 -04003590 } else if (I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
3591 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3592 // 8 bits.
3593 // Before:
3594 // %result = trunc i32 %a to i8
3595 // After
3596 // %result = OpBitwiseAnd %uint %a %uint_255
3597
3598 SPIRVOperandList Ops;
3599
David Neto257c3892018-04-11 13:19:45 -04003600 Ops << MkId(lookupType(OpTy)) << MkId(VMap[I.getOperand(0)]);
David Netod2de94a2017-08-28 17:27:47 -04003601
3602 Type *UintTy = Type::getInt32Ty(Context);
3603 uint32_t MaskID = VMap[ConstantInt::get(UintTy, 255)];
David Neto257c3892018-04-11 13:19:45 -04003604 Ops << MkId(MaskID);
David Netod2de94a2017-08-28 17:27:47 -04003605
David Neto87846742018-04-11 17:36:22 -04003606 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Netod2de94a2017-08-28 17:27:47 -04003607 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003608 } else {
3609 // Ops[0] = Result Type ID
3610 // Ops[1] = Source Value ID
3611 SPIRVOperandList Ops;
3612
David Neto257c3892018-04-11 13:19:45 -04003613 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003614
David Neto87846742018-04-11 17:36:22 -04003615 auto *Inst = new SPIRVInstruction(GetSPIRVCastOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003616 SPIRVInstList.push_back(Inst);
3617 }
3618 } else if (isa<BinaryOperator>(I)) {
3619 //
3620 // Generate SPIRV instructions for binary operators.
3621 //
3622
3623 // Handle xor with i1 type specially.
3624 if (I.getOpcode() == Instruction::Xor &&
3625 I.getType() == Type::getInt1Ty(Context) &&
3626 (isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
3627 //
3628 // Generate OpLogicalNot.
3629 //
3630 // Ops[0] = Result Type ID
3631 // Ops[1] = Operand
3632 SPIRVOperandList Ops;
3633
David Neto257c3892018-04-11 13:19:45 -04003634 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003635
3636 Value *CondV = I.getOperand(0);
3637 if (isa<Constant>(I.getOperand(0))) {
3638 CondV = I.getOperand(1);
3639 }
David Neto257c3892018-04-11 13:19:45 -04003640 Ops << MkId(VMap[CondV]);
David Neto22f144c2017-06-12 14:26:21 -04003641
David Neto87846742018-04-11 17:36:22 -04003642 auto *Inst = new SPIRVInstruction(spv::OpLogicalNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003643 SPIRVInstList.push_back(Inst);
3644 } else {
3645 // Ops[0] = Result Type ID
3646 // Ops[1] = Operand 0
3647 // Ops[2] = Operand 1
3648 SPIRVOperandList Ops;
3649
David Neto257c3892018-04-11 13:19:45 -04003650 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
3651 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003652
David Neto87846742018-04-11 17:36:22 -04003653 auto *Inst =
3654 new SPIRVInstruction(GetSPIRVBinaryOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003655 SPIRVInstList.push_back(Inst);
3656 }
3657 } else {
3658 I.print(errs());
3659 llvm_unreachable("Unsupported instruction???");
3660 }
3661 break;
3662 }
3663 case Instruction::GetElementPtr: {
3664 auto &GlobalConstArgSet = getGlobalConstArgSet();
3665
3666 //
3667 // Generate OpAccessChain.
3668 //
3669 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
3670
3671 //
3672 // Generate OpAccessChain.
3673 //
3674
3675 // Ops[0] = Result Type ID
3676 // Ops[1] = Base ID
3677 // Ops[2] ... Ops[n] = Indexes ID
3678 SPIRVOperandList Ops;
3679
David Neto1a1a0582017-07-07 12:01:44 -04003680 PointerType* ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04003681 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
3682 GlobalConstArgSet.count(GEP->getPointerOperand())) {
3683 // Use pointer type with private address space for global constant.
3684 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04003685 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04003686 }
David Neto257c3892018-04-11 13:19:45 -04003687
3688 Ops << MkId(lookupType(ResultType));
David Neto22f144c2017-06-12 14:26:21 -04003689
David Neto862b7d82018-06-14 18:48:37 -04003690 // Generate the base pointer.
3691 Ops << MkId(VMap[GEP->getPointerOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04003692
David Neto862b7d82018-06-14 18:48:37 -04003693 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04003694
3695 //
3696 // Follows below rules for gep.
3697 //
David Neto862b7d82018-06-14 18:48:37 -04003698 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
3699 // first index.
David Neto22f144c2017-06-12 14:26:21 -04003700 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
3701 // first index.
3702 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
3703 // use gep's first index.
3704 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
3705 // gep's first index.
3706 //
3707 spv::Op Opcode = spv::OpAccessChain;
3708 unsigned offset = 0;
3709 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04003710 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04003711 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04003712 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04003713 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04003714 }
David Neto862b7d82018-06-14 18:48:37 -04003715 } else {
David Neto22f144c2017-06-12 14:26:21 -04003716 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04003717 }
3718
3719 if (Opcode == spv::OpPtrAccessChain) {
David Neto22f144c2017-06-12 14:26:21 -04003720 setVariablePointers(true);
David Neto1a1a0582017-07-07 12:01:44 -04003721 // Do we need to generate ArrayStride? Check against the GEP result type
3722 // rather than the pointer type of the base because when indexing into
3723 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
3724 // for something else in the SPIR-V.
3725 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
3726 if (GetStorageClass(ResultType->getAddressSpace()) ==
3727 spv::StorageClassStorageBuffer) {
3728 // Save the need to generate an ArrayStride decoration. But defer
3729 // generation until later, so we only make one decoration.
David Neto85082642018-03-24 06:55:20 -07003730 getTypesNeedingArrayStride().insert(ResultType);
David Neto1a1a0582017-07-07 12:01:44 -04003731 }
David Neto22f144c2017-06-12 14:26:21 -04003732 }
3733
3734 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
David Neto257c3892018-04-11 13:19:45 -04003735 Ops << MkId(VMap[*II]);
David Neto22f144c2017-06-12 14:26:21 -04003736 }
3737
David Neto87846742018-04-11 17:36:22 -04003738 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003739 SPIRVInstList.push_back(Inst);
3740 break;
3741 }
3742 case Instruction::ExtractValue: {
3743 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3744 // Ops[0] = Result Type ID
3745 // Ops[1] = Composite ID
3746 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3747 SPIRVOperandList Ops;
3748
David Neto257c3892018-04-11 13:19:45 -04003749 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003750
3751 uint32_t CompositeID = VMap[EVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003752 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003753
3754 for (auto &Index : EVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003755 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003756 }
3757
David Neto87846742018-04-11 17:36:22 -04003758 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003759 SPIRVInstList.push_back(Inst);
3760 break;
3761 }
3762 case Instruction::InsertValue: {
3763 InsertValueInst *IVI = cast<InsertValueInst>(&I);
3764 // Ops[0] = Result Type ID
3765 // Ops[1] = Object ID
3766 // Ops[2] = Composite ID
3767 // Ops[3] ... Ops[n] = Indexes (Literal Number)
3768 SPIRVOperandList Ops;
3769
3770 uint32_t ResTyID = lookupType(I.getType());
David Neto257c3892018-04-11 13:19:45 -04003771 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04003772
3773 uint32_t ObjectID = VMap[IVI->getInsertedValueOperand()];
David Neto257c3892018-04-11 13:19:45 -04003774 Ops << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04003775
3776 uint32_t CompositeID = VMap[IVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003777 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003778
3779 for (auto &Index : IVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003780 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003781 }
3782
David Neto87846742018-04-11 17:36:22 -04003783 auto *Inst = new SPIRVInstruction(spv::OpCompositeInsert, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003784 SPIRVInstList.push_back(Inst);
3785 break;
3786 }
3787 case Instruction::Select: {
3788 //
3789 // Generate OpSelect.
3790 //
3791
3792 // Ops[0] = Result Type ID
3793 // Ops[1] = Condition ID
3794 // Ops[2] = True Constant ID
3795 // Ops[3] = False Constant ID
3796 SPIRVOperandList Ops;
3797
3798 // Find SPIRV instruction for parameter type.
3799 auto Ty = I.getType();
3800 if (Ty->isPointerTy()) {
3801 auto PointeeTy = Ty->getPointerElementType();
3802 if (PointeeTy->isStructTy() &&
3803 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
3804 Ty = PointeeTy;
3805 }
3806 }
3807
David Neto257c3892018-04-11 13:19:45 -04003808 Ops << MkId(lookupType(Ty)) << MkId(VMap[I.getOperand(0)])
3809 << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003810
David Neto87846742018-04-11 17:36:22 -04003811 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003812 SPIRVInstList.push_back(Inst);
3813 break;
3814 }
3815 case Instruction::ExtractElement: {
3816 // Handle <4 x i8> type manually.
3817 Type *CompositeTy = I.getOperand(0)->getType();
3818 if (is4xi8vec(CompositeTy)) {
3819 //
3820 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
3821 // <4 x i8>.
3822 //
3823
3824 //
3825 // Generate OpShiftRightLogical
3826 //
3827 // Ops[0] = Result Type ID
3828 // Ops[1] = Operand 0
3829 // Ops[2] = Operand 1
3830 //
3831 SPIRVOperandList Ops;
3832
David Neto257c3892018-04-11 13:19:45 -04003833 Ops << MkId(lookupType(CompositeTy));
David Neto22f144c2017-06-12 14:26:21 -04003834
3835 uint32_t Op0ID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003836 Ops << MkId(Op0ID);
David Neto22f144c2017-06-12 14:26:21 -04003837
3838 uint32_t Op1ID = 0;
3839 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
3840 // Handle constant index.
3841 uint64_t Idx = CI->getZExtValue();
3842 Value *ShiftAmount =
3843 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3844 Op1ID = VMap[ShiftAmount];
3845 } else {
3846 // Handle variable index.
3847 SPIRVOperandList TmpOps;
3848
David Neto257c3892018-04-11 13:19:45 -04003849 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3850 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003851
3852 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003853 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003854
3855 Op1ID = nextID;
3856
David Neto87846742018-04-11 17:36:22 -04003857 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003858 SPIRVInstList.push_back(TmpInst);
3859 }
David Neto257c3892018-04-11 13:19:45 -04003860 Ops << MkId(Op1ID);
David Neto22f144c2017-06-12 14:26:21 -04003861
3862 uint32_t ShiftID = nextID;
3863
David Neto87846742018-04-11 17:36:22 -04003864 auto *Inst =
3865 new SPIRVInstruction(spv::OpShiftRightLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003866 SPIRVInstList.push_back(Inst);
3867
3868 //
3869 // Generate OpBitwiseAnd
3870 //
3871 // Ops[0] = Result Type ID
3872 // Ops[1] = Operand 0
3873 // Ops[2] = Operand 1
3874 //
3875 Ops.clear();
3876
David Neto257c3892018-04-11 13:19:45 -04003877 Ops << MkId(lookupType(CompositeTy)) << MkId(ShiftID);
David Neto22f144c2017-06-12 14:26:21 -04003878
3879 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
David Neto257c3892018-04-11 13:19:45 -04003880 Ops << MkId(VMap[CstFF]);
David Neto22f144c2017-06-12 14:26:21 -04003881
David Neto9b2d6252017-09-06 15:47:37 -04003882 // Reset mapping for this value to the result of the bitwise and.
3883 VMap[&I] = nextID;
3884
David Neto87846742018-04-11 17:36:22 -04003885 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003886 SPIRVInstList.push_back(Inst);
3887 break;
3888 }
3889
3890 // Ops[0] = Result Type ID
3891 // Ops[1] = Composite ID
3892 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3893 SPIRVOperandList Ops;
3894
David Neto257c3892018-04-11 13:19:45 -04003895 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003896
3897 spv::Op Opcode = spv::OpCompositeExtract;
3898 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
David Neto257c3892018-04-11 13:19:45 -04003899 Ops << MkNum(static_cast<uint32_t>(CI->getZExtValue()));
David Neto22f144c2017-06-12 14:26:21 -04003900 } else {
David Neto257c3892018-04-11 13:19:45 -04003901 Ops << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003902 Opcode = spv::OpVectorExtractDynamic;
3903 }
3904
David Neto87846742018-04-11 17:36:22 -04003905 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003906 SPIRVInstList.push_back(Inst);
3907 break;
3908 }
3909 case Instruction::InsertElement: {
3910 // Handle <4 x i8> type manually.
3911 Type *CompositeTy = I.getOperand(0)->getType();
3912 if (is4xi8vec(CompositeTy)) {
3913 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
3914 uint32_t CstFFID = VMap[CstFF];
3915
3916 uint32_t ShiftAmountID = 0;
3917 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
3918 // Handle constant index.
3919 uint64_t Idx = CI->getZExtValue();
3920 Value *ShiftAmount =
3921 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3922 ShiftAmountID = VMap[ShiftAmount];
3923 } else {
3924 // Handle variable index.
3925 SPIRVOperandList TmpOps;
3926
David Neto257c3892018-04-11 13:19:45 -04003927 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3928 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003929
3930 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003931 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003932
3933 ShiftAmountID = nextID;
3934
David Neto87846742018-04-11 17:36:22 -04003935 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003936 SPIRVInstList.push_back(TmpInst);
3937 }
3938
3939 //
3940 // Generate mask operations.
3941 //
3942
3943 // ShiftLeft mask according to index of insertelement.
3944 SPIRVOperandList Ops;
3945
David Neto257c3892018-04-11 13:19:45 -04003946 const uint32_t ResTyID = lookupType(CompositeTy);
3947 Ops << MkId(ResTyID) << MkId(CstFFID) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04003948
3949 uint32_t MaskID = nextID;
3950
David Neto87846742018-04-11 17:36:22 -04003951 auto *Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003952 SPIRVInstList.push_back(Inst);
3953
3954 // Inverse mask.
3955 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003956 Ops << MkId(ResTyID) << MkId(MaskID);
David Neto22f144c2017-06-12 14:26:21 -04003957
3958 uint32_t InvMaskID = nextID;
3959
David Neto87846742018-04-11 17:36:22 -04003960 Inst = new SPIRVInstruction(spv::OpNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003961 SPIRVInstList.push_back(Inst);
3962
3963 // Apply mask.
3964 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003965 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(0)]) << MkId(InvMaskID);
David Neto22f144c2017-06-12 14:26:21 -04003966
3967 uint32_t OrgValID = nextID;
3968
David Neto87846742018-04-11 17:36:22 -04003969 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003970 SPIRVInstList.push_back(Inst);
3971
3972 // Create correct value according to index of insertelement.
3973 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003974 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(1)]) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04003975
3976 uint32_t InsertValID = nextID;
3977
David Neto87846742018-04-11 17:36:22 -04003978 Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003979 SPIRVInstList.push_back(Inst);
3980
3981 // Insert value to original value.
3982 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003983 Ops << MkId(ResTyID) << MkId(OrgValID) << MkId(InsertValID);
David Neto22f144c2017-06-12 14:26:21 -04003984
David Netoa394f392017-08-26 20:45:29 -04003985 VMap[&I] = nextID;
3986
David Neto87846742018-04-11 17:36:22 -04003987 Inst = new SPIRVInstruction(spv::OpBitwiseOr, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003988 SPIRVInstList.push_back(Inst);
3989
3990 break;
3991 }
3992
David Neto22f144c2017-06-12 14:26:21 -04003993 SPIRVOperandList Ops;
3994
James Priced26efea2018-06-09 23:28:32 +01003995 // Ops[0] = Result Type ID
3996 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003997
3998 spv::Op Opcode = spv::OpCompositeInsert;
3999 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04004000 const auto value = CI->getZExtValue();
4001 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01004002 // Ops[1] = Object ID
4003 // Ops[2] = Composite ID
4004 // Ops[3] ... Ops[n] = Indexes (Literal Number)
4005 Ops << MkId(VMap[I.getOperand(1)])
4006 << MkId(VMap[I.getOperand(0)])
4007 << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004008 } else {
James Priced26efea2018-06-09 23:28:32 +01004009 // Ops[1] = Composite ID
4010 // Ops[2] = Object ID
4011 // Ops[3] ... Ops[n] = Indexes (Literal Number)
4012 Ops << MkId(VMap[I.getOperand(0)])
4013 << MkId(VMap[I.getOperand(1)])
4014 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004015 Opcode = spv::OpVectorInsertDynamic;
4016 }
4017
David Neto87846742018-04-11 17:36:22 -04004018 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004019 SPIRVInstList.push_back(Inst);
4020 break;
4021 }
4022 case Instruction::ShuffleVector: {
4023 // Ops[0] = Result Type ID
4024 // Ops[1] = Vector 1 ID
4025 // Ops[2] = Vector 2 ID
4026 // Ops[3] ... Ops[n] = Components (Literal Number)
4027 SPIRVOperandList Ops;
4028
David Neto257c3892018-04-11 13:19:45 -04004029 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4030 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004031
4032 uint64_t NumElements = 0;
4033 if (Constant *Cst = dyn_cast<Constant>(I.getOperand(2))) {
4034 NumElements = cast<VectorType>(Cst->getType())->getNumElements();
4035
4036 if (Cst->isNullValue()) {
4037 for (unsigned i = 0; i < NumElements; i++) {
David Neto257c3892018-04-11 13:19:45 -04004038 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04004039 }
4040 } else if (const ConstantDataSequential *CDS =
4041 dyn_cast<ConstantDataSequential>(Cst)) {
4042 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
4043 std::vector<uint32_t> LiteralNum;
David Neto257c3892018-04-11 13:19:45 -04004044 const auto value = CDS->getElementAsInteger(i);
4045 assert(value <= UINT32_MAX);
4046 Ops << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004047 }
4048 } else if (const ConstantVector *CV = dyn_cast<ConstantVector>(Cst)) {
4049 for (unsigned i = 0; i < CV->getNumOperands(); i++) {
4050 auto Op = CV->getOperand(i);
4051
4052 uint32_t literal = 0;
4053
4054 if (auto CI = dyn_cast<ConstantInt>(Op)) {
4055 literal = static_cast<uint32_t>(CI->getZExtValue());
4056 } else if (auto UI = dyn_cast<UndefValue>(Op)) {
4057 literal = 0xFFFFFFFFu;
4058 } else {
4059 Op->print(errs());
4060 llvm_unreachable("Unsupported element in ConstantVector!");
4061 }
4062
David Neto257c3892018-04-11 13:19:45 -04004063 Ops << MkNum(literal);
David Neto22f144c2017-06-12 14:26:21 -04004064 }
4065 } else {
4066 Cst->print(errs());
4067 llvm_unreachable("Unsupported constant mask in ShuffleVector!");
4068 }
4069 }
4070
David Neto87846742018-04-11 17:36:22 -04004071 auto *Inst = new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004072 SPIRVInstList.push_back(Inst);
4073 break;
4074 }
4075 case Instruction::ICmp:
4076 case Instruction::FCmp: {
4077 CmpInst *CmpI = cast<CmpInst>(&I);
4078
David Netod4ca2e62017-07-06 18:47:35 -04004079 // Pointer equality is invalid.
4080 Type* ArgTy = CmpI->getOperand(0)->getType();
4081 if (isa<PointerType>(ArgTy)) {
4082 CmpI->print(errs());
4083 std::string name = I.getParent()->getParent()->getName();
4084 errs()
4085 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4086 << "in function " << name << "\n";
4087 llvm_unreachable("Pointer equality check is invalid");
4088 break;
4089 }
4090
David Neto257c3892018-04-11 13:19:45 -04004091 // Ops[0] = Result Type ID
4092 // Ops[1] = Operand 1 ID
4093 // Ops[2] = Operand 2 ID
4094 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004095
David Neto257c3892018-04-11 13:19:45 -04004096 Ops << MkId(lookupType(CmpI->getType())) << MkId(VMap[CmpI->getOperand(0)])
4097 << MkId(VMap[CmpI->getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004098
4099 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
David Neto87846742018-04-11 17:36:22 -04004100 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004101 SPIRVInstList.push_back(Inst);
4102 break;
4103 }
4104 case Instruction::Br: {
4105 // Branch instrucion is deferred because it needs label's ID. Record slot's
4106 // location on SPIRVInstructionList.
4107 DeferredInsts.push_back(
4108 std::make_tuple(&I, --SPIRVInstList.end(), 0 /* No id */));
4109 break;
4110 }
4111 case Instruction::Switch: {
4112 I.print(errs());
4113 llvm_unreachable("Unsupported instruction???");
4114 break;
4115 }
4116 case Instruction::IndirectBr: {
4117 I.print(errs());
4118 llvm_unreachable("Unsupported instruction???");
4119 break;
4120 }
4121 case Instruction::PHI: {
4122 // Branch instrucion is deferred because it needs label's ID. Record slot's
4123 // location on SPIRVInstructionList.
4124 DeferredInsts.push_back(
4125 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4126 break;
4127 }
4128 case Instruction::Alloca: {
4129 //
4130 // Generate OpVariable.
4131 //
4132 // Ops[0] : Result Type ID
4133 // Ops[1] : Storage Class
4134 SPIRVOperandList Ops;
4135
David Neto257c3892018-04-11 13:19:45 -04004136 Ops << MkId(lookupType(I.getType())) << MkNum(spv::StorageClassFunction);
David Neto22f144c2017-06-12 14:26:21 -04004137
David Neto87846742018-04-11 17:36:22 -04004138 auto *Inst = new SPIRVInstruction(spv::OpVariable, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004139 SPIRVInstList.push_back(Inst);
4140 break;
4141 }
4142 case Instruction::Load: {
4143 LoadInst *LD = cast<LoadInst>(&I);
4144 //
4145 // Generate OpLoad.
4146 //
4147
David Neto0a2f98d2017-09-15 19:38:40 -04004148 uint32_t ResTyID = lookupType(LD->getType());
David Netoa60b00b2017-09-15 16:34:09 -04004149 uint32_t PointerID = VMap[LD->getPointerOperand()];
4150
4151 // This is a hack to work around what looks like a driver bug.
4152 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004153 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4154 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004155 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004156 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004157 // Generate a bitwise-and of the original value with itself.
4158 // We should have been able to get away with just an OpCopyObject,
4159 // but we need something more complex to get past certain driver bugs.
4160 // This is ridiculous, but necessary.
4161 // TODO(dneto): Revisit this once drivers fix their bugs.
4162
4163 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004164 Ops << MkId(ResTyID) << MkId(WorkgroupSizeValueID)
4165 << MkId(WorkgroupSizeValueID);
David Neto0a2f98d2017-09-15 19:38:40 -04004166
David Neto87846742018-04-11 17:36:22 -04004167 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto0a2f98d2017-09-15 19:38:40 -04004168 SPIRVInstList.push_back(Inst);
David Netoa60b00b2017-09-15 16:34:09 -04004169 break;
4170 }
4171
4172 // This is the normal path. Generate a load.
4173
David Neto22f144c2017-06-12 14:26:21 -04004174 // Ops[0] = Result Type ID
4175 // Ops[1] = Pointer ID
4176 // Ops[2] ... Ops[n] = Optional Memory Access
4177 //
4178 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004179
David Neto22f144c2017-06-12 14:26:21 -04004180 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004181 Ops << MkId(ResTyID) << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04004182
David Neto87846742018-04-11 17:36:22 -04004183 auto *Inst = new SPIRVInstruction(spv::OpLoad, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004184 SPIRVInstList.push_back(Inst);
4185 break;
4186 }
4187 case Instruction::Store: {
4188 StoreInst *ST = cast<StoreInst>(&I);
4189 //
4190 // Generate OpStore.
4191 //
4192
4193 // Ops[0] = Pointer ID
4194 // Ops[1] = Object ID
4195 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4196 //
4197 // TODO: Do we need to implement Optional Memory Access???
David Neto257c3892018-04-11 13:19:45 -04004198 SPIRVOperandList Ops;
4199 Ops << MkId(VMap[ST->getPointerOperand()])
4200 << MkId(VMap[ST->getValueOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004201
David Neto87846742018-04-11 17:36:22 -04004202 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004203 SPIRVInstList.push_back(Inst);
4204 break;
4205 }
4206 case Instruction::AtomicCmpXchg: {
4207 I.print(errs());
4208 llvm_unreachable("Unsupported instruction???");
4209 break;
4210 }
4211 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004212 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4213
4214 spv::Op opcode;
4215
4216 switch (AtomicRMW->getOperation()) {
4217 default:
4218 I.print(errs());
4219 llvm_unreachable("Unsupported instruction???");
4220 case llvm::AtomicRMWInst::Add:
4221 opcode = spv::OpAtomicIAdd;
4222 break;
4223 case llvm::AtomicRMWInst::Sub:
4224 opcode = spv::OpAtomicISub;
4225 break;
4226 case llvm::AtomicRMWInst::Xchg:
4227 opcode = spv::OpAtomicExchange;
4228 break;
4229 case llvm::AtomicRMWInst::Min:
4230 opcode = spv::OpAtomicSMin;
4231 break;
4232 case llvm::AtomicRMWInst::Max:
4233 opcode = spv::OpAtomicSMax;
4234 break;
4235 case llvm::AtomicRMWInst::UMin:
4236 opcode = spv::OpAtomicUMin;
4237 break;
4238 case llvm::AtomicRMWInst::UMax:
4239 opcode = spv::OpAtomicUMax;
4240 break;
4241 case llvm::AtomicRMWInst::And:
4242 opcode = spv::OpAtomicAnd;
4243 break;
4244 case llvm::AtomicRMWInst::Or:
4245 opcode = spv::OpAtomicOr;
4246 break;
4247 case llvm::AtomicRMWInst::Xor:
4248 opcode = spv::OpAtomicXor;
4249 break;
4250 }
4251
4252 //
4253 // Generate OpAtomic*.
4254 //
4255 SPIRVOperandList Ops;
4256
David Neto257c3892018-04-11 13:19:45 -04004257 Ops << MkId(lookupType(I.getType()))
4258 << MkId(VMap[AtomicRMW->getPointerOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004259
4260 auto IntTy = Type::getInt32Ty(I.getContext());
Neil Henning39672102017-09-29 14:33:13 +01004261 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
David Neto257c3892018-04-11 13:19:45 -04004262 Ops << MkId(VMap[ConstantScopeDevice]);
Neil Henning39672102017-09-29 14:33:13 +01004263
4264 const auto ConstantMemorySemantics = ConstantInt::get(
4265 IntTy, spv::MemorySemanticsUniformMemoryMask |
4266 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto257c3892018-04-11 13:19:45 -04004267 Ops << MkId(VMap[ConstantMemorySemantics]);
Neil Henning39672102017-09-29 14:33:13 +01004268
David Neto257c3892018-04-11 13:19:45 -04004269 Ops << MkId(VMap[AtomicRMW->getValOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004270
4271 VMap[&I] = nextID;
4272
David Neto87846742018-04-11 17:36:22 -04004273 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
Neil Henning39672102017-09-29 14:33:13 +01004274 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004275 break;
4276 }
4277 case Instruction::Fence: {
4278 I.print(errs());
4279 llvm_unreachable("Unsupported instruction???");
4280 break;
4281 }
4282 case Instruction::Call: {
4283 CallInst *Call = dyn_cast<CallInst>(&I);
4284 Function *Callee = Call->getCalledFunction();
4285
Alan Baker202c8c72018-08-13 13:47:44 -04004286 if (Callee->getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004287 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
4288 // Generate an OpLoad
4289 SPIRVOperandList Ops;
4290 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004291
David Neto862b7d82018-06-14 18:48:37 -04004292 Ops << MkId(lookupType(Call->getType()->getPointerElementType()))
4293 << MkId(ResourceVarDeferredLoadCalls[Call]);
4294
4295 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
4296 SPIRVInstList.push_back(Inst);
4297 VMap[Call] = load_id;
4298 break;
4299
4300 } else {
4301 // This maps to an OpVariable we've already generated.
4302 // No code is generated for the call.
4303 }
4304 break;
Alan Baker202c8c72018-08-13 13:47:44 -04004305 } else if (Callee->getName().startswith(clspv::WorkgroupAccessorFunction())) {
4306 // Don't codegen an instruction here, but instead map this call directly
4307 // to the workgroup variable id.
4308 int spec_id = cast<ConstantInt>(Call->getOperand(0))->getSExtValue();
4309 const auto &info = LocalSpecIdInfoMap[spec_id];
4310 VMap[Call] = info.variable_id;
4311 break;
David Neto862b7d82018-06-14 18:48:37 -04004312 }
4313
4314 // Sampler initializers become a load of the corresponding sampler.
4315
4316 if (Callee->getName().equals("clspv.sampler.var.literal")) {
4317 // Map this to a load from the variable.
4318 const auto index_into_sampler_map =
4319 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4320
4321 // Generate an OpLoad
David Neto22f144c2017-06-12 14:26:21 -04004322 SPIRVOperandList Ops;
David Neto862b7d82018-06-14 18:48:37 -04004323 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004324
David Neto257c3892018-04-11 13:19:45 -04004325 Ops << MkId(lookupType(SamplerTy->getPointerElementType()))
David Neto862b7d82018-06-14 18:48:37 -04004326 << MkId(SamplerMapIndexToIDMap[index_into_sampler_map]);
David Neto22f144c2017-06-12 14:26:21 -04004327
David Neto862b7d82018-06-14 18:48:37 -04004328 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004329 SPIRVInstList.push_back(Inst);
David Neto862b7d82018-06-14 18:48:37 -04004330 VMap[Call] = load_id;
David Neto22f144c2017-06-12 14:26:21 -04004331 break;
4332 }
4333
4334 if (Callee->getName().startswith("spirv.atomic")) {
4335 spv::Op opcode = StringSwitch<spv::Op>(Callee->getName())
4336 .Case("spirv.atomic_add", spv::OpAtomicIAdd)
4337 .Case("spirv.atomic_sub", spv::OpAtomicISub)
4338 .Case("spirv.atomic_exchange", spv::OpAtomicExchange)
4339 .Case("spirv.atomic_inc", spv::OpAtomicIIncrement)
4340 .Case("spirv.atomic_dec", spv::OpAtomicIDecrement)
4341 .Case("spirv.atomic_compare_exchange",
4342 spv::OpAtomicCompareExchange)
4343 .Case("spirv.atomic_umin", spv::OpAtomicUMin)
4344 .Case("spirv.atomic_smin", spv::OpAtomicSMin)
4345 .Case("spirv.atomic_umax", spv::OpAtomicUMax)
4346 .Case("spirv.atomic_smax", spv::OpAtomicSMax)
4347 .Case("spirv.atomic_and", spv::OpAtomicAnd)
4348 .Case("spirv.atomic_or", spv::OpAtomicOr)
4349 .Case("spirv.atomic_xor", spv::OpAtomicXor)
4350 .Default(spv::OpNop);
4351
4352 //
4353 // Generate OpAtomic*.
4354 //
4355 SPIRVOperandList Ops;
4356
David Neto257c3892018-04-11 13:19:45 -04004357 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004358
4359 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004360 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004361 }
4362
4363 VMap[&I] = nextID;
4364
David Neto87846742018-04-11 17:36:22 -04004365 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004366 SPIRVInstList.push_back(Inst);
4367 break;
4368 }
4369
4370 if (Callee->getName().startswith("_Z3dot")) {
4371 // If the argument is a vector type, generate OpDot
4372 if (Call->getArgOperand(0)->getType()->isVectorTy()) {
4373 //
4374 // Generate OpDot.
4375 //
4376 SPIRVOperandList Ops;
4377
David Neto257c3892018-04-11 13:19:45 -04004378 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004379
4380 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004381 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004382 }
4383
4384 VMap[&I] = nextID;
4385
David Neto87846742018-04-11 17:36:22 -04004386 auto *Inst = new SPIRVInstruction(spv::OpDot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004387 SPIRVInstList.push_back(Inst);
4388 } else {
4389 //
4390 // Generate OpFMul.
4391 //
4392 SPIRVOperandList Ops;
4393
David Neto257c3892018-04-11 13:19:45 -04004394 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004395
4396 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004397 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004398 }
4399
4400 VMap[&I] = nextID;
4401
David Neto87846742018-04-11 17:36:22 -04004402 auto *Inst = new SPIRVInstruction(spv::OpFMul, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004403 SPIRVInstList.push_back(Inst);
4404 }
4405 break;
4406 }
4407
David Neto8505ebf2017-10-13 18:50:50 -04004408 if (Callee->getName().startswith("_Z4fmod")) {
4409 // OpenCL fmod(x,y) is x - y * trunc(x/y)
4410 // The sign for a non-zero result is taken from x.
4411 // (Try an example.)
4412 // So translate to OpFRem
4413
4414 SPIRVOperandList Ops;
4415
David Neto257c3892018-04-11 13:19:45 -04004416 Ops << MkId(lookupType(I.getType()));
David Neto8505ebf2017-10-13 18:50:50 -04004417
4418 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004419 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto8505ebf2017-10-13 18:50:50 -04004420 }
4421
4422 VMap[&I] = nextID;
4423
David Neto87846742018-04-11 17:36:22 -04004424 auto *Inst = new SPIRVInstruction(spv::OpFRem, nextID++, Ops);
David Neto8505ebf2017-10-13 18:50:50 -04004425 SPIRVInstList.push_back(Inst);
4426 break;
4427 }
4428
David Neto22f144c2017-06-12 14:26:21 -04004429 // spirv.store_null.* intrinsics become OpStore's.
4430 if (Callee->getName().startswith("spirv.store_null")) {
4431 //
4432 // Generate OpStore.
4433 //
4434
4435 // Ops[0] = Pointer ID
4436 // Ops[1] = Object ID
4437 // Ops[2] ... Ops[n]
4438 SPIRVOperandList Ops;
4439
4440 uint32_t PointerID = VMap[Call->getArgOperand(0)];
David Neto22f144c2017-06-12 14:26:21 -04004441 uint32_t ObjectID = VMap[Call->getArgOperand(1)];
David Neto257c3892018-04-11 13:19:45 -04004442 Ops << MkId(PointerID) << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04004443
David Neto87846742018-04-11 17:36:22 -04004444 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpStore, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004445
4446 break;
4447 }
4448
4449 // spirv.copy_memory.* intrinsics become OpMemoryMemory's.
4450 if (Callee->getName().startswith("spirv.copy_memory")) {
4451 //
4452 // Generate OpCopyMemory.
4453 //
4454
4455 // Ops[0] = Dst ID
4456 // Ops[1] = Src ID
4457 // Ops[2] = Memory Access
4458 // Ops[3] = Alignment
4459
4460 auto IsVolatile =
4461 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
4462
4463 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
4464 : spv::MemoryAccessMaskNone;
4465
4466 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
4467
4468 auto Alignment =
4469 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4470
David Neto257c3892018-04-11 13:19:45 -04004471 SPIRVOperandList Ops;
4472 Ops << MkId(VMap[Call->getArgOperand(0)])
4473 << MkId(VMap[Call->getArgOperand(1)]) << MkNum(MemoryAccess)
4474 << MkNum(static_cast<uint32_t>(Alignment));
David Neto22f144c2017-06-12 14:26:21 -04004475
David Neto87846742018-04-11 17:36:22 -04004476 auto *Inst = new SPIRVInstruction(spv::OpCopyMemory, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004477
4478 SPIRVInstList.push_back(Inst);
4479
4480 break;
4481 }
4482
4483 // Nothing to do for abs with uint. Map abs's operand ID to VMap for abs
4484 // with unit.
4485 if (Callee->getName().equals("_Z3absj") ||
4486 Callee->getName().equals("_Z3absDv2_j") ||
4487 Callee->getName().equals("_Z3absDv3_j") ||
4488 Callee->getName().equals("_Z3absDv4_j")) {
4489 VMap[&I] = VMap[Call->getOperand(0)];
4490 break;
4491 }
4492
4493 // barrier is converted to OpControlBarrier
4494 if (Callee->getName().equals("__spirv_control_barrier")) {
4495 //
4496 // Generate OpControlBarrier.
4497 //
4498 // Ops[0] = Execution Scope ID
4499 // Ops[1] = Memory Scope ID
4500 // Ops[2] = Memory Semantics ID
4501 //
4502 Value *ExecutionScope = Call->getArgOperand(0);
4503 Value *MemoryScope = Call->getArgOperand(1);
4504 Value *MemorySemantics = Call->getArgOperand(2);
4505
David Neto257c3892018-04-11 13:19:45 -04004506 SPIRVOperandList Ops;
4507 Ops << MkId(VMap[ExecutionScope]) << MkId(VMap[MemoryScope])
4508 << MkId(VMap[MemorySemantics]);
David Neto22f144c2017-06-12 14:26:21 -04004509
David Neto87846742018-04-11 17:36:22 -04004510 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpControlBarrier, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004511 break;
4512 }
4513
4514 // memory barrier is converted to OpMemoryBarrier
4515 if (Callee->getName().equals("__spirv_memory_barrier")) {
4516 //
4517 // Generate OpMemoryBarrier.
4518 //
4519 // Ops[0] = Memory Scope ID
4520 // Ops[1] = Memory Semantics ID
4521 //
4522 SPIRVOperandList Ops;
4523
David Neto257c3892018-04-11 13:19:45 -04004524 uint32_t MemoryScopeID = VMap[Call->getArgOperand(0)];
4525 uint32_t MemorySemanticsID = VMap[Call->getArgOperand(1)];
David Neto22f144c2017-06-12 14:26:21 -04004526
David Neto257c3892018-04-11 13:19:45 -04004527 Ops << MkId(MemoryScopeID) << MkId(MemorySemanticsID);
David Neto22f144c2017-06-12 14:26:21 -04004528
David Neto87846742018-04-11 17:36:22 -04004529 auto *Inst = new SPIRVInstruction(spv::OpMemoryBarrier, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004530 SPIRVInstList.push_back(Inst);
4531 break;
4532 }
4533
4534 // isinf is converted to OpIsInf
4535 if (Callee->getName().equals("__spirv_isinff") ||
4536 Callee->getName().equals("__spirv_isinfDv2_f") ||
4537 Callee->getName().equals("__spirv_isinfDv3_f") ||
4538 Callee->getName().equals("__spirv_isinfDv4_f")) {
4539 //
4540 // Generate OpIsInf.
4541 //
4542 // Ops[0] = Result Type ID
4543 // Ops[1] = X ID
4544 //
4545 SPIRVOperandList Ops;
4546
David Neto257c3892018-04-11 13:19:45 -04004547 Ops << MkId(lookupType(I.getType()))
4548 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004549
4550 VMap[&I] = nextID;
4551
David Neto87846742018-04-11 17:36:22 -04004552 auto *Inst = new SPIRVInstruction(spv::OpIsInf, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004553 SPIRVInstList.push_back(Inst);
4554 break;
4555 }
4556
4557 // isnan is converted to OpIsNan
4558 if (Callee->getName().equals("__spirv_isnanf") ||
4559 Callee->getName().equals("__spirv_isnanDv2_f") ||
4560 Callee->getName().equals("__spirv_isnanDv3_f") ||
4561 Callee->getName().equals("__spirv_isnanDv4_f")) {
4562 //
4563 // Generate OpIsInf.
4564 //
4565 // Ops[0] = Result Type ID
4566 // Ops[1] = X ID
4567 //
4568 SPIRVOperandList Ops;
4569
David Neto257c3892018-04-11 13:19:45 -04004570 Ops << MkId(lookupType(I.getType()))
4571 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004572
4573 VMap[&I] = nextID;
4574
David Neto87846742018-04-11 17:36:22 -04004575 auto *Inst = new SPIRVInstruction(spv::OpIsNan, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004576 SPIRVInstList.push_back(Inst);
4577 break;
4578 }
4579
4580 // all is converted to OpAll
4581 if (Callee->getName().equals("__spirv_allDv2_i") ||
4582 Callee->getName().equals("__spirv_allDv3_i") ||
4583 Callee->getName().equals("__spirv_allDv4_i")) {
4584 //
4585 // Generate OpAll.
4586 //
4587 // Ops[0] = Result Type ID
4588 // Ops[1] = Vector ID
4589 //
4590 SPIRVOperandList Ops;
4591
David Neto257c3892018-04-11 13:19:45 -04004592 Ops << MkId(lookupType(I.getType()))
4593 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004594
4595 VMap[&I] = nextID;
4596
David Neto87846742018-04-11 17:36:22 -04004597 auto *Inst = new SPIRVInstruction(spv::OpAll, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004598 SPIRVInstList.push_back(Inst);
4599 break;
4600 }
4601
4602 // any is converted to OpAny
4603 if (Callee->getName().equals("__spirv_anyDv2_i") ||
4604 Callee->getName().equals("__spirv_anyDv3_i") ||
4605 Callee->getName().equals("__spirv_anyDv4_i")) {
4606 //
4607 // Generate OpAny.
4608 //
4609 // Ops[0] = Result Type ID
4610 // Ops[1] = Vector ID
4611 //
4612 SPIRVOperandList Ops;
4613
David Neto257c3892018-04-11 13:19:45 -04004614 Ops << MkId(lookupType(I.getType()))
4615 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004616
4617 VMap[&I] = nextID;
4618
David Neto87846742018-04-11 17:36:22 -04004619 auto *Inst = new SPIRVInstruction(spv::OpAny, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004620 SPIRVInstList.push_back(Inst);
4621 break;
4622 }
4623
4624 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
4625 // Additionally, OpTypeSampledImage is generated.
4626 if (Callee->getName().equals(
4627 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
4628 Callee->getName().equals(
4629 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
4630 //
4631 // Generate OpSampledImage.
4632 //
4633 // Ops[0] = Result Type ID
4634 // Ops[1] = Image ID
4635 // Ops[2] = Sampler ID
4636 //
4637 SPIRVOperandList Ops;
4638
4639 Value *Image = Call->getArgOperand(0);
4640 Value *Sampler = Call->getArgOperand(1);
4641 Value *Coordinate = Call->getArgOperand(2);
4642
4643 TypeMapType &OpImageTypeMap = getImageTypeMap();
4644 Type *ImageTy = Image->getType()->getPointerElementType();
4645 uint32_t ImageTyID = OpImageTypeMap[ImageTy];
David Neto22f144c2017-06-12 14:26:21 -04004646 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004647 uint32_t SamplerID = VMap[Sampler];
David Neto257c3892018-04-11 13:19:45 -04004648
4649 Ops << MkId(ImageTyID) << MkId(ImageID) << MkId(SamplerID);
David Neto22f144c2017-06-12 14:26:21 -04004650
4651 uint32_t SampledImageID = nextID;
4652
David Neto87846742018-04-11 17:36:22 -04004653 auto *Inst = new SPIRVInstruction(spv::OpSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004654 SPIRVInstList.push_back(Inst);
4655
4656 //
4657 // Generate OpImageSampleExplicitLod.
4658 //
4659 // Ops[0] = Result Type ID
4660 // Ops[1] = Sampled Image ID
4661 // Ops[2] = Coordinate ID
4662 // Ops[3] = Image Operands Type ID
4663 // Ops[4] ... Ops[n] = Operands ID
4664 //
4665 Ops.clear();
4666
David Neto257c3892018-04-11 13:19:45 -04004667 Ops << MkId(lookupType(Call->getType())) << MkId(SampledImageID)
4668 << MkId(VMap[Coordinate]) << MkNum(spv::ImageOperandsLodMask);
David Neto22f144c2017-06-12 14:26:21 -04004669
4670 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
David Neto257c3892018-04-11 13:19:45 -04004671 Ops << MkId(VMap[CstFP0]);
David Neto22f144c2017-06-12 14:26:21 -04004672
4673 VMap[&I] = nextID;
4674
David Neto87846742018-04-11 17:36:22 -04004675 Inst = new SPIRVInstruction(spv::OpImageSampleExplicitLod, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004676 SPIRVInstList.push_back(Inst);
4677 break;
4678 }
4679
4680 // write_imagef is mapped to OpImageWrite.
4681 if (Callee->getName().equals(
4682 "_Z12write_imagef14ocl_image2d_woDv2_iDv4_f") ||
4683 Callee->getName().equals(
4684 "_Z12write_imagef14ocl_image3d_woDv4_iDv4_f")) {
4685 //
4686 // Generate OpImageWrite.
4687 //
4688 // Ops[0] = Image ID
4689 // Ops[1] = Coordinate ID
4690 // Ops[2] = Texel ID
4691 // Ops[3] = (Optional) Image Operands Type (Literal Number)
4692 // Ops[4] ... Ops[n] = (Optional) Operands ID
4693 //
4694 SPIRVOperandList Ops;
4695
4696 Value *Image = Call->getArgOperand(0);
4697 Value *Coordinate = Call->getArgOperand(1);
4698 Value *Texel = Call->getArgOperand(2);
4699
4700 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004701 uint32_t CoordinateID = VMap[Coordinate];
David Neto22f144c2017-06-12 14:26:21 -04004702 uint32_t TexelID = VMap[Texel];
David Neto257c3892018-04-11 13:19:45 -04004703 Ops << MkId(ImageID) << MkId(CoordinateID) << MkId(TexelID);
David Neto22f144c2017-06-12 14:26:21 -04004704
David Neto87846742018-04-11 17:36:22 -04004705 auto *Inst = new SPIRVInstruction(spv::OpImageWrite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004706 SPIRVInstList.push_back(Inst);
4707 break;
4708 }
4709
David Neto5c22a252018-03-15 16:07:41 -04004710 // get_image_width is mapped to OpImageQuerySize
4711 if (Callee->getName().equals("_Z15get_image_width14ocl_image2d_ro") ||
4712 Callee->getName().equals("_Z15get_image_width14ocl_image2d_wo") ||
4713 Callee->getName().equals("_Z16get_image_height14ocl_image2d_ro") ||
4714 Callee->getName().equals("_Z16get_image_height14ocl_image2d_wo")) {
4715 //
4716 // Generate OpImageQuerySize, then pull out the right component.
4717 // Assume 2D image for now.
4718 //
4719 // Ops[0] = Image ID
4720 //
4721 // %sizes = OpImageQuerySizes %uint2 %im
4722 // %result = OpCompositeExtract %uint %sizes 0-or-1
4723 SPIRVOperandList Ops;
4724
4725 // Implement:
4726 // %sizes = OpImageQuerySizes %uint2 %im
4727 uint32_t SizesTypeID =
4728 TypeMap[VectorType::get(Type::getInt32Ty(Context), 2)];
David Neto5c22a252018-03-15 16:07:41 -04004729 Value *Image = Call->getArgOperand(0);
4730 uint32_t ImageID = VMap[Image];
David Neto257c3892018-04-11 13:19:45 -04004731 Ops << MkId(SizesTypeID) << MkId(ImageID);
David Neto5c22a252018-03-15 16:07:41 -04004732
4733 uint32_t SizesID = nextID++;
David Neto87846742018-04-11 17:36:22 -04004734 auto *QueryInst =
4735 new SPIRVInstruction(spv::OpImageQuerySize, SizesID, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004736 SPIRVInstList.push_back(QueryInst);
4737
4738 // Reset value map entry since we generated an intermediate instruction.
4739 VMap[&I] = nextID;
4740
4741 // Implement:
4742 // %result = OpCompositeExtract %uint %sizes 0-or-1
4743 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004744 Ops << MkId(TypeMap[I.getType()]) << MkId(SizesID);
David Neto5c22a252018-03-15 16:07:41 -04004745
4746 uint32_t component = Callee->getName().contains("height") ? 1 : 0;
David Neto257c3892018-04-11 13:19:45 -04004747 Ops << MkNum(component);
David Neto5c22a252018-03-15 16:07:41 -04004748
David Neto87846742018-04-11 17:36:22 -04004749 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004750 SPIRVInstList.push_back(Inst);
4751 break;
4752 }
4753
David Neto22f144c2017-06-12 14:26:21 -04004754 // Call instrucion is deferred because it needs function's ID. Record
4755 // slot's location on SPIRVInstructionList.
4756 DeferredInsts.push_back(
4757 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4758
David Neto3fbb4072017-10-16 11:28:14 -04004759 // Check whether the implementation of this call uses an extended
4760 // instruction plus one more value-producing instruction. If so, then
4761 // reserve the id for the extra value-producing slot.
4762 glsl::ExtInst EInst = getIndirectExtInstEnum(Callee->getName());
4763 if (EInst != kGlslExtInstBad) {
4764 // Reserve a spot for the extra value.
David Neto4d02a532017-09-17 12:57:44 -04004765 // Increase nextID.
David Neto22f144c2017-06-12 14:26:21 -04004766 VMap[&I] = nextID;
4767 nextID++;
4768 }
4769 break;
4770 }
4771 case Instruction::Ret: {
4772 unsigned NumOps = I.getNumOperands();
4773 if (NumOps == 0) {
4774 //
4775 // Generate OpReturn.
4776 //
David Neto87846742018-04-11 17:36:22 -04004777 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpReturn, {}));
David Neto22f144c2017-06-12 14:26:21 -04004778 } else {
4779 //
4780 // Generate OpReturnValue.
4781 //
4782
4783 // Ops[0] = Return Value ID
4784 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004785
4786 Ops << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004787
David Neto87846742018-04-11 17:36:22 -04004788 auto *Inst = new SPIRVInstruction(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004789 SPIRVInstList.push_back(Inst);
4790 break;
4791 }
4792 break;
4793 }
4794 }
4795}
4796
4797void SPIRVProducerPass::GenerateFuncEpilogue() {
4798 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4799
4800 //
4801 // Generate OpFunctionEnd
4802 //
4803
David Neto87846742018-04-11 17:36:22 -04004804 auto *Inst = new SPIRVInstruction(spv::OpFunctionEnd, {});
David Neto22f144c2017-06-12 14:26:21 -04004805 SPIRVInstList.push_back(Inst);
4806}
4807
4808bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
4809 LLVMContext &Context = Ty->getContext();
4810 if (Ty->isVectorTy()) {
4811 if (Ty->getVectorElementType() == Type::getInt8Ty(Context) &&
4812 Ty->getVectorNumElements() == 4) {
4813 return true;
4814 }
4815 }
4816
4817 return false;
4818}
4819
David Neto257c3892018-04-11 13:19:45 -04004820uint32_t SPIRVProducerPass::GetI32Zero() {
4821 if (0 == constant_i32_zero_id_) {
4822 llvm_unreachable("Requesting a 32-bit integer constant but it is not "
4823 "defined in the SPIR-V module");
4824 }
4825 return constant_i32_zero_id_;
4826}
4827
David Neto22f144c2017-06-12 14:26:21 -04004828void SPIRVProducerPass::HandleDeferredInstruction() {
4829 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4830 ValueMapType &VMap = getValueMap();
4831 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4832
4833 for (auto DeferredInst = DeferredInsts.rbegin();
4834 DeferredInst != DeferredInsts.rend(); ++DeferredInst) {
4835 Value *Inst = std::get<0>(*DeferredInst);
4836 SPIRVInstructionList::iterator InsertPoint = ++std::get<1>(*DeferredInst);
4837 if (InsertPoint != SPIRVInstList.end()) {
4838 while ((*InsertPoint)->getOpcode() == spv::OpPhi) {
4839 ++InsertPoint;
4840 }
4841 }
4842
4843 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
4844 // Check whether basic block, which has this branch instruction, is loop
4845 // header or not. If it is loop header, generate OpLoopMerge and
4846 // OpBranchConditional.
4847 Function *Func = Br->getParent()->getParent();
4848 DominatorTree &DT =
4849 getAnalysis<DominatorTreeWrapperPass>(*Func).getDomTree();
4850 const LoopInfo &LI =
4851 getAnalysis<LoopInfoWrapperPass>(*Func).getLoopInfo();
4852
4853 BasicBlock *BrBB = Br->getParent();
4854 if (LI.isLoopHeader(BrBB)) {
4855 Value *ContinueBB = nullptr;
4856 Value *MergeBB = nullptr;
4857
4858 Loop *L = LI.getLoopFor(BrBB);
4859 MergeBB = L->getExitBlock();
4860 if (!MergeBB) {
4861 // StructurizeCFG pass converts CFG into triangle shape and the cfg
4862 // has regions with single entry/exit. As a result, loop should not
4863 // have multiple exits.
4864 llvm_unreachable("Loop has multiple exits???");
4865 }
4866
4867 if (L->isLoopLatch(BrBB)) {
4868 ContinueBB = BrBB;
4869 } else {
4870 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
4871 // block.
4872 BasicBlock *Header = L->getHeader();
4873 BasicBlock *Latch = L->getLoopLatch();
4874 for (BasicBlock *BB : L->blocks()) {
4875 if (BB == Header) {
4876 continue;
4877 }
4878
4879 // Check whether block dominates block with back-edge.
4880 if (DT.dominates(BB, Latch)) {
4881 ContinueBB = BB;
4882 }
4883 }
4884
4885 if (!ContinueBB) {
4886 llvm_unreachable("Wrong continue block from loop");
4887 }
4888 }
4889
4890 //
4891 // Generate OpLoopMerge.
4892 //
4893 // Ops[0] = Merge Block ID
4894 // Ops[1] = Continue Target ID
4895 // Ops[2] = Selection Control
4896 SPIRVOperandList Ops;
4897
4898 // StructurizeCFG pass already manipulated CFG. Just use false block of
4899 // branch instruction as merge block.
4900 uint32_t MergeBBID = VMap[MergeBB];
David Neto22f144c2017-06-12 14:26:21 -04004901 uint32_t ContinueBBID = VMap[ContinueBB];
David Neto257c3892018-04-11 13:19:45 -04004902 Ops << MkId(MergeBBID) << MkId(ContinueBBID)
4903 << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004904
David Neto87846742018-04-11 17:36:22 -04004905 auto *MergeInst = new SPIRVInstruction(spv::OpLoopMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004906 SPIRVInstList.insert(InsertPoint, MergeInst);
4907
4908 } else if (Br->isConditional()) {
4909 bool HasBackEdge = false;
4910
4911 for (unsigned i = 0; i < Br->getNumSuccessors(); i++) {
4912 if (LI.isLoopHeader(Br->getSuccessor(i))) {
4913 HasBackEdge = true;
4914 }
4915 }
4916 if (!HasBackEdge) {
4917 //
4918 // Generate OpSelectionMerge.
4919 //
4920 // Ops[0] = Merge Block ID
4921 // Ops[1] = Selection Control
4922 SPIRVOperandList Ops;
4923
4924 // StructurizeCFG pass already manipulated CFG. Just use false block
4925 // of branch instruction as merge block.
4926 uint32_t MergeBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004927 Ops << MkId(MergeBBID) << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004928
David Neto87846742018-04-11 17:36:22 -04004929 auto *MergeInst = new SPIRVInstruction(spv::OpSelectionMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004930 SPIRVInstList.insert(InsertPoint, MergeInst);
4931 }
4932 }
4933
4934 if (Br->isConditional()) {
4935 //
4936 // Generate OpBranchConditional.
4937 //
4938 // Ops[0] = Condition ID
4939 // Ops[1] = True Label ID
4940 // Ops[2] = False Label ID
4941 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
4942 SPIRVOperandList Ops;
4943
4944 uint32_t CondID = VMap[Br->getCondition()];
David Neto22f144c2017-06-12 14:26:21 -04004945 uint32_t TrueBBID = VMap[Br->getSuccessor(0)];
David Neto22f144c2017-06-12 14:26:21 -04004946 uint32_t FalseBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004947
4948 Ops << MkId(CondID) << MkId(TrueBBID) << MkId(FalseBBID);
David Neto22f144c2017-06-12 14:26:21 -04004949
David Neto87846742018-04-11 17:36:22 -04004950 auto *BrInst = new SPIRVInstruction(spv::OpBranchConditional, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004951 SPIRVInstList.insert(InsertPoint, BrInst);
4952 } else {
4953 //
4954 // Generate OpBranch.
4955 //
4956 // Ops[0] = Target Label ID
4957 SPIRVOperandList Ops;
4958
4959 uint32_t TargetID = VMap[Br->getSuccessor(0)];
David Neto257c3892018-04-11 13:19:45 -04004960 Ops << MkId(TargetID);
David Neto22f144c2017-06-12 14:26:21 -04004961
David Neto87846742018-04-11 17:36:22 -04004962 SPIRVInstList.insert(InsertPoint,
4963 new SPIRVInstruction(spv::OpBranch, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004964 }
4965 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
4966 //
4967 // Generate OpPhi.
4968 //
4969 // Ops[0] = Result Type ID
4970 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
4971 SPIRVOperandList Ops;
4972
David Neto257c3892018-04-11 13:19:45 -04004973 Ops << MkId(lookupType(PHI->getType()));
David Neto22f144c2017-06-12 14:26:21 -04004974
David Neto22f144c2017-06-12 14:26:21 -04004975 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
4976 uint32_t VarID = VMap[PHI->getIncomingValue(i)];
David Neto22f144c2017-06-12 14:26:21 -04004977 uint32_t ParentID = VMap[PHI->getIncomingBlock(i)];
David Neto257c3892018-04-11 13:19:45 -04004978 Ops << MkId(VarID) << MkId(ParentID);
David Neto22f144c2017-06-12 14:26:21 -04004979 }
4980
4981 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04004982 InsertPoint,
4983 new SPIRVInstruction(spv::OpPhi, std::get<2>(*DeferredInst), Ops));
David Neto22f144c2017-06-12 14:26:21 -04004984 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
4985 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04004986 auto callee_name = Callee->getName();
4987 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04004988
4989 if (EInst) {
4990 uint32_t &ExtInstImportID = getOpExtInstImportID();
4991
4992 //
4993 // Generate OpExtInst.
4994 //
4995
4996 // Ops[0] = Result Type ID
4997 // Ops[1] = Set ID (OpExtInstImport ID)
4998 // Ops[2] = Instruction Number (Literal Number)
4999 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5000 SPIRVOperandList Ops;
5001
David Neto862b7d82018-06-14 18:48:37 -04005002 Ops << MkId(lookupType(Call->getType())) << MkId(ExtInstImportID)
5003 << MkNum(EInst);
David Neto22f144c2017-06-12 14:26:21 -04005004
David Neto22f144c2017-06-12 14:26:21 -04005005 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5006 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04005007 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04005008 }
5009
David Neto87846742018-04-11 17:36:22 -04005010 auto *ExtInst = new SPIRVInstruction(spv::OpExtInst,
5011 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005012 SPIRVInstList.insert(InsertPoint, ExtInst);
5013
David Neto3fbb4072017-10-16 11:28:14 -04005014 const auto IndirectExtInst = getIndirectExtInstEnum(callee_name);
5015 if (IndirectExtInst != kGlslExtInstBad) {
5016 // Generate one more instruction that uses the result of the extended
5017 // instruction. Its result id is one more than the id of the
5018 // extended instruction.
David Neto22f144c2017-06-12 14:26:21 -04005019 LLVMContext &Context =
5020 Call->getParent()->getParent()->getParent()->getContext();
David Neto22f144c2017-06-12 14:26:21 -04005021
David Neto3fbb4072017-10-16 11:28:14 -04005022 auto generate_extra_inst = [this, &Context, &Call, &DeferredInst,
5023 &VMap, &SPIRVInstList, &InsertPoint](
5024 spv::Op opcode, Constant *constant) {
5025 //
5026 // Generate instruction like:
5027 // result = opcode constant <extinst-result>
5028 //
5029 // Ops[0] = Result Type ID
5030 // Ops[1] = Operand 0 ;; the constant, suitably splatted
5031 // Ops[2] = Operand 1 ;; the result of the extended instruction
5032 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04005033
David Neto3fbb4072017-10-16 11:28:14 -04005034 Type *resultTy = Call->getType();
David Neto257c3892018-04-11 13:19:45 -04005035 Ops << MkId(lookupType(resultTy));
David Neto3fbb4072017-10-16 11:28:14 -04005036
5037 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
5038 constant = ConstantVector::getSplat(
5039 static_cast<unsigned>(vectorTy->getNumElements()), constant);
5040 }
David Neto257c3892018-04-11 13:19:45 -04005041 Ops << MkId(VMap[constant]) << MkId(std::get<2>(*DeferredInst));
David Neto3fbb4072017-10-16 11:28:14 -04005042
5043 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005044 InsertPoint, new SPIRVInstruction(
5045 opcode, std::get<2>(*DeferredInst) + 1, Ops));
David Neto3fbb4072017-10-16 11:28:14 -04005046 };
5047
5048 switch (IndirectExtInst) {
5049 case glsl::ExtInstFindUMsb: // Implementing clz
5050 generate_extra_inst(
5051 spv::OpISub, ConstantInt::get(Type::getInt32Ty(Context), 31));
5052 break;
5053 case glsl::ExtInstAcos: // Implementing acospi
5054 case glsl::ExtInstAsin: // Implementing asinpi
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005055 case glsl::ExtInstAtan: // Implementing atanpi
David Neto3fbb4072017-10-16 11:28:14 -04005056 case glsl::ExtInstAtan2: // Implementing atan2pi
5057 generate_extra_inst(
5058 spv::OpFMul,
5059 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
5060 break;
5061
5062 default:
5063 assert(false && "internally inconsistent");
David Neto4d02a532017-09-17 12:57:44 -04005064 }
David Neto22f144c2017-06-12 14:26:21 -04005065 }
David Neto3fbb4072017-10-16 11:28:14 -04005066
David Neto862b7d82018-06-14 18:48:37 -04005067 } else if (callee_name.equals("_Z8popcounti") ||
5068 callee_name.equals("_Z8popcountj") ||
5069 callee_name.equals("_Z8popcountDv2_i") ||
5070 callee_name.equals("_Z8popcountDv3_i") ||
5071 callee_name.equals("_Z8popcountDv4_i") ||
5072 callee_name.equals("_Z8popcountDv2_j") ||
5073 callee_name.equals("_Z8popcountDv3_j") ||
5074 callee_name.equals("_Z8popcountDv4_j")) {
David Neto22f144c2017-06-12 14:26:21 -04005075 //
5076 // Generate OpBitCount
5077 //
5078 // Ops[0] = Result Type ID
5079 // Ops[1] = Base ID
David Neto257c3892018-04-11 13:19:45 -04005080 SPIRVOperandList Ops;
5081 Ops << MkId(lookupType(Call->getType()))
5082 << MkId(VMap[Call->getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04005083
5084 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005085 InsertPoint, new SPIRVInstruction(spv::OpBitCount,
David Neto22f144c2017-06-12 14:26:21 -04005086 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005087
David Neto862b7d82018-06-14 18:48:37 -04005088 } else if (callee_name.startswith(kCompositeConstructFunctionPrefix)) {
David Netoab03f432017-11-03 17:00:44 -04005089
5090 // Generate an OpCompositeConstruct
5091 SPIRVOperandList Ops;
5092
5093 // The result type.
David Neto257c3892018-04-11 13:19:45 -04005094 Ops << MkId(lookupType(Call->getType()));
David Netoab03f432017-11-03 17:00:44 -04005095
5096 for (Use &use : Call->arg_operands()) {
David Neto257c3892018-04-11 13:19:45 -04005097 Ops << MkId(VMap[use.get()]);
David Netoab03f432017-11-03 17:00:44 -04005098 }
5099
5100 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005101 InsertPoint, new SPIRVInstruction(spv::OpCompositeConstruct,
5102 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005103
Alan Baker202c8c72018-08-13 13:47:44 -04005104 } else if (callee_name.startswith(clspv::ResourceAccessorFunction())) {
5105
5106 // We have already mapped the call's result value to an ID.
5107 // Don't generate any code now.
5108
5109 } else if (callee_name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04005110
5111 // We have already mapped the call's result value to an ID.
5112 // Don't generate any code now.
5113
David Neto22f144c2017-06-12 14:26:21 -04005114 } else {
5115 //
5116 // Generate OpFunctionCall.
5117 //
5118
5119 // Ops[0] = Result Type ID
5120 // Ops[1] = Callee Function ID
5121 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
5122 SPIRVOperandList Ops;
5123
David Neto862b7d82018-06-14 18:48:37 -04005124 Ops << MkId(lookupType(Call->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005125
5126 uint32_t CalleeID = VMap[Callee];
David Neto43568eb2017-10-13 18:25:25 -04005127 if (CalleeID == 0) {
5128 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04005129 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04005130 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
5131 // causes an infinite loop. Instead, go ahead and generate
5132 // the bad function call. A validator will catch the 0-Id.
5133 // llvm_unreachable("Can't translate function call");
5134 }
David Neto22f144c2017-06-12 14:26:21 -04005135
David Neto257c3892018-04-11 13:19:45 -04005136 Ops << MkId(CalleeID);
David Neto22f144c2017-06-12 14:26:21 -04005137
David Neto22f144c2017-06-12 14:26:21 -04005138 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5139 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04005140 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04005141 }
5142
David Neto87846742018-04-11 17:36:22 -04005143 auto *CallInst = new SPIRVInstruction(spv::OpFunctionCall,
5144 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005145 SPIRVInstList.insert(InsertPoint, CallInst);
5146 }
5147 }
5148 }
5149}
5150
David Neto1a1a0582017-07-07 12:01:44 -04005151void SPIRVProducerPass::HandleDeferredDecorations(const DataLayout &DL) {
Alan Baker202c8c72018-08-13 13:47:44 -04005152 if (getTypesNeedingArrayStride().empty() && LocalArgSpecIds.empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04005153 return;
David Netoc6f3ab22018-04-06 18:02:31 -04005154 }
David Neto1a1a0582017-07-07 12:01:44 -04005155
5156 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto1a1a0582017-07-07 12:01:44 -04005157
5158 // Find an iterator pointing just past the last decoration.
5159 bool seen_decorations = false;
5160 auto DecoInsertPoint =
5161 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
5162 [&seen_decorations](SPIRVInstruction *Inst) -> bool {
5163 const bool is_decoration =
5164 Inst->getOpcode() == spv::OpDecorate ||
5165 Inst->getOpcode() == spv::OpMemberDecorate;
5166 if (is_decoration) {
5167 seen_decorations = true;
5168 return false;
5169 } else {
5170 return seen_decorations;
5171 }
5172 });
5173
David Netoc6f3ab22018-04-06 18:02:31 -04005174 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
5175 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07005176 for (auto *type : getTypesNeedingArrayStride()) {
5177 Type *elemTy = nullptr;
5178 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
5179 elemTy = ptrTy->getElementType();
5180 } else if (auto* arrayTy = dyn_cast<ArrayType>(type)) {
5181 elemTy = arrayTy->getArrayElementType();
5182 } else if (auto* seqTy = dyn_cast<SequentialType>(type)) {
5183 elemTy = seqTy->getSequentialElementType();
5184 } else {
5185 errs() << "Unhandled strided type " << *type << "\n";
5186 llvm_unreachable("Unhandled strided type");
5187 }
David Neto1a1a0582017-07-07 12:01:44 -04005188
5189 // Ops[0] = Target ID
5190 // Ops[1] = Decoration (ArrayStride)
5191 // Ops[2] = Stride number (Literal Number)
5192 SPIRVOperandList Ops;
5193
David Neto85082642018-03-24 06:55:20 -07005194 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Neil Henning39672102017-09-29 14:33:13 +01005195 const uint32_t stride = static_cast<uint32_t>(DL.getTypeAllocSize(elemTy));
David Neto257c3892018-04-11 13:19:45 -04005196
5197 Ops << MkId(lookupType(type)) << MkNum(spv::DecorationArrayStride)
5198 << MkNum(stride);
David Neto1a1a0582017-07-07 12:01:44 -04005199
David Neto87846742018-04-11 17:36:22 -04005200 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto1a1a0582017-07-07 12:01:44 -04005201 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
5202 }
David Netoc6f3ab22018-04-06 18:02:31 -04005203
5204 // Emit SpecId decorations targeting the array size value.
Alan Baker202c8c72018-08-13 13:47:44 -04005205 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
5206 ++spec_id) {
5207 LocalArgInfo& arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04005208 SPIRVOperandList Ops;
5209 Ops << MkId(arg_info.array_size_id) << MkNum(spv::DecorationSpecId)
5210 << MkNum(arg_info.spec_id);
5211 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04005212 new SPIRVInstruction(spv::OpDecorate, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04005213 }
David Neto1a1a0582017-07-07 12:01:44 -04005214}
5215
David Neto22f144c2017-06-12 14:26:21 -04005216glsl::ExtInst SPIRVProducerPass::getExtInstEnum(StringRef Name) {
5217 return StringSwitch<glsl::ExtInst>(Name)
5218 .Case("_Z3absi", glsl::ExtInst::ExtInstSAbs)
5219 .Case("_Z3absDv2_i", glsl::ExtInst::ExtInstSAbs)
5220 .Case("_Z3absDv3_i", glsl::ExtInst::ExtInstSAbs)
5221 .Case("_Z3absDv4_i", glsl::ExtInst::ExtInstSAbs)
5222 .Case("_Z5clampiii", glsl::ExtInst::ExtInstSClamp)
5223 .Case("_Z5clampDv2_iS_S_", glsl::ExtInst::ExtInstSClamp)
5224 .Case("_Z5clampDv3_iS_S_", glsl::ExtInst::ExtInstSClamp)
5225 .Case("_Z5clampDv4_iS_S_", glsl::ExtInst::ExtInstSClamp)
5226 .Case("_Z5clampjjj", glsl::ExtInst::ExtInstUClamp)
5227 .Case("_Z5clampDv2_jS_S_", glsl::ExtInst::ExtInstUClamp)
5228 .Case("_Z5clampDv3_jS_S_", glsl::ExtInst::ExtInstUClamp)
5229 .Case("_Z5clampDv4_jS_S_", glsl::ExtInst::ExtInstUClamp)
5230 .Case("_Z5clampfff", glsl::ExtInst::ExtInstFClamp)
5231 .Case("_Z5clampDv2_fS_S_", glsl::ExtInst::ExtInstFClamp)
5232 .Case("_Z5clampDv3_fS_S_", glsl::ExtInst::ExtInstFClamp)
5233 .Case("_Z5clampDv4_fS_S_", glsl::ExtInst::ExtInstFClamp)
David Neto22f144c2017-06-12 14:26:21 -04005234 .Case("_Z3maxii", glsl::ExtInst::ExtInstSMax)
5235 .Case("_Z3maxDv2_iS_", glsl::ExtInst::ExtInstSMax)
5236 .Case("_Z3maxDv3_iS_", glsl::ExtInst::ExtInstSMax)
5237 .Case("_Z3maxDv4_iS_", glsl::ExtInst::ExtInstSMax)
5238 .Case("_Z3maxjj", glsl::ExtInst::ExtInstUMax)
5239 .Case("_Z3maxDv2_jS_", glsl::ExtInst::ExtInstUMax)
5240 .Case("_Z3maxDv3_jS_", glsl::ExtInst::ExtInstUMax)
5241 .Case("_Z3maxDv4_jS_", glsl::ExtInst::ExtInstUMax)
5242 .Case("_Z3maxff", glsl::ExtInst::ExtInstFMax)
5243 .Case("_Z3maxDv2_fS_", glsl::ExtInst::ExtInstFMax)
5244 .Case("_Z3maxDv3_fS_", glsl::ExtInst::ExtInstFMax)
5245 .Case("_Z3maxDv4_fS_", glsl::ExtInst::ExtInstFMax)
5246 .StartsWith("_Z4fmax", glsl::ExtInst::ExtInstFMax)
5247 .Case("_Z3minii", glsl::ExtInst::ExtInstSMin)
5248 .Case("_Z3minDv2_iS_", glsl::ExtInst::ExtInstSMin)
5249 .Case("_Z3minDv3_iS_", glsl::ExtInst::ExtInstSMin)
5250 .Case("_Z3minDv4_iS_", glsl::ExtInst::ExtInstSMin)
5251 .Case("_Z3minjj", glsl::ExtInst::ExtInstUMin)
5252 .Case("_Z3minDv2_jS_", glsl::ExtInst::ExtInstUMin)
5253 .Case("_Z3minDv3_jS_", glsl::ExtInst::ExtInstUMin)
5254 .Case("_Z3minDv4_jS_", glsl::ExtInst::ExtInstUMin)
5255 .Case("_Z3minff", glsl::ExtInst::ExtInstFMin)
5256 .Case("_Z3minDv2_fS_", glsl::ExtInst::ExtInstFMin)
5257 .Case("_Z3minDv3_fS_", glsl::ExtInst::ExtInstFMin)
5258 .Case("_Z3minDv4_fS_", glsl::ExtInst::ExtInstFMin)
5259 .StartsWith("_Z4fmin", glsl::ExtInst::ExtInstFMin)
5260 .StartsWith("_Z7degrees", glsl::ExtInst::ExtInstDegrees)
5261 .StartsWith("_Z7radians", glsl::ExtInst::ExtInstRadians)
5262 .StartsWith("_Z3mix", glsl::ExtInst::ExtInstFMix)
5263 .StartsWith("_Z4acos", glsl::ExtInst::ExtInstAcos)
5264 .StartsWith("_Z5acosh", glsl::ExtInst::ExtInstAcosh)
5265 .StartsWith("_Z4asin", glsl::ExtInst::ExtInstAsin)
5266 .StartsWith("_Z5asinh", glsl::ExtInst::ExtInstAsinh)
5267 .StartsWith("_Z4atan", glsl::ExtInst::ExtInstAtan)
5268 .StartsWith("_Z5atan2", glsl::ExtInst::ExtInstAtan2)
5269 .StartsWith("_Z5atanh", glsl::ExtInst::ExtInstAtanh)
5270 .StartsWith("_Z4ceil", glsl::ExtInst::ExtInstCeil)
5271 .StartsWith("_Z3sin", glsl::ExtInst::ExtInstSin)
5272 .StartsWith("_Z4sinh", glsl::ExtInst::ExtInstSinh)
5273 .StartsWith("_Z8half_sin", glsl::ExtInst::ExtInstSin)
5274 .StartsWith("_Z10native_sin", glsl::ExtInst::ExtInstSin)
5275 .StartsWith("_Z3cos", glsl::ExtInst::ExtInstCos)
5276 .StartsWith("_Z4cosh", glsl::ExtInst::ExtInstCosh)
5277 .StartsWith("_Z8half_cos", glsl::ExtInst::ExtInstCos)
5278 .StartsWith("_Z10native_cos", glsl::ExtInst::ExtInstCos)
5279 .StartsWith("_Z3tan", glsl::ExtInst::ExtInstTan)
5280 .StartsWith("_Z4tanh", glsl::ExtInst::ExtInstTanh)
5281 .StartsWith("_Z8half_tan", glsl::ExtInst::ExtInstTan)
5282 .StartsWith("_Z10native_tan", glsl::ExtInst::ExtInstTan)
5283 .StartsWith("_Z3exp", glsl::ExtInst::ExtInstExp)
5284 .StartsWith("_Z8half_exp", glsl::ExtInst::ExtInstExp)
5285 .StartsWith("_Z10native_exp", glsl::ExtInst::ExtInstExp)
5286 .StartsWith("_Z4exp2", glsl::ExtInst::ExtInstExp2)
5287 .StartsWith("_Z9half_exp2", glsl::ExtInst::ExtInstExp2)
5288 .StartsWith("_Z11native_exp2", glsl::ExtInst::ExtInstExp2)
5289 .StartsWith("_Z3log", glsl::ExtInst::ExtInstLog)
5290 .StartsWith("_Z8half_log", glsl::ExtInst::ExtInstLog)
5291 .StartsWith("_Z10native_log", glsl::ExtInst::ExtInstLog)
5292 .StartsWith("_Z4log2", glsl::ExtInst::ExtInstLog2)
5293 .StartsWith("_Z9half_log2", glsl::ExtInst::ExtInstLog2)
5294 .StartsWith("_Z11native_log2", glsl::ExtInst::ExtInstLog2)
5295 .StartsWith("_Z4fabs", glsl::ExtInst::ExtInstFAbs)
kpet3458e942018-10-03 14:35:21 +01005296 .StartsWith("_Z3fma", glsl::ExtInst::ExtInstFma)
David Neto22f144c2017-06-12 14:26:21 -04005297 .StartsWith("_Z5floor", glsl::ExtInst::ExtInstFloor)
5298 .StartsWith("_Z5ldexp", glsl::ExtInst::ExtInstLdexp)
5299 .StartsWith("_Z3pow", glsl::ExtInst::ExtInstPow)
5300 .StartsWith("_Z4powr", glsl::ExtInst::ExtInstPow)
5301 .StartsWith("_Z9half_powr", glsl::ExtInst::ExtInstPow)
5302 .StartsWith("_Z11native_powr", glsl::ExtInst::ExtInstPow)
5303 .StartsWith("_Z5round", glsl::ExtInst::ExtInstRound)
5304 .StartsWith("_Z4sqrt", glsl::ExtInst::ExtInstSqrt)
5305 .StartsWith("_Z9half_sqrt", glsl::ExtInst::ExtInstSqrt)
5306 .StartsWith("_Z11native_sqrt", glsl::ExtInst::ExtInstSqrt)
5307 .StartsWith("_Z5rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5308 .StartsWith("_Z10half_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5309 .StartsWith("_Z12native_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5310 .StartsWith("_Z5trunc", glsl::ExtInst::ExtInstTrunc)
5311 .StartsWith("_Z5frexp", glsl::ExtInst::ExtInstFrexp)
5312 .StartsWith("_Z4sign", glsl::ExtInst::ExtInstFSign)
5313 .StartsWith("_Z6length", glsl::ExtInst::ExtInstLength)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005314 .StartsWith("_Z11fast_length", glsl::ExtInst::ExtInstLength)
David Neto22f144c2017-06-12 14:26:21 -04005315 .StartsWith("_Z8distance", glsl::ExtInst::ExtInstDistance)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005316 .StartsWith("_Z13fast_distance", glsl::ExtInst::ExtInstDistance)
David Netoe9a03512017-10-16 10:08:27 -04005317 .StartsWith("_Z4step", glsl::ExtInst::ExtInstStep)
kpet6fd2a262018-10-03 14:48:01 +01005318 .StartsWith("_Z10smoothstep", glsl::ExtInst::ExtInstSmoothStep)
David Neto22f144c2017-06-12 14:26:21 -04005319 .Case("_Z5crossDv3_fS_", glsl::ExtInst::ExtInstCross)
5320 .StartsWith("_Z9normalize", glsl::ExtInst::ExtInstNormalize)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005321 .StartsWith("_Z14fast_normalize", glsl::ExtInst::ExtInstNormalize)
David Neto22f144c2017-06-12 14:26:21 -04005322 .StartsWith("llvm.fmuladd.", glsl::ExtInst::ExtInstFma)
5323 .Case("spirv.unpack.v2f16", glsl::ExtInst::ExtInstUnpackHalf2x16)
5324 .Case("spirv.pack.v2f16", glsl::ExtInst::ExtInstPackHalf2x16)
David Neto62653202017-10-16 19:05:18 -04005325 .Case("clspv.fract.f", glsl::ExtInst::ExtInstFract)
5326 .Case("clspv.fract.v2f", glsl::ExtInst::ExtInstFract)
5327 .Case("clspv.fract.v3f", glsl::ExtInst::ExtInstFract)
5328 .Case("clspv.fract.v4f", glsl::ExtInst::ExtInstFract)
David Neto3fbb4072017-10-16 11:28:14 -04005329 .Default(kGlslExtInstBad);
5330}
5331
5332glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(StringRef Name) {
5333 // Check indirect cases.
5334 return StringSwitch<glsl::ExtInst>(Name)
5335 .StartsWith("_Z3clz", glsl::ExtInst::ExtInstFindUMsb)
5336 // Use exact match on float arg because these need a multiply
5337 // of a constant of the right floating point type.
5338 .Case("_Z6acospif", glsl::ExtInst::ExtInstAcos)
5339 .Case("_Z6acospiDv2_f", glsl::ExtInst::ExtInstAcos)
5340 .Case("_Z6acospiDv3_f", glsl::ExtInst::ExtInstAcos)
5341 .Case("_Z6acospiDv4_f", glsl::ExtInst::ExtInstAcos)
5342 .Case("_Z6asinpif", glsl::ExtInst::ExtInstAsin)
5343 .Case("_Z6asinpiDv2_f", glsl::ExtInst::ExtInstAsin)
5344 .Case("_Z6asinpiDv3_f", glsl::ExtInst::ExtInstAsin)
5345 .Case("_Z6asinpiDv4_f", glsl::ExtInst::ExtInstAsin)
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005346 .Case("_Z6atanpif", glsl::ExtInst::ExtInstAtan)
5347 .Case("_Z6atanpiDv2_f", glsl::ExtInst::ExtInstAtan)
5348 .Case("_Z6atanpiDv3_f", glsl::ExtInst::ExtInstAtan)
5349 .Case("_Z6atanpiDv4_f", glsl::ExtInst::ExtInstAtan)
David Neto3fbb4072017-10-16 11:28:14 -04005350 .Case("_Z7atan2piff", glsl::ExtInst::ExtInstAtan2)
5351 .Case("_Z7atan2piDv2_fS_", glsl::ExtInst::ExtInstAtan2)
5352 .Case("_Z7atan2piDv3_fS_", glsl::ExtInst::ExtInstAtan2)
5353 .Case("_Z7atan2piDv4_fS_", glsl::ExtInst::ExtInstAtan2)
5354 .Default(kGlslExtInstBad);
5355}
5356
5357glsl::ExtInst SPIRVProducerPass::getDirectOrIndirectExtInstEnum(StringRef Name) {
5358 auto direct = getExtInstEnum(Name);
5359 if (direct != kGlslExtInstBad)
5360 return direct;
5361 return getIndirectExtInstEnum(Name);
David Neto22f144c2017-06-12 14:26:21 -04005362}
5363
5364void SPIRVProducerPass::PrintResID(SPIRVInstruction *Inst) {
5365 out << "%" << Inst->getResultID();
5366}
5367
5368void SPIRVProducerPass::PrintOpcode(SPIRVInstruction *Inst) {
5369 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5370 out << "\t" << spv::getOpName(Opcode);
5371}
5372
5373void SPIRVProducerPass::PrintOperand(SPIRVOperand *Op) {
5374 SPIRVOperandType OpTy = Op->getType();
5375 switch (OpTy) {
5376 default: {
5377 llvm_unreachable("Unsupported SPIRV Operand Type???");
5378 break;
5379 }
5380 case SPIRVOperandType::NUMBERID: {
5381 out << "%" << Op->getNumID();
5382 break;
5383 }
5384 case SPIRVOperandType::LITERAL_STRING: {
5385 out << "\"" << Op->getLiteralStr() << "\"";
5386 break;
5387 }
5388 case SPIRVOperandType::LITERAL_INTEGER: {
5389 // TODO: Handle LiteralNum carefully.
5390 for (auto Word : Op->getLiteralNum()) {
5391 out << Word;
5392 }
5393 break;
5394 }
5395 case SPIRVOperandType::LITERAL_FLOAT: {
5396 // TODO: Handle LiteralNum carefully.
5397 for (auto Word : Op->getLiteralNum()) {
5398 APFloat APF = APFloat(APFloat::IEEEsingle(), APInt(32, Word));
5399 SmallString<8> Str;
5400 APF.toString(Str, 6, 2);
5401 out << Str;
5402 }
5403 break;
5404 }
5405 }
5406}
5407
5408void SPIRVProducerPass::PrintCapability(SPIRVOperand *Op) {
5409 spv::Capability Cap = static_cast<spv::Capability>(Op->getNumID());
5410 out << spv::getCapabilityName(Cap);
5411}
5412
5413void SPIRVProducerPass::PrintExtInst(SPIRVOperand *Op) {
5414 auto LiteralNum = Op->getLiteralNum();
5415 glsl::ExtInst Ext = static_cast<glsl::ExtInst>(LiteralNum[0]);
5416 out << glsl::getExtInstName(Ext);
5417}
5418
5419void SPIRVProducerPass::PrintAddrModel(SPIRVOperand *Op) {
5420 spv::AddressingModel AddrModel =
5421 static_cast<spv::AddressingModel>(Op->getNumID());
5422 out << spv::getAddressingModelName(AddrModel);
5423}
5424
5425void SPIRVProducerPass::PrintMemModel(SPIRVOperand *Op) {
5426 spv::MemoryModel MemModel = static_cast<spv::MemoryModel>(Op->getNumID());
5427 out << spv::getMemoryModelName(MemModel);
5428}
5429
5430void SPIRVProducerPass::PrintExecModel(SPIRVOperand *Op) {
5431 spv::ExecutionModel ExecModel =
5432 static_cast<spv::ExecutionModel>(Op->getNumID());
5433 out << spv::getExecutionModelName(ExecModel);
5434}
5435
5436void SPIRVProducerPass::PrintExecMode(SPIRVOperand *Op) {
5437 spv::ExecutionMode ExecMode = static_cast<spv::ExecutionMode>(Op->getNumID());
5438 out << spv::getExecutionModeName(ExecMode);
5439}
5440
5441void SPIRVProducerPass::PrintSourceLanguage(SPIRVOperand *Op) {
5442 spv::SourceLanguage SourceLang = static_cast<spv::SourceLanguage>(Op->getNumID());
5443 out << spv::getSourceLanguageName(SourceLang);
5444}
5445
5446void SPIRVProducerPass::PrintFuncCtrl(SPIRVOperand *Op) {
5447 spv::FunctionControlMask FuncCtrl =
5448 static_cast<spv::FunctionControlMask>(Op->getNumID());
5449 out << spv::getFunctionControlName(FuncCtrl);
5450}
5451
5452void SPIRVProducerPass::PrintStorageClass(SPIRVOperand *Op) {
5453 spv::StorageClass StClass = static_cast<spv::StorageClass>(Op->getNumID());
5454 out << getStorageClassName(StClass);
5455}
5456
5457void SPIRVProducerPass::PrintDecoration(SPIRVOperand *Op) {
5458 spv::Decoration Deco = static_cast<spv::Decoration>(Op->getNumID());
5459 out << getDecorationName(Deco);
5460}
5461
5462void SPIRVProducerPass::PrintBuiltIn(SPIRVOperand *Op) {
5463 spv::BuiltIn BIn = static_cast<spv::BuiltIn>(Op->getNumID());
5464 out << getBuiltInName(BIn);
5465}
5466
5467void SPIRVProducerPass::PrintSelectionControl(SPIRVOperand *Op) {
5468 spv::SelectionControlMask BIn =
5469 static_cast<spv::SelectionControlMask>(Op->getNumID());
5470 out << getSelectionControlName(BIn);
5471}
5472
5473void SPIRVProducerPass::PrintLoopControl(SPIRVOperand *Op) {
5474 spv::LoopControlMask BIn = static_cast<spv::LoopControlMask>(Op->getNumID());
5475 out << getLoopControlName(BIn);
5476}
5477
5478void SPIRVProducerPass::PrintDimensionality(SPIRVOperand *Op) {
5479 spv::Dim DIM = static_cast<spv::Dim>(Op->getNumID());
5480 out << getDimName(DIM);
5481}
5482
5483void SPIRVProducerPass::PrintImageFormat(SPIRVOperand *Op) {
5484 spv::ImageFormat Format = static_cast<spv::ImageFormat>(Op->getNumID());
5485 out << getImageFormatName(Format);
5486}
5487
5488void SPIRVProducerPass::PrintMemoryAccess(SPIRVOperand *Op) {
5489 out << spv::getMemoryAccessName(
5490 static_cast<spv::MemoryAccessMask>(Op->getNumID()));
5491}
5492
5493void SPIRVProducerPass::PrintImageOperandsType(SPIRVOperand *Op) {
5494 auto LiteralNum = Op->getLiteralNum();
5495 spv::ImageOperandsMask Type =
5496 static_cast<spv::ImageOperandsMask>(LiteralNum[0]);
5497 out << getImageOperandsName(Type);
5498}
5499
5500void SPIRVProducerPass::WriteSPIRVAssembly() {
5501 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5502
5503 for (auto Inst : SPIRVInstList) {
5504 SPIRVOperandList Ops = Inst->getOperands();
5505 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5506
5507 switch (Opcode) {
5508 default: {
5509 llvm_unreachable("Unsupported SPIRV instruction");
5510 break;
5511 }
5512 case spv::OpCapability: {
5513 // Ops[0] = Capability
5514 PrintOpcode(Inst);
5515 out << " ";
5516 PrintCapability(Ops[0]);
5517 out << "\n";
5518 break;
5519 }
5520 case spv::OpMemoryModel: {
5521 // Ops[0] = Addressing Model
5522 // Ops[1] = Memory Model
5523 PrintOpcode(Inst);
5524 out << " ";
5525 PrintAddrModel(Ops[0]);
5526 out << " ";
5527 PrintMemModel(Ops[1]);
5528 out << "\n";
5529 break;
5530 }
5531 case spv::OpEntryPoint: {
5532 // Ops[0] = Execution Model
5533 // Ops[1] = EntryPoint ID
5534 // Ops[2] = Name (Literal String)
5535 // Ops[3] ... Ops[n] = Interface ID
5536 PrintOpcode(Inst);
5537 out << " ";
5538 PrintExecModel(Ops[0]);
5539 for (uint32_t i = 1; i < Ops.size(); i++) {
5540 out << " ";
5541 PrintOperand(Ops[i]);
5542 }
5543 out << "\n";
5544 break;
5545 }
5546 case spv::OpExecutionMode: {
5547 // Ops[0] = Entry Point ID
5548 // Ops[1] = Execution Mode
5549 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
5550 PrintOpcode(Inst);
5551 out << " ";
5552 PrintOperand(Ops[0]);
5553 out << " ";
5554 PrintExecMode(Ops[1]);
5555 for (uint32_t i = 2; i < Ops.size(); i++) {
5556 out << " ";
5557 PrintOperand(Ops[i]);
5558 }
5559 out << "\n";
5560 break;
5561 }
5562 case spv::OpSource: {
5563 // Ops[0] = SourceLanguage ID
5564 // Ops[1] = Version (LiteralNum)
5565 PrintOpcode(Inst);
5566 out << " ";
5567 PrintSourceLanguage(Ops[0]);
5568 out << " ";
5569 PrintOperand(Ops[1]);
5570 out << "\n";
5571 break;
5572 }
5573 case spv::OpDecorate: {
5574 // Ops[0] = Target ID
5575 // Ops[1] = Decoration (Block or BufferBlock)
5576 // Ops[2] ... Ops[n] = Optional literals according to Decoration
5577 PrintOpcode(Inst);
5578 out << " ";
5579 PrintOperand(Ops[0]);
5580 out << " ";
5581 PrintDecoration(Ops[1]);
5582 // Handle BuiltIn OpDecorate specially.
5583 if (Ops[1]->getNumID() == spv::DecorationBuiltIn) {
5584 out << " ";
5585 PrintBuiltIn(Ops[2]);
5586 } else {
5587 for (uint32_t i = 2; i < Ops.size(); i++) {
5588 out << " ";
5589 PrintOperand(Ops[i]);
5590 }
5591 }
5592 out << "\n";
5593 break;
5594 }
5595 case spv::OpMemberDecorate: {
5596 // Ops[0] = Structure Type ID
5597 // Ops[1] = Member Index(Literal Number)
5598 // Ops[2] = Decoration
5599 // Ops[3] ... Ops[n] = Optional literals according to Decoration
5600 PrintOpcode(Inst);
5601 out << " ";
5602 PrintOperand(Ops[0]);
5603 out << " ";
5604 PrintOperand(Ops[1]);
5605 out << " ";
5606 PrintDecoration(Ops[2]);
5607 for (uint32_t i = 3; i < Ops.size(); i++) {
5608 out << " ";
5609 PrintOperand(Ops[i]);
5610 }
5611 out << "\n";
5612 break;
5613 }
5614 case spv::OpTypePointer: {
5615 // Ops[0] = Storage Class
5616 // Ops[1] = Element Type ID
5617 PrintResID(Inst);
5618 out << " = ";
5619 PrintOpcode(Inst);
5620 out << " ";
5621 PrintStorageClass(Ops[0]);
5622 out << " ";
5623 PrintOperand(Ops[1]);
5624 out << "\n";
5625 break;
5626 }
5627 case spv::OpTypeImage: {
5628 // Ops[0] = Sampled Type ID
5629 // Ops[1] = Dim ID
5630 // Ops[2] = Depth (Literal Number)
5631 // Ops[3] = Arrayed (Literal Number)
5632 // Ops[4] = MS (Literal Number)
5633 // Ops[5] = Sampled (Literal Number)
5634 // Ops[6] = Image Format ID
5635 PrintResID(Inst);
5636 out << " = ";
5637 PrintOpcode(Inst);
5638 out << " ";
5639 PrintOperand(Ops[0]);
5640 out << " ";
5641 PrintDimensionality(Ops[1]);
5642 out << " ";
5643 PrintOperand(Ops[2]);
5644 out << " ";
5645 PrintOperand(Ops[3]);
5646 out << " ";
5647 PrintOperand(Ops[4]);
5648 out << " ";
5649 PrintOperand(Ops[5]);
5650 out << " ";
5651 PrintImageFormat(Ops[6]);
5652 out << "\n";
5653 break;
5654 }
5655 case spv::OpFunction: {
5656 // Ops[0] : Result Type ID
5657 // Ops[1] : Function Control
5658 // Ops[2] : Function Type ID
5659 PrintResID(Inst);
5660 out << " = ";
5661 PrintOpcode(Inst);
5662 out << " ";
5663 PrintOperand(Ops[0]);
5664 out << " ";
5665 PrintFuncCtrl(Ops[1]);
5666 out << " ";
5667 PrintOperand(Ops[2]);
5668 out << "\n";
5669 break;
5670 }
5671 case spv::OpSelectionMerge: {
5672 // Ops[0] = Merge Block ID
5673 // Ops[1] = Selection Control
5674 PrintOpcode(Inst);
5675 out << " ";
5676 PrintOperand(Ops[0]);
5677 out << " ";
5678 PrintSelectionControl(Ops[1]);
5679 out << "\n";
5680 break;
5681 }
5682 case spv::OpLoopMerge: {
5683 // Ops[0] = Merge Block ID
5684 // Ops[1] = Continue Target ID
5685 // Ops[2] = Selection Control
5686 PrintOpcode(Inst);
5687 out << " ";
5688 PrintOperand(Ops[0]);
5689 out << " ";
5690 PrintOperand(Ops[1]);
5691 out << " ";
5692 PrintLoopControl(Ops[2]);
5693 out << "\n";
5694 break;
5695 }
5696 case spv::OpImageSampleExplicitLod: {
5697 // Ops[0] = Result Type ID
5698 // Ops[1] = Sampled Image ID
5699 // Ops[2] = Coordinate ID
5700 // Ops[3] = Image Operands Type ID
5701 // Ops[4] ... Ops[n] = Operands ID
5702 PrintResID(Inst);
5703 out << " = ";
5704 PrintOpcode(Inst);
5705 for (uint32_t i = 0; i < 3; i++) {
5706 out << " ";
5707 PrintOperand(Ops[i]);
5708 }
5709 out << " ";
5710 PrintImageOperandsType(Ops[3]);
5711 for (uint32_t i = 4; i < Ops.size(); i++) {
5712 out << " ";
5713 PrintOperand(Ops[i]);
5714 }
5715 out << "\n";
5716 break;
5717 }
5718 case spv::OpVariable: {
5719 // Ops[0] : Result Type ID
5720 // Ops[1] : Storage Class
5721 // Ops[2] ... Ops[n] = Initializer IDs
5722 PrintResID(Inst);
5723 out << " = ";
5724 PrintOpcode(Inst);
5725 out << " ";
5726 PrintOperand(Ops[0]);
5727 out << " ";
5728 PrintStorageClass(Ops[1]);
5729 for (uint32_t i = 2; i < Ops.size(); i++) {
5730 out << " ";
5731 PrintOperand(Ops[i]);
5732 }
5733 out << "\n";
5734 break;
5735 }
5736 case spv::OpExtInst: {
5737 // Ops[0] = Result Type ID
5738 // Ops[1] = Set ID (OpExtInstImport ID)
5739 // Ops[2] = Instruction Number (Literal Number)
5740 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5741 PrintResID(Inst);
5742 out << " = ";
5743 PrintOpcode(Inst);
5744 out << " ";
5745 PrintOperand(Ops[0]);
5746 out << " ";
5747 PrintOperand(Ops[1]);
5748 out << " ";
5749 PrintExtInst(Ops[2]);
5750 for (uint32_t i = 3; i < Ops.size(); i++) {
5751 out << " ";
5752 PrintOperand(Ops[i]);
5753 }
5754 out << "\n";
5755 break;
5756 }
5757 case spv::OpCopyMemory: {
5758 // Ops[0] = Addressing Model
5759 // Ops[1] = Memory Model
5760 PrintOpcode(Inst);
5761 out << " ";
5762 PrintOperand(Ops[0]);
5763 out << " ";
5764 PrintOperand(Ops[1]);
5765 out << " ";
5766 PrintMemoryAccess(Ops[2]);
5767 out << " ";
5768 PrintOperand(Ops[3]);
5769 out << "\n";
5770 break;
5771 }
5772 case spv::OpExtension:
5773 case spv::OpControlBarrier:
5774 case spv::OpMemoryBarrier:
5775 case spv::OpBranch:
5776 case spv::OpBranchConditional:
5777 case spv::OpStore:
5778 case spv::OpImageWrite:
5779 case spv::OpReturnValue:
5780 case spv::OpReturn:
5781 case spv::OpFunctionEnd: {
5782 PrintOpcode(Inst);
5783 for (uint32_t i = 0; i < Ops.size(); i++) {
5784 out << " ";
5785 PrintOperand(Ops[i]);
5786 }
5787 out << "\n";
5788 break;
5789 }
5790 case spv::OpExtInstImport:
5791 case spv::OpTypeRuntimeArray:
5792 case spv::OpTypeStruct:
5793 case spv::OpTypeSampler:
5794 case spv::OpTypeSampledImage:
5795 case spv::OpTypeInt:
5796 case spv::OpTypeFloat:
5797 case spv::OpTypeArray:
5798 case spv::OpTypeVector:
5799 case spv::OpTypeBool:
5800 case spv::OpTypeVoid:
5801 case spv::OpTypeFunction:
5802 case spv::OpFunctionParameter:
5803 case spv::OpLabel:
5804 case spv::OpPhi:
5805 case spv::OpLoad:
5806 case spv::OpSelect:
5807 case spv::OpAccessChain:
5808 case spv::OpPtrAccessChain:
5809 case spv::OpInBoundsAccessChain:
5810 case spv::OpUConvert:
5811 case spv::OpSConvert:
5812 case spv::OpConvertFToU:
5813 case spv::OpConvertFToS:
5814 case spv::OpConvertUToF:
5815 case spv::OpConvertSToF:
5816 case spv::OpFConvert:
5817 case spv::OpConvertPtrToU:
5818 case spv::OpConvertUToPtr:
5819 case spv::OpBitcast:
5820 case spv::OpIAdd:
5821 case spv::OpFAdd:
5822 case spv::OpISub:
5823 case spv::OpFSub:
5824 case spv::OpIMul:
5825 case spv::OpFMul:
5826 case spv::OpUDiv:
5827 case spv::OpSDiv:
5828 case spv::OpFDiv:
5829 case spv::OpUMod:
5830 case spv::OpSRem:
5831 case spv::OpFRem:
5832 case spv::OpBitwiseOr:
5833 case spv::OpBitwiseXor:
5834 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005835 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005836 case spv::OpShiftLeftLogical:
5837 case spv::OpShiftRightLogical:
5838 case spv::OpShiftRightArithmetic:
5839 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04005840 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04005841 case spv::OpCompositeExtract:
5842 case spv::OpVectorExtractDynamic:
5843 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04005844 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04005845 case spv::OpVectorInsertDynamic:
5846 case spv::OpVectorShuffle:
5847 case spv::OpIEqual:
5848 case spv::OpINotEqual:
5849 case spv::OpUGreaterThan:
5850 case spv::OpUGreaterThanEqual:
5851 case spv::OpULessThan:
5852 case spv::OpULessThanEqual:
5853 case spv::OpSGreaterThan:
5854 case spv::OpSGreaterThanEqual:
5855 case spv::OpSLessThan:
5856 case spv::OpSLessThanEqual:
5857 case spv::OpFOrdEqual:
5858 case spv::OpFOrdGreaterThan:
5859 case spv::OpFOrdGreaterThanEqual:
5860 case spv::OpFOrdLessThan:
5861 case spv::OpFOrdLessThanEqual:
5862 case spv::OpFOrdNotEqual:
5863 case spv::OpFUnordEqual:
5864 case spv::OpFUnordGreaterThan:
5865 case spv::OpFUnordGreaterThanEqual:
5866 case spv::OpFUnordLessThan:
5867 case spv::OpFUnordLessThanEqual:
5868 case spv::OpFUnordNotEqual:
5869 case spv::OpSampledImage:
5870 case spv::OpFunctionCall:
5871 case spv::OpConstantTrue:
5872 case spv::OpConstantFalse:
5873 case spv::OpConstant:
5874 case spv::OpSpecConstant:
5875 case spv::OpConstantComposite:
5876 case spv::OpSpecConstantComposite:
5877 case spv::OpConstantNull:
5878 case spv::OpLogicalOr:
5879 case spv::OpLogicalAnd:
5880 case spv::OpLogicalNot:
5881 case spv::OpLogicalNotEqual:
5882 case spv::OpUndef:
5883 case spv::OpIsInf:
5884 case spv::OpIsNan:
5885 case spv::OpAny:
5886 case spv::OpAll:
David Neto5c22a252018-03-15 16:07:41 -04005887 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04005888 case spv::OpAtomicIAdd:
5889 case spv::OpAtomicISub:
5890 case spv::OpAtomicExchange:
5891 case spv::OpAtomicIIncrement:
5892 case spv::OpAtomicIDecrement:
5893 case spv::OpAtomicCompareExchange:
5894 case spv::OpAtomicUMin:
5895 case spv::OpAtomicSMin:
5896 case spv::OpAtomicUMax:
5897 case spv::OpAtomicSMax:
5898 case spv::OpAtomicAnd:
5899 case spv::OpAtomicOr:
5900 case spv::OpAtomicXor:
5901 case spv::OpDot: {
5902 PrintResID(Inst);
5903 out << " = ";
5904 PrintOpcode(Inst);
5905 for (uint32_t i = 0; i < Ops.size(); i++) {
5906 out << " ";
5907 PrintOperand(Ops[i]);
5908 }
5909 out << "\n";
5910 break;
5911 }
5912 }
5913 }
5914}
5915
5916void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04005917 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04005918}
5919
5920void SPIRVProducerPass::WriteResultID(SPIRVInstruction *Inst) {
5921 WriteOneWord(Inst->getResultID());
5922}
5923
5924void SPIRVProducerPass::WriteWordCountAndOpcode(SPIRVInstruction *Inst) {
5925 // High 16 bit : Word Count
5926 // Low 16 bit : Opcode
5927 uint32_t Word = Inst->getOpcode();
David Netoee2660d2018-06-28 16:31:29 -04005928 const uint32_t count = Inst->getWordCount();
5929 if (count > 65535) {
5930 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
5931 llvm_unreachable("Word count too high");
5932 }
David Neto22f144c2017-06-12 14:26:21 -04005933 Word |= Inst->getWordCount() << 16;
5934 WriteOneWord(Word);
5935}
5936
5937void SPIRVProducerPass::WriteOperand(SPIRVOperand *Op) {
5938 SPIRVOperandType OpTy = Op->getType();
5939 switch (OpTy) {
5940 default: {
5941 llvm_unreachable("Unsupported SPIRV Operand Type???");
5942 break;
5943 }
5944 case SPIRVOperandType::NUMBERID: {
5945 WriteOneWord(Op->getNumID());
5946 break;
5947 }
5948 case SPIRVOperandType::LITERAL_STRING: {
5949 std::string Str = Op->getLiteralStr();
5950 const char *Data = Str.c_str();
5951 size_t WordSize = Str.size() / 4;
5952 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
5953 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
5954 }
5955
5956 uint32_t Remainder = Str.size() % 4;
5957 uint32_t LastWord = 0;
5958 if (Remainder) {
5959 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
5960 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
5961 }
5962 }
5963
5964 WriteOneWord(LastWord);
5965 break;
5966 }
5967 case SPIRVOperandType::LITERAL_INTEGER:
5968 case SPIRVOperandType::LITERAL_FLOAT: {
5969 auto LiteralNum = Op->getLiteralNum();
5970 // TODO: Handle LiteranNum carefully.
5971 for (auto Word : LiteralNum) {
5972 WriteOneWord(Word);
5973 }
5974 break;
5975 }
5976 }
5977}
5978
5979void SPIRVProducerPass::WriteSPIRVBinary() {
5980 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5981
5982 for (auto Inst : SPIRVInstList) {
David Netoc6f3ab22018-04-06 18:02:31 -04005983 SPIRVOperandList Ops{Inst->getOperands()};
David Neto22f144c2017-06-12 14:26:21 -04005984 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5985
5986 switch (Opcode) {
5987 default: {
David Neto5c22a252018-03-15 16:07:41 -04005988 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04005989 llvm_unreachable("Unsupported SPIRV instruction");
5990 break;
5991 }
5992 case spv::OpCapability:
5993 case spv::OpExtension:
5994 case spv::OpMemoryModel:
5995 case spv::OpEntryPoint:
5996 case spv::OpExecutionMode:
5997 case spv::OpSource:
5998 case spv::OpDecorate:
5999 case spv::OpMemberDecorate:
6000 case spv::OpBranch:
6001 case spv::OpBranchConditional:
6002 case spv::OpSelectionMerge:
6003 case spv::OpLoopMerge:
6004 case spv::OpStore:
6005 case spv::OpImageWrite:
6006 case spv::OpReturnValue:
6007 case spv::OpControlBarrier:
6008 case spv::OpMemoryBarrier:
6009 case spv::OpReturn:
6010 case spv::OpFunctionEnd:
6011 case spv::OpCopyMemory: {
6012 WriteWordCountAndOpcode(Inst);
6013 for (uint32_t i = 0; i < Ops.size(); i++) {
6014 WriteOperand(Ops[i]);
6015 }
6016 break;
6017 }
6018 case spv::OpTypeBool:
6019 case spv::OpTypeVoid:
6020 case spv::OpTypeSampler:
6021 case spv::OpLabel:
6022 case spv::OpExtInstImport:
6023 case spv::OpTypePointer:
6024 case spv::OpTypeRuntimeArray:
6025 case spv::OpTypeStruct:
6026 case spv::OpTypeImage:
6027 case spv::OpTypeSampledImage:
6028 case spv::OpTypeInt:
6029 case spv::OpTypeFloat:
6030 case spv::OpTypeArray:
6031 case spv::OpTypeVector:
6032 case spv::OpTypeFunction: {
6033 WriteWordCountAndOpcode(Inst);
6034 WriteResultID(Inst);
6035 for (uint32_t i = 0; i < Ops.size(); i++) {
6036 WriteOperand(Ops[i]);
6037 }
6038 break;
6039 }
6040 case spv::OpFunction:
6041 case spv::OpFunctionParameter:
6042 case spv::OpAccessChain:
6043 case spv::OpPtrAccessChain:
6044 case spv::OpInBoundsAccessChain:
6045 case spv::OpUConvert:
6046 case spv::OpSConvert:
6047 case spv::OpConvertFToU:
6048 case spv::OpConvertFToS:
6049 case spv::OpConvertUToF:
6050 case spv::OpConvertSToF:
6051 case spv::OpFConvert:
6052 case spv::OpConvertPtrToU:
6053 case spv::OpConvertUToPtr:
6054 case spv::OpBitcast:
6055 case spv::OpIAdd:
6056 case spv::OpFAdd:
6057 case spv::OpISub:
6058 case spv::OpFSub:
6059 case spv::OpIMul:
6060 case spv::OpFMul:
6061 case spv::OpUDiv:
6062 case spv::OpSDiv:
6063 case spv::OpFDiv:
6064 case spv::OpUMod:
6065 case spv::OpSRem:
6066 case spv::OpFRem:
6067 case spv::OpBitwiseOr:
6068 case spv::OpBitwiseXor:
6069 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04006070 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04006071 case spv::OpShiftLeftLogical:
6072 case spv::OpShiftRightLogical:
6073 case spv::OpShiftRightArithmetic:
6074 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04006075 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04006076 case spv::OpCompositeExtract:
6077 case spv::OpVectorExtractDynamic:
6078 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04006079 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04006080 case spv::OpVectorInsertDynamic:
6081 case spv::OpVectorShuffle:
6082 case spv::OpIEqual:
6083 case spv::OpINotEqual:
6084 case spv::OpUGreaterThan:
6085 case spv::OpUGreaterThanEqual:
6086 case spv::OpULessThan:
6087 case spv::OpULessThanEqual:
6088 case spv::OpSGreaterThan:
6089 case spv::OpSGreaterThanEqual:
6090 case spv::OpSLessThan:
6091 case spv::OpSLessThanEqual:
6092 case spv::OpFOrdEqual:
6093 case spv::OpFOrdGreaterThan:
6094 case spv::OpFOrdGreaterThanEqual:
6095 case spv::OpFOrdLessThan:
6096 case spv::OpFOrdLessThanEqual:
6097 case spv::OpFOrdNotEqual:
6098 case spv::OpFUnordEqual:
6099 case spv::OpFUnordGreaterThan:
6100 case spv::OpFUnordGreaterThanEqual:
6101 case spv::OpFUnordLessThan:
6102 case spv::OpFUnordLessThanEqual:
6103 case spv::OpFUnordNotEqual:
6104 case spv::OpExtInst:
6105 case spv::OpIsInf:
6106 case spv::OpIsNan:
6107 case spv::OpAny:
6108 case spv::OpAll:
6109 case spv::OpUndef:
6110 case spv::OpConstantNull:
6111 case spv::OpLogicalOr:
6112 case spv::OpLogicalAnd:
6113 case spv::OpLogicalNot:
6114 case spv::OpLogicalNotEqual:
6115 case spv::OpConstantComposite:
6116 case spv::OpSpecConstantComposite:
6117 case spv::OpConstantTrue:
6118 case spv::OpConstantFalse:
6119 case spv::OpConstant:
6120 case spv::OpSpecConstant:
6121 case spv::OpVariable:
6122 case spv::OpFunctionCall:
6123 case spv::OpSampledImage:
6124 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04006125 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04006126 case spv::OpSelect:
6127 case spv::OpPhi:
6128 case spv::OpLoad:
6129 case spv::OpAtomicIAdd:
6130 case spv::OpAtomicISub:
6131 case spv::OpAtomicExchange:
6132 case spv::OpAtomicIIncrement:
6133 case spv::OpAtomicIDecrement:
6134 case spv::OpAtomicCompareExchange:
6135 case spv::OpAtomicUMin:
6136 case spv::OpAtomicSMin:
6137 case spv::OpAtomicUMax:
6138 case spv::OpAtomicSMax:
6139 case spv::OpAtomicAnd:
6140 case spv::OpAtomicOr:
6141 case spv::OpAtomicXor:
6142 case spv::OpDot: {
6143 WriteWordCountAndOpcode(Inst);
6144 WriteOperand(Ops[0]);
6145 WriteResultID(Inst);
6146 for (uint32_t i = 1; i < Ops.size(); i++) {
6147 WriteOperand(Ops[i]);
6148 }
6149 break;
6150 }
6151 }
6152 }
6153}
Alan Baker9bf93fb2018-08-28 16:59:26 -04006154
6155bool SPIRVProducerPass::IsTypeNullable(const Type* type) const {
6156 switch (type->getTypeID()) {
6157 case Type::HalfTyID:
6158 case Type::FloatTyID:
6159 case Type::DoubleTyID:
6160 case Type::IntegerTyID:
6161 case Type::VectorTyID:
6162 return true;
6163 case Type::PointerTyID: {
6164 const PointerType *pointer_type = cast<PointerType>(type);
6165 if (pointer_type->getPointerAddressSpace() !=
6166 AddressSpace::UniformConstant) {
6167 auto pointee_type = pointer_type->getPointerElementType();
6168 if (pointee_type->isStructTy() &&
6169 cast<StructType>(pointee_type)->isOpaque()) {
6170 // Images and samplers are not nullable.
6171 return false;
6172 }
6173 }
6174 return true;
6175 }
6176 case Type::ArrayTyID:
6177 return IsTypeNullable(cast<CompositeType>(type)->getTypeAtIndex(0u));
6178 case Type::StructTyID: {
6179 const StructType* struct_type = cast<StructType>(type);
6180 // Images and samplers are not nullable.
6181 if (struct_type->isOpaque()) return false;
6182 for (const auto element : struct_type->elements()) {
6183 if (!IsTypeNullable(element)) return false;
6184 }
6185 return true;
6186 }
6187 default:
6188 return false;
6189 }
6190}