blob: 6bbdc3ad922c761a297fec9a0fa5712a3f54a0e6 [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>
21
David Neto5c22a252018-03-15 16:07:41 -040022#include <unordered_set>
David Neto482550a2018-03-24 05:21:07 -070023#include <clspv/Option.h>
David Neto22f144c2017-06-12 14:26:21 -040024#include <clspv/Passes.h>
25
26#include <llvm/ADT/StringSwitch.h>
27#include <llvm/ADT/UniqueVector.h>
28#include <llvm/Analysis/LoopInfo.h>
29#include <llvm/IR/Constants.h>
30#include <llvm/IR/Dominators.h>
31#include <llvm/IR/Instructions.h>
32#include <llvm/IR/Metadata.h>
33#include <llvm/IR/Module.h>
34#include <llvm/Pass.h>
David Netocd8ca5f2017-10-02 23:34:11 -040035#include <llvm/Support/CommandLine.h>
David Neto22f144c2017-06-12 14:26:21 -040036#include <llvm/Support/raw_ostream.h>
37#include <llvm/Transforms/Utils/Cloning.h>
38
David Neto85082642018-03-24 06:55:20 -070039#include "spirv/1.0/spirv.hpp"
40#include "clspv/AddressSpace.h"
41#include "clspv/spirv_c_strings.hpp"
42#include "clspv/spirv_glsl.hpp"
David Neto22f144c2017-06-12 14:26:21 -040043
David Neto4feb7a42017-10-06 17:29:42 -040044#include "ArgKind.h"
David Neto85082642018-03-24 06:55:20 -070045#include "ConstantEmitter.h"
David Neto48f56a42017-10-06 16:44:25 -040046
David Neto22f144c2017-06-12 14:26:21 -040047#include <list>
David Neto0676e6f2017-07-11 18:47:44 -040048#include <iomanip>
David Neto26aaf622017-10-23 18:11:53 -040049#include <set>
David Neto0676e6f2017-07-11 18:47:44 -040050#include <sstream>
David Neto257c3892018-04-11 13:19:45 -040051#include <string>
David Neto26aaf622017-10-23 18:11:53 -040052#include <tuple>
David Neto44795152017-07-13 15:45:28 -040053#include <utility>
David Neto22f144c2017-06-12 14:26:21 -040054
55#if defined(_MSC_VER)
56#pragma warning(pop)
57#endif
58
59using namespace llvm;
60using namespace clspv;
David Neto156783e2017-07-05 15:39:41 -040061using namespace mdconst;
David Neto22f144c2017-06-12 14:26:21 -040062
63namespace {
David Netocd8ca5f2017-10-02 23:34:11 -040064
David Neto3fbb4072017-10-16 11:28:14 -040065// The value of 1/pi. This value is from MSDN
66// https://msdn.microsoft.com/en-us/library/4hwaceh6.aspx
67const double kOneOverPi = 0.318309886183790671538;
68const glsl::ExtInst kGlslExtInstBad = static_cast<glsl::ExtInst>(0);
69
David Netoab03f432017-11-03 17:00:44 -040070const char* kCompositeConstructFunctionPrefix = "clspv.composite_construct.";
71
David Neto22f144c2017-06-12 14:26:21 -040072enum SPIRVOperandType {
73 NUMBERID,
74 LITERAL_INTEGER,
75 LITERAL_STRING,
76 LITERAL_FLOAT
77};
78
79struct SPIRVOperand {
80 explicit SPIRVOperand(SPIRVOperandType Ty, uint32_t Num)
81 : Type(Ty), LiteralNum(1, Num) {}
82 explicit SPIRVOperand(SPIRVOperandType Ty, const char *Str)
83 : Type(Ty), LiteralStr(Str) {}
84 explicit SPIRVOperand(SPIRVOperandType Ty, StringRef Str)
85 : Type(Ty), LiteralStr(Str) {}
86 explicit SPIRVOperand(SPIRVOperandType Ty, ArrayRef<uint32_t> NumVec)
87 : Type(Ty), LiteralNum(NumVec.begin(), NumVec.end()) {}
88
89 SPIRVOperandType getType() { return Type; };
90 uint32_t getNumID() { return LiteralNum[0]; };
91 std::string getLiteralStr() { return LiteralStr; };
92 ArrayRef<uint32_t> getLiteralNum() { return LiteralNum; };
93
David Neto87846742018-04-11 17:36:22 -040094 uint32_t GetNumWords() const {
95 switch (Type) {
96 case NUMBERID:
97 return 1;
98 case LITERAL_INTEGER:
99 case LITERAL_FLOAT:
100 return LiteralNum.size();
101 case LITERAL_STRING:
102 // Account for the terminating null character.
103 return (LiteralStr.size() + 4) / 4;
104 }
105 llvm_unreachable("Unhandled case in SPIRVOperand::GetNumWords()");
106 }
107
David Neto22f144c2017-06-12 14:26:21 -0400108private:
109 SPIRVOperandType Type;
110 std::string LiteralStr;
111 SmallVector<uint32_t, 4> LiteralNum;
112};
113
David Netoc6f3ab22018-04-06 18:02:31 -0400114class SPIRVOperandList {
115public:
116 SPIRVOperandList() {}
117 SPIRVOperandList(const SPIRVOperandList& other) = delete;
118 SPIRVOperandList(SPIRVOperandList&& other) {
119 contents_ = std::move(other.contents_);
120 other.contents_.clear();
121 }
122 SPIRVOperandList(ArrayRef<SPIRVOperand *> init)
123 : contents_(init.begin(), init.end()) {}
124 operator ArrayRef<SPIRVOperand *>() { return contents_; }
125 void push_back(SPIRVOperand *op) { contents_.push_back(op); }
126 void clear() { contents_.clear();}
127 size_t size() const { return contents_.size(); }
128 SPIRVOperand *&operator[](size_t i) { return contents_[i]; }
129
David Neto87846742018-04-11 17:36:22 -0400130 const SmallVector<SPIRVOperand *, 8> &getOperands() const {
131 return contents_;
132 }
133
David Netoc6f3ab22018-04-06 18:02:31 -0400134private:
135 SmallVector<SPIRVOperand *,8> contents_;
136};
137
138SPIRVOperandList &operator<<(SPIRVOperandList &list, SPIRVOperand *elem) {
139 list.push_back(elem);
140 return list;
141}
142
143SPIRVOperand* MkNum(uint32_t num) {
144 return new SPIRVOperand(LITERAL_INTEGER, num);
145}
David Neto257c3892018-04-11 13:19:45 -0400146SPIRVOperand* MkInteger(ArrayRef<uint32_t> num_vec) {
147 return new SPIRVOperand(LITERAL_INTEGER, num_vec);
148}
149SPIRVOperand* MkFloat(ArrayRef<uint32_t> num_vec) {
150 return new SPIRVOperand(LITERAL_FLOAT, num_vec);
151}
David Netoc6f3ab22018-04-06 18:02:31 -0400152SPIRVOperand* MkId(uint32_t id) {
153 return new SPIRVOperand(NUMBERID, id);
154}
David Neto257c3892018-04-11 13:19:45 -0400155SPIRVOperand* MkString(StringRef str) {
156 return new SPIRVOperand(LITERAL_STRING, str);
157}
David Netoc6f3ab22018-04-06 18:02:31 -0400158
David Neto22f144c2017-06-12 14:26:21 -0400159struct SPIRVInstruction {
David Neto87846742018-04-11 17:36:22 -0400160 // Create an instruction with an opcode and no result ID, and with the given
161 // operands. This computes its own word count.
162 explicit SPIRVInstruction(spv::Op Opc, ArrayRef<SPIRVOperand *> Ops)
163 : WordCount(1), Opcode(static_cast<uint16_t>(Opc)), ResultID(0),
164 Operands(Ops.begin(), Ops.end()) {
165 for (auto *operand : Ops) {
166 WordCount += operand->GetNumWords();
167 }
168 }
169 // Create an instruction with an opcode and a no-zero result ID, and
170 // with the given operands. This computes its own word count.
171 explicit SPIRVInstruction(spv::Op Opc, uint32_t ResID,
David Neto22f144c2017-06-12 14:26:21 -0400172 ArrayRef<SPIRVOperand *> Ops)
David Neto87846742018-04-11 17:36:22 -0400173 : WordCount(2), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID),
174 Operands(Ops.begin(), Ops.end()) {
175 if (ResID == 0) {
176 llvm_unreachable("Result ID of 0 was provided");
177 }
178 for (auto *operand : Ops) {
179 WordCount += operand->GetNumWords();
180 }
181 }
David Neto22f144c2017-06-12 14:26:21 -0400182
183 uint16_t getWordCount() const { return WordCount; }
184 uint16_t getOpcode() const { return Opcode; }
185 uint32_t getResultID() const { return ResultID; }
186 ArrayRef<SPIRVOperand *> getOperands() const { return Operands; }
187
188private:
189 uint16_t WordCount;
190 uint16_t Opcode;
191 uint32_t ResultID;
192 SmallVector<SPIRVOperand *, 4> Operands;
193};
194
195struct SPIRVProducerPass final : public ModulePass {
David Neto22f144c2017-06-12 14:26:21 -0400196 typedef DenseMap<Type *, uint32_t> TypeMapType;
197 typedef UniqueVector<Type *> TypeList;
198 typedef DenseMap<Value *, uint32_t> ValueMapType;
David Netofb9a7972017-08-25 17:08:24 -0400199 typedef UniqueVector<Value *> ValueList;
David Neto22f144c2017-06-12 14:26:21 -0400200 typedef std::vector<std::pair<Value *, uint32_t>> EntryPointVecType;
201 typedef std::list<SPIRVInstruction *> SPIRVInstructionList;
David Neto87846742018-04-11 17:36:22 -0400202 // A vector of tuples, each of which is:
203 // - the LLVM instruction that we will later generate SPIR-V code for
204 // - where the SPIR-V instruction should be inserted
205 // - the result ID of the SPIR-V instruction
David Neto22f144c2017-06-12 14:26:21 -0400206 typedef std::vector<
207 std::tuple<Value *, SPIRVInstructionList::iterator, uint32_t>>
208 DeferredInstVecType;
209 typedef DenseMap<FunctionType *, std::pair<FunctionType *, uint32_t>>
210 GlobalConstFuncMapType;
211
David Neto44795152017-07-13 15:45:28 -0400212 explicit SPIRVProducerPass(
213 raw_pwrite_stream &out, raw_ostream &descriptor_map_out,
214 ArrayRef<std::pair<unsigned, std::string>> samplerMap, bool outputAsm,
215 bool outputCInitList)
David Netoc2c368d2017-06-30 16:50:17 -0400216 : ModulePass(ID), samplerMap(samplerMap), out(out),
David Neto0676e6f2017-07-11 18:47:44 -0400217 binaryTempOut(binaryTempUnderlyingVector), binaryOut(&out),
David Netoc2c368d2017-06-30 16:50:17 -0400218 descriptorMapOut(descriptor_map_out), outputAsm(outputAsm),
David Neto0676e6f2017-07-11 18:47:44 -0400219 outputCInitList(outputCInitList), patchBoundOffset(0), nextID(1),
David Netoa60b00b2017-09-15 16:34:09 -0400220 OpExtInstImportID(0), HasVariablePointers(false), SamplerTy(nullptr),
David Neto85082642018-03-24 06:55:20 -0700221 WorkgroupSizeValueID(0), WorkgroupSizeVarID(0),
David Neto257c3892018-04-11 13:19:45 -0400222 NextDescriptorSetIndex(0), constant_i32_zero_id_(0) {}
David Neto22f144c2017-06-12 14:26:21 -0400223
224 void getAnalysisUsage(AnalysisUsage &AU) const override {
225 AU.addRequired<DominatorTreeWrapperPass>();
226 AU.addRequired<LoopInfoWrapperPass>();
227 }
228
229 virtual bool runOnModule(Module &module) override;
230
231 // output the SPIR-V header block
232 void outputHeader();
233
234 // patch the SPIR-V header block
235 void patchHeader();
236
237 uint32_t lookupType(Type *Ty) {
238 if (Ty->isPointerTy() &&
239 (Ty->getPointerAddressSpace() != AddressSpace::UniformConstant)) {
240 auto PointeeTy = Ty->getPointerElementType();
241 if (PointeeTy->isStructTy() &&
242 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
243 Ty = PointeeTy;
244 }
245 }
246
247 if (0 == TypeMap.count(Ty)) {
248 Ty->print(errs());
David Netoe439d702018-03-23 13:14:08 -0700249 llvm_unreachable("\nUnhandled type!");
David Neto22f144c2017-06-12 14:26:21 -0400250 }
251
252 return TypeMap[Ty];
253 }
254 TypeMapType &getImageTypeMap() { return ImageTypeMap; }
255 TypeList &getTypeList() { return Types; };
256 ValueList &getConstantList() { return Constants; };
257 ValueMapType &getValueMap() { return ValueMap; }
258 ValueMapType &getAllocatedValueMap() { return AllocatedValueMap; }
259 SPIRVInstructionList &getSPIRVInstList() { return SPIRVInsts; };
260 ValueToValueMapTy &getArgumentGVMap() { return ArgumentGVMap; };
261 ValueMapType &getArgumentGVIDMap() { return ArgumentGVIDMap; };
262 EntryPointVecType &getEntryPointVec() { return EntryPointVec; };
263 DeferredInstVecType &getDeferredInstVec() { return DeferredInstVec; };
264 ValueList &getEntryPointInterfacesVec() { return EntryPointInterfacesVec; };
265 uint32_t &getOpExtInstImportID() { return OpExtInstImportID; };
266 std::vector<uint32_t> &getBuiltinDimVec() { return BuiltinDimensionVec; };
267 bool hasVariablePointers() { return true; /* We use StorageBuffer everywhere */ };
268 void setVariablePointers(bool Val) { HasVariablePointers = Val; };
David Neto44795152017-07-13 15:45:28 -0400269 ArrayRef<std::pair<unsigned, std::string>> &getSamplerMap() { return samplerMap; }
David Neto22f144c2017-06-12 14:26:21 -0400270 GlobalConstFuncMapType &getGlobalConstFuncTypeMap() {
271 return GlobalConstFuncTypeMap;
272 }
273 SmallPtrSet<Value *, 16> &getGlobalConstArgSet() {
274 return GlobalConstArgumentSet;
275 }
David Neto85082642018-03-24 06:55:20 -0700276 TypeList &getTypesNeedingArrayStride() {
277 return TypesNeedingArrayStride;
David Neto1a1a0582017-07-07 12:01:44 -0400278 }
David Neto22f144c2017-06-12 14:26:21 -0400279
David Netoc6f3ab22018-04-06 18:02:31 -0400280 void GenerateLLVMIRInfo(Module &M, const DataLayout &DL);
David Neto22f144c2017-06-12 14:26:21 -0400281 bool FindExtInst(Module &M);
282 void FindTypePerGlobalVar(GlobalVariable &GV);
283 void FindTypePerFunc(Function &F);
David Neto19a1bad2017-08-25 15:01:41 -0400284 // Inserts |Ty| and relevant sub-types into the |Types| member, indicating that
285 // |Ty| and its subtypes will need a corresponding SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400286 void FindType(Type *Ty);
287 void FindConstantPerGlobalVar(GlobalVariable &GV);
288 void FindConstantPerFunc(Function &F);
289 void FindConstant(Value *V);
290 void GenerateExtInstImport();
David Neto19a1bad2017-08-25 15:01:41 -0400291 // Generates instructions for SPIR-V types corresponding to the LLVM types
292 // saved in the |Types| member. A type follows its subtypes. IDs are
293 // allocated sequentially starting with the current value of nextID, and
294 // with a type following its subtypes. Also updates nextID to just beyond
295 // the last generated ID.
David Netoc6f3ab22018-04-06 18:02:31 -0400296 void GenerateSPIRVTypes(LLVMContext& context, const DataLayout &DL);
David Neto22f144c2017-06-12 14:26:21 -0400297 void GenerateSPIRVConstants();
David Neto5c22a252018-03-15 16:07:41 -0400298 void GenerateModuleInfo(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400299 void GenerateGlobalVar(GlobalVariable &GV);
David Netoc6f3ab22018-04-06 18:02:31 -0400300 void GenerateWorkgroupVars();
David Neto22f144c2017-06-12 14:26:21 -0400301 void GenerateSamplers(Module &M);
302 void GenerateFuncPrologue(Function &F);
303 void GenerateFuncBody(Function &F);
304 void GenerateInstForArg(Function &F);
David Netob6e2e062018-04-25 10:32:06 -0400305 void GenerateEntryPointInitialStores();
David Neto22f144c2017-06-12 14:26:21 -0400306 spv::Op GetSPIRVCmpOpcode(CmpInst *CmpI);
307 spv::Op GetSPIRVCastOpcode(Instruction &I);
308 spv::Op GetSPIRVBinaryOpcode(Instruction &I);
309 void GenerateInstruction(Instruction &I);
310 void GenerateFuncEpilogue();
311 void HandleDeferredInstruction();
David Neto1a1a0582017-07-07 12:01:44 -0400312 void HandleDeferredDecorations(const DataLayout& DL);
David Neto22f144c2017-06-12 14:26:21 -0400313 bool is4xi8vec(Type *Ty) const;
David Neto257c3892018-04-11 13:19:45 -0400314 // Return the SPIR-V Id for 32-bit constant zero. The constant must already
315 // have been created.
316 uint32_t GetI32Zero();
David Neto22f144c2017-06-12 14:26:21 -0400317 spv::StorageClass GetStorageClass(unsigned AddrSpace) const;
318 spv::BuiltIn GetBuiltin(StringRef globalVarName) const;
David Neto3fbb4072017-10-16 11:28:14 -0400319 // Returns the GLSL extended instruction enum that the given function
320 // call maps to. If none, then returns the 0 value, i.e. GLSLstd4580Bad.
David Neto22f144c2017-06-12 14:26:21 -0400321 glsl::ExtInst getExtInstEnum(StringRef Name);
David Neto3fbb4072017-10-16 11:28:14 -0400322 // Returns the GLSL extended instruction enum indirectly used by the given
323 // function. That is, to implement the given function, we use an extended
324 // instruction plus one more instruction. If none, then returns the 0 value,
325 // i.e. GLSLstd4580Bad.
326 glsl::ExtInst getIndirectExtInstEnum(StringRef Name);
327 // Returns the single GLSL extended instruction used directly or
328 // indirectly by the given function call.
329 glsl::ExtInst getDirectOrIndirectExtInstEnum(StringRef Name);
David Neto22f144c2017-06-12 14:26:21 -0400330 void PrintResID(SPIRVInstruction *Inst);
331 void PrintOpcode(SPIRVInstruction *Inst);
332 void PrintOperand(SPIRVOperand *Op);
333 void PrintCapability(SPIRVOperand *Op);
334 void PrintExtInst(SPIRVOperand *Op);
335 void PrintAddrModel(SPIRVOperand *Op);
336 void PrintMemModel(SPIRVOperand *Op);
337 void PrintExecModel(SPIRVOperand *Op);
338 void PrintExecMode(SPIRVOperand *Op);
339 void PrintSourceLanguage(SPIRVOperand *Op);
340 void PrintFuncCtrl(SPIRVOperand *Op);
341 void PrintStorageClass(SPIRVOperand *Op);
342 void PrintDecoration(SPIRVOperand *Op);
343 void PrintBuiltIn(SPIRVOperand *Op);
344 void PrintSelectionControl(SPIRVOperand *Op);
345 void PrintLoopControl(SPIRVOperand *Op);
346 void PrintDimensionality(SPIRVOperand *Op);
347 void PrintImageFormat(SPIRVOperand *Op);
348 void PrintMemoryAccess(SPIRVOperand *Op);
349 void PrintImageOperandsType(SPIRVOperand *Op);
350 void WriteSPIRVAssembly();
351 void WriteOneWord(uint32_t Word);
352 void WriteResultID(SPIRVInstruction *Inst);
353 void WriteWordCountAndOpcode(SPIRVInstruction *Inst);
354 void WriteOperand(SPIRVOperand *Op);
355 void WriteSPIRVBinary();
356
357private:
358 static char ID;
David Neto44795152017-07-13 15:45:28 -0400359 ArrayRef<std::pair<unsigned, std::string>> samplerMap;
David Neto22f144c2017-06-12 14:26:21 -0400360 raw_pwrite_stream &out;
David Neto0676e6f2017-07-11 18:47:44 -0400361
362 // TODO(dneto): Wouldn't it be better to always just emit a binary, and then
363 // convert to other formats on demand?
364
365 // When emitting a C initialization list, the WriteSPIRVBinary method
366 // will actually write its words to this vector via binaryTempOut.
367 SmallVector<char, 100> binaryTempUnderlyingVector;
368 raw_svector_ostream binaryTempOut;
369
370 // Binary output writes to this stream, which might be |out| or
371 // |binaryTempOut|. It's the latter when we really want to write a C
372 // initializer list.
373 raw_pwrite_stream* binaryOut;
David Netoc2c368d2017-06-30 16:50:17 -0400374 raw_ostream &descriptorMapOut;
David Neto22f144c2017-06-12 14:26:21 -0400375 const bool outputAsm;
David Neto0676e6f2017-07-11 18:47:44 -0400376 const bool outputCInitList; // If true, output look like {0x7023, ... , 5}
David Neto22f144c2017-06-12 14:26:21 -0400377 uint64_t patchBoundOffset;
378 uint32_t nextID;
379
David Neto19a1bad2017-08-25 15:01:41 -0400380 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400381 TypeMapType TypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400382 // Maps an LLVM image type to its SPIR-V ID.
David Neto22f144c2017-06-12 14:26:21 -0400383 TypeMapType ImageTypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400384 // A unique-vector of LLVM types that map to a SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400385 TypeList Types;
386 ValueList Constants;
David Neto19a1bad2017-08-25 15:01:41 -0400387 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400388 ValueMapType ValueMap;
389 ValueMapType AllocatedValueMap;
390 SPIRVInstructionList SPIRVInsts;
David Netoe439d702018-03-23 13:14:08 -0700391 // Maps a kernel argument value to a global value. OpenCL kernel arguments
392 // have to map to resources: buffers, samplers, images, or sampled images.
David Neto22f144c2017-06-12 14:26:21 -0400393 ValueToValueMapTy ArgumentGVMap;
394 ValueMapType ArgumentGVIDMap;
395 EntryPointVecType EntryPointVec;
396 DeferredInstVecType DeferredInstVec;
397 ValueList EntryPointInterfacesVec;
398 uint32_t OpExtInstImportID;
399 std::vector<uint32_t> BuiltinDimensionVec;
400 bool HasVariablePointers;
401 Type *SamplerTy;
David Netoc77d9e22018-03-24 06:30:28 -0700402
403 // If a function F has a pointer-to-__constant parameter, then this variable
David Neto9ed8e2f2018-03-24 06:47:24 -0700404 // will map F's type to (G, index of the parameter), where in a first phase
405 // G is F's type. During FindTypePerFunc, G will be changed to F's type
406 // but replacing the pointer-to-constant parameter with
407 // pointer-to-ModuleScopePrivate.
David Netoc77d9e22018-03-24 06:30:28 -0700408 // TODO(dneto): This doesn't seem general enough? A function might have
409 // more than one such parameter.
David Neto22f144c2017-06-12 14:26:21 -0400410 GlobalConstFuncMapType GlobalConstFuncTypeMap;
411 SmallPtrSet<Value *, 16> GlobalConstArgumentSet;
David Neto1a1a0582017-07-07 12:01:44 -0400412 // An ordered set of pointer types of Base arguments to OpPtrAccessChain,
David Neto85082642018-03-24 06:55:20 -0700413 // or array types, and which point into transparent memory (StorageBuffer
414 // storage class). These will require an ArrayStride decoration.
David Neto1a1a0582017-07-07 12:01:44 -0400415 // See SPV_KHR_variable_pointers rev 13.
David Neto85082642018-03-24 06:55:20 -0700416 TypeList TypesNeedingArrayStride;
David Netoa60b00b2017-09-15 16:34:09 -0400417
418 // This is truly ugly, but works around what look like driver bugs.
419 // For get_local_size, an earlier part of the flow has created a module-scope
420 // variable in Private address space to hold the value for the workgroup
421 // size. Its intializer is a uint3 value marked as builtin WorkgroupSize.
422 // When this is present, save the IDs of the initializer value and variable
423 // in these two variables. We only ever do a vector load from it, and
424 // when we see one of those, substitute just the value of the intializer.
425 // This mimics what Glslang does, and that's what drivers are used to.
David Neto66cfe642018-03-24 06:13:56 -0700426 // TODO(dneto): Remove this once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -0400427 uint32_t WorkgroupSizeValueID;
428 uint32_t WorkgroupSizeVarID;
David Neto26aaf622017-10-23 18:11:53 -0400429
430 // What module-scope variables already have had their binding information
431 // emitted?
432 DenseSet<Value*> GVarWithEmittedBindingInfo;
David Neto85082642018-03-24 06:55:20 -0700433
David Netoc6f3ab22018-04-06 18:02:31 -0400434 // An ordered list of the kernel arguments of type pointer-to-local.
435 using LocalArgList = SmallVector<const Argument*, 8>;
436 LocalArgList LocalArgs;
437 // Information about a pointer-to-local argument.
438 struct LocalArgInfo {
439 // The SPIR-V ID of the array variable.
440 uint32_t variable_id;
441 // The element type of the
442 Type* elem_type;
443 // The ID of the array type.
444 uint32_t array_size_id;
445 // The ID of the array type.
446 uint32_t array_type_id;
447 // The ID of the pointer to the array type.
448 uint32_t ptr_array_type_id;
449 // The ID of the pointer to the first element of the array.
450 uint32_t first_elem_ptr_id;
451 // The specialization constant ID of the array size.
452 int spec_id;
453 };
454 // A mapping from a pointer-to-local argument value to a LocalArgInfo value.
455 DenseMap<const Argument*, LocalArgInfo> LocalArgMap;
456
David Neto85082642018-03-24 06:55:20 -0700457 // The next descriptor set index to use.
458 uint32_t NextDescriptorSetIndex;
David Netoc6f3ab22018-04-06 18:02:31 -0400459
460 // A mapping from pointer-to-local argument to a specialization constant ID
461 // for that argument's array size. This is generated from AllocatArgSpecIds.
462 ArgIdMapType ArgSpecIdMap;
David Neto257c3892018-04-11 13:19:45 -0400463
464 // The ID of 32-bit integer zero constant. This is only valid after
465 // GenerateSPIRVConstants has run.
466 uint32_t constant_i32_zero_id_;
David Neto22f144c2017-06-12 14:26:21 -0400467};
468
469char SPIRVProducerPass::ID;
David Netoc6f3ab22018-04-06 18:02:31 -0400470
David Neto22f144c2017-06-12 14:26:21 -0400471}
472
473namespace clspv {
David Neto44795152017-07-13 15:45:28 -0400474ModulePass *
475createSPIRVProducerPass(raw_pwrite_stream &out, raw_ostream &descriptor_map_out,
476 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
477 bool outputAsm, bool outputCInitList) {
478 return new SPIRVProducerPass(out, descriptor_map_out, samplerMap, outputAsm,
479 outputCInitList);
David Neto22f144c2017-06-12 14:26:21 -0400480}
David Netoc2c368d2017-06-30 16:50:17 -0400481} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400482
483bool SPIRVProducerPass::runOnModule(Module &module) {
David Neto0676e6f2017-07-11 18:47:44 -0400484 binaryOut = outputCInitList ? &binaryTempOut : &out;
485
David Neto257c3892018-04-11 13:19:45 -0400486 constant_i32_zero_id_ = 0; // Reset, for the benefit of validity checks.
487
David Netoc6f3ab22018-04-06 18:02:31 -0400488 ArgSpecIdMap = AllocateArgSpecIds(module);
489
David Neto22f144c2017-06-12 14:26:21 -0400490 // SPIR-V always begins with its header information
491 outputHeader();
492
David Netoc6f3ab22018-04-06 18:02:31 -0400493 const DataLayout &DL = module.getDataLayout();
494
David Neto22f144c2017-06-12 14:26:21 -0400495 // Gather information from the LLVM IR that we require.
David Netoc6f3ab22018-04-06 18:02:31 -0400496 GenerateLLVMIRInfo(module, DL);
David Neto22f144c2017-06-12 14:26:21 -0400497
498 // If we are using a sampler map, find the type of the sampler.
499 if (0 < getSamplerMap().size()) {
500 auto SamplerStructTy = module.getTypeByName("opencl.sampler_t");
501 if (!SamplerStructTy) {
502 SamplerStructTy =
503 StructType::create(module.getContext(), "opencl.sampler_t");
504 }
505
506 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
507
508 FindType(SamplerTy);
509 }
510
511 // Collect information on global variables too.
512 for (GlobalVariable &GV : module.globals()) {
513 // If the GV is one of our special __spirv_* variables, remove the
514 // initializer as it was only placed there to force LLVM to not throw the
515 // value away.
516 if (GV.getName().startswith("__spirv_")) {
517 GV.setInitializer(nullptr);
518 }
519
520 // Collect types' information from global variable.
521 FindTypePerGlobalVar(GV);
522
523 // Collect constant information from global variable.
524 FindConstantPerGlobalVar(GV);
525
526 // If the variable is an input, entry points need to know about it.
527 if (AddressSpace::Input == GV.getType()->getPointerAddressSpace()) {
David Netofb9a7972017-08-25 17:08:24 -0400528 getEntryPointInterfacesVec().insert(&GV);
David Neto22f144c2017-06-12 14:26:21 -0400529 }
530 }
531
David Netoc6f3ab22018-04-06 18:02:31 -0400532 // Find types related to pointer-to-local arguments.
533 for (auto& arg_spec_id_pair : ArgSpecIdMap) {
534 const Argument* arg = arg_spec_id_pair.first;
535 FindType(arg->getType());
536 FindType(arg->getType()->getPointerElementType());
537 }
538
David Neto22f144c2017-06-12 14:26:21 -0400539 // If there are extended instructions, generate OpExtInstImport.
540 if (FindExtInst(module)) {
541 GenerateExtInstImport();
542 }
543
544 // Generate SPIRV instructions for types.
David Netoc6f3ab22018-04-06 18:02:31 -0400545 GenerateSPIRVTypes(module.getContext(), DL);
David Neto22f144c2017-06-12 14:26:21 -0400546
547 // Generate SPIRV constants.
548 GenerateSPIRVConstants();
549
550 // If we have a sampler map, we might have literal samplers to generate.
551 if (0 < getSamplerMap().size()) {
552 GenerateSamplers(module);
553 }
554
555 // Generate SPIRV variables.
556 for (GlobalVariable &GV : module.globals()) {
557 GenerateGlobalVar(GV);
558 }
David Netoc6f3ab22018-04-06 18:02:31 -0400559 GenerateWorkgroupVars();
David Neto22f144c2017-06-12 14:26:21 -0400560
561 // Generate SPIRV instructions for each function.
562 for (Function &F : module) {
563 if (F.isDeclaration()) {
564 continue;
565 }
566
567 // Generate Function Prologue.
568 GenerateFuncPrologue(F);
569
570 // Generate SPIRV instructions for function body.
571 GenerateFuncBody(F);
572
573 // Generate Function Epilogue.
574 GenerateFuncEpilogue();
575 }
576
577 HandleDeferredInstruction();
David Neto1a1a0582017-07-07 12:01:44 -0400578 HandleDeferredDecorations(DL);
David Neto22f144c2017-06-12 14:26:21 -0400579
580 // Generate SPIRV module information.
David Neto5c22a252018-03-15 16:07:41 -0400581 GenerateModuleInfo(module);
David Neto22f144c2017-06-12 14:26:21 -0400582
583 if (outputAsm) {
584 WriteSPIRVAssembly();
585 } else {
586 WriteSPIRVBinary();
587 }
588
589 // We need to patch the SPIR-V header to set bound correctly.
590 patchHeader();
David Neto0676e6f2017-07-11 18:47:44 -0400591
592 if (outputCInitList) {
593 bool first = true;
David Neto0676e6f2017-07-11 18:47:44 -0400594 std::ostringstream os;
595
David Neto57fb0b92017-08-04 15:35:09 -0400596 auto emit_word = [&os, &first](uint32_t word) {
David Neto0676e6f2017-07-11 18:47:44 -0400597 if (!first)
David Neto57fb0b92017-08-04 15:35:09 -0400598 os << ",\n";
599 os << word;
David Neto0676e6f2017-07-11 18:47:44 -0400600 first = false;
601 };
602
603 os << "{";
David Neto57fb0b92017-08-04 15:35:09 -0400604 const std::string str(binaryTempOut.str());
605 for (unsigned i = 0; i < str.size(); i += 4) {
606 const uint32_t a = static_cast<unsigned char>(str[i]);
607 const uint32_t b = static_cast<unsigned char>(str[i + 1]);
608 const uint32_t c = static_cast<unsigned char>(str[i + 2]);
609 const uint32_t d = static_cast<unsigned char>(str[i + 3]);
610 emit_word(a | (b << 8) | (c << 16) | (d << 24));
David Neto0676e6f2017-07-11 18:47:44 -0400611 }
612 os << "}\n";
613 out << os.str();
614 }
615
David Neto22f144c2017-06-12 14:26:21 -0400616 return false;
617}
618
619void SPIRVProducerPass::outputHeader() {
620 if (outputAsm) {
621 // for ASM output the header goes into 5 comments at the beginning of the
622 // file
623 out << "; SPIR-V\n";
624
625 // the major version number is in the 2nd highest byte
626 const uint32_t major = (spv::Version >> 16) & 0xFF;
627
628 // the minor version number is in the 2nd lowest byte
629 const uint32_t minor = (spv::Version >> 8) & 0xFF;
630 out << "; Version: " << major << "." << minor << "\n";
631
632 // use Codeplay's vendor ID
633 out << "; Generator: Codeplay; 0\n";
634
635 out << "; Bound: ";
636
637 // we record where we need to come back to and patch in the bound value
638 patchBoundOffset = out.tell();
639
640 // output one space per digit for the max size of a 32 bit unsigned integer
641 // (which is the maximum ID we could possibly be using)
642 for (uint32_t i = std::numeric_limits<uint32_t>::max(); 0 != i; i /= 10) {
643 out << " ";
644 }
645
646 out << "\n";
647
648 out << "; Schema: 0\n";
649 } else {
David Neto0676e6f2017-07-11 18:47:44 -0400650 binaryOut->write(reinterpret_cast<const char *>(&spv::MagicNumber),
David Neto22f144c2017-06-12 14:26:21 -0400651 sizeof(spv::MagicNumber));
David Neto0676e6f2017-07-11 18:47:44 -0400652 binaryOut->write(reinterpret_cast<const char *>(&spv::Version),
David Neto22f144c2017-06-12 14:26:21 -0400653 sizeof(spv::Version));
654
655 // use Codeplay's vendor ID
656 const uint32_t vendor = 3 << 16;
David Neto0676e6f2017-07-11 18:47:44 -0400657 binaryOut->write(reinterpret_cast<const char *>(&vendor), sizeof(vendor));
David Neto22f144c2017-06-12 14:26:21 -0400658
659 // we record where we need to come back to and patch in the bound value
David Neto0676e6f2017-07-11 18:47:44 -0400660 patchBoundOffset = binaryOut->tell();
David Neto22f144c2017-06-12 14:26:21 -0400661
662 // output a bad bound for now
David Neto0676e6f2017-07-11 18:47:44 -0400663 binaryOut->write(reinterpret_cast<const char *>(&nextID), sizeof(nextID));
David Neto22f144c2017-06-12 14:26:21 -0400664
665 // output the schema (reserved for use and must be 0)
666 const uint32_t schema = 0;
David Neto0676e6f2017-07-11 18:47:44 -0400667 binaryOut->write(reinterpret_cast<const char *>(&schema), sizeof(schema));
David Neto22f144c2017-06-12 14:26:21 -0400668 }
669}
670
671void SPIRVProducerPass::patchHeader() {
672 if (outputAsm) {
673 // get the string representation of the max bound used (nextID will be the
674 // max ID used)
675 auto asString = std::to_string(nextID);
676 out.pwrite(asString.c_str(), asString.size(), patchBoundOffset);
677 } else {
678 // for a binary we just write the value of nextID over bound
David Neto0676e6f2017-07-11 18:47:44 -0400679 binaryOut->pwrite(reinterpret_cast<char *>(&nextID), sizeof(nextID),
680 patchBoundOffset);
David Neto22f144c2017-06-12 14:26:21 -0400681 }
682}
683
David Netoc6f3ab22018-04-06 18:02:31 -0400684void SPIRVProducerPass::GenerateLLVMIRInfo(Module &M, const DataLayout &DL) {
David Neto22f144c2017-06-12 14:26:21 -0400685 // This function generates LLVM IR for function such as global variable for
686 // argument, constant and pointer type for argument access. These information
687 // is artificial one because we need Vulkan SPIR-V output. This function is
688 // executed ahead of FindType and FindConstant.
689 ValueToValueMapTy &ArgGVMap = getArgumentGVMap();
690 LLVMContext &Context = M.getContext();
691
692 // Map for avoiding to generate struct type with same fields.
693 DenseMap<Type *, Type *> ArgTyMap;
694
David Neto5c22a252018-03-15 16:07:41 -0400695 // These function calls need a <2 x i32> as an intermediate result but not
696 // the final result.
697 std::unordered_set<std::string> NeedsIVec2{
698 "_Z15get_image_width14ocl_image2d_ro",
699 "_Z15get_image_width14ocl_image2d_wo",
700 "_Z16get_image_height14ocl_image2d_ro",
701 "_Z16get_image_height14ocl_image2d_wo",
702 };
703
David Neto22f144c2017-06-12 14:26:21 -0400704 // Collect global constant variables.
David Netoc6f3ab22018-04-06 18:02:31 -0400705 {
706 SmallVector<GlobalVariable *, 8> GVList;
707 SmallVector<GlobalVariable *, 8> DeadGVList;
708 for (GlobalVariable &GV : M.globals()) {
709 if (GV.getType()->getAddressSpace() == AddressSpace::Constant) {
710 if (GV.use_empty()) {
711 DeadGVList.push_back(&GV);
712 } else {
713 GVList.push_back(&GV);
714 }
David Netofba9d262018-03-24 06:14:18 -0700715 }
David Neto22f144c2017-06-12 14:26:21 -0400716 }
David Neto22f144c2017-06-12 14:26:21 -0400717
David Netoc6f3ab22018-04-06 18:02:31 -0400718 // Remove dead global __constant variables.
719 for (auto GV : DeadGVList) {
720 GV->eraseFromParent();
David Neto85082642018-03-24 06:55:20 -0700721 }
David Netoc6f3ab22018-04-06 18:02:31 -0400722 DeadGVList.clear();
David Neto22f144c2017-06-12 14:26:21 -0400723
David Netoc6f3ab22018-04-06 18:02:31 -0400724 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
725 // For now, we only support a single storage buffer.
726 if (GVList.size() > 0) {
727 assert(GVList.size() == 1);
728 const auto *GV = GVList[0];
729 const size_t constants_byte_size =
730 (DL.getTypeSizeInBits(GV->getInitializer()->getType())) / 8;
731 const size_t kConstantMaxSize = 65536;
732 if (constants_byte_size > kConstantMaxSize) {
733 outs() << "Max __constant capacity of " << kConstantMaxSize
734 << " bytes exceeded: " << constants_byte_size
735 << " bytes used\n";
736 llvm_unreachable("Max __constant capacity exceeded");
737 }
738 }
739 } else {
740 // Change global constant variable's address space to ModuleScopePrivate.
741 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
742 for (auto GV : GVList) {
743 // Create new gv with ModuleScopePrivate address space.
744 Type *NewGVTy = GV->getType()->getPointerElementType();
745 GlobalVariable *NewGV = new GlobalVariable(
746 M, NewGVTy, false, GV->getLinkage(), GV->getInitializer(), "",
747 nullptr, GV->getThreadLocalMode(),
748 AddressSpace::ModuleScopePrivate);
749 NewGV->takeName(GV);
David Neto22f144c2017-06-12 14:26:21 -0400750
David Netoc6f3ab22018-04-06 18:02:31 -0400751 const SmallVector<User *, 8> GVUsers(GV->user_begin(), GV->user_end());
752 SmallVector<User *, 8> CandidateUsers;
753
754 auto record_called_function_type_as_user =
755 [&GlobalConstFuncTyMap](Value *gv, CallInst *call) {
756 // Find argument index.
757 unsigned index = 0;
758 for (unsigned i = 0; i < call->getNumArgOperands(); i++) {
759 if (gv == call->getOperand(i)) {
760 // TODO(dneto): Should we break here?
761 index = i;
762 }
763 }
764
765 // Record function type with global constant.
766 GlobalConstFuncTyMap[call->getFunctionType()] =
767 std::make_pair(call->getFunctionType(), index);
768 };
769
770 for (User *GVU : GVUsers) {
771 if (CallInst *Call = dyn_cast<CallInst>(GVU)) {
772 record_called_function_type_as_user(GV, Call);
773 } else if (GetElementPtrInst *GEP =
774 dyn_cast<GetElementPtrInst>(GVU)) {
775 // Check GEP users.
776 for (User *GEPU : GEP->users()) {
777 if (CallInst *GEPCall = dyn_cast<CallInst>(GEPU)) {
778 record_called_function_type_as_user(GEP, GEPCall);
David Neto85082642018-03-24 06:55:20 -0700779 }
780 }
David Netoc77d9e22018-03-24 06:30:28 -0700781 }
David Netoc6f3ab22018-04-06 18:02:31 -0400782
783 CandidateUsers.push_back(GVU);
David Neto22f144c2017-06-12 14:26:21 -0400784 }
David Neto85082642018-03-24 06:55:20 -0700785
David Netoc6f3ab22018-04-06 18:02:31 -0400786 for (User *U : CandidateUsers) {
787 // Update users of gv with new gv.
788 U->replaceUsesOfWith(GV, NewGV);
789 }
David Neto22f144c2017-06-12 14:26:21 -0400790
David Netoc6f3ab22018-04-06 18:02:31 -0400791 // Delete original gv.
792 GV->eraseFromParent();
David Neto85082642018-03-24 06:55:20 -0700793 }
David Neto22f144c2017-06-12 14:26:21 -0400794 }
David Neto22f144c2017-06-12 14:26:21 -0400795 }
796
797 bool HasWorkGroupBuiltin = false;
798 for (GlobalVariable &GV : M.globals()) {
799 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
800 if (spv::BuiltInWorkgroupSize == BuiltinType) {
801 HasWorkGroupBuiltin = true;
802 }
803 }
804
805
David Neto26aaf622017-10-23 18:11:53 -0400806 // Map kernel functions to their ordinal number in the compilation unit.
807 UniqueVector<Function*> KernelOrdinal;
808
809 // Map the global variables created for kernel args to their creation
810 // order.
811 UniqueVector<GlobalVariable*> KernelArgVarOrdinal;
812
David Netoc6f3ab22018-04-06 18:02:31 -0400813 // For each kernel argument type, record the kernel arg global resource variables
David Neto26aaf622017-10-23 18:11:53 -0400814 // generated for that type, the function in which that variable was most
815 // recently used, and the binding number it took. For reproducibility,
816 // we track things by ordinal number (rather than pointer), and we use a
817 // std::set rather than DenseSet since std::set maintains an ordering.
818 // Each tuple is the ordinals of the kernel function, the binding number,
819 // and the ordinal of the kernal-arg-var.
820 //
821 // This table lets us reuse module-scope StorageBuffer variables between
822 // different kernels.
823 DenseMap<Type *, std::set<std::tuple<unsigned, unsigned, unsigned>>>
824 GVarsForType;
825
David Neto22f144c2017-06-12 14:26:21 -0400826 for (Function &F : M) {
827 // Handle kernel function first.
828 if (F.isDeclaration() || F.getCallingConv() != CallingConv::SPIR_KERNEL) {
829 continue;
830 }
David Neto26aaf622017-10-23 18:11:53 -0400831 KernelOrdinal.insert(&F);
David Neto22f144c2017-06-12 14:26:21 -0400832
833 for (BasicBlock &BB : F) {
834 for (Instruction &I : BB) {
835 if (I.getOpcode() == Instruction::ZExt ||
836 I.getOpcode() == Instruction::SExt ||
837 I.getOpcode() == Instruction::UIToFP) {
838 // If there is zext with i1 type, it will be changed to OpSelect. The
839 // OpSelect needs constant 0 and 1 so the constants are added here.
840
841 auto OpTy = I.getOperand(0)->getType();
842
843 if (OpTy->isIntegerTy(1) ||
844 (OpTy->isVectorTy() &&
845 OpTy->getVectorElementType()->isIntegerTy(1))) {
846 if (I.getOpcode() == Instruction::ZExt) {
847 APInt One(32, 1);
848 FindConstant(Constant::getNullValue(I.getType()));
849 FindConstant(Constant::getIntegerValue(I.getType(), One));
850 } else if (I.getOpcode() == Instruction::SExt) {
851 APInt MinusOne(32, UINT64_MAX, true);
852 FindConstant(Constant::getNullValue(I.getType()));
853 FindConstant(Constant::getIntegerValue(I.getType(), MinusOne));
854 } else {
855 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
856 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
857 }
858 }
859 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
860 Function *Callee = Call->getCalledFunction();
861
862 // Handle image type specially.
863 if (Callee->getName().equals(
864 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
865 Callee->getName().equals(
866 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
867 TypeMapType &OpImageTypeMap = getImageTypeMap();
868 Type *ImageTy =
869 Call->getArgOperand(0)->getType()->getPointerElementType();
870 OpImageTypeMap[ImageTy] = 0;
871
872 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
873 }
David Neto5c22a252018-03-15 16:07:41 -0400874
875 if (NeedsIVec2.find(Callee->getName()) != NeedsIVec2.end()) {
876 FindType(VectorType::get(Type::getInt32Ty(Context), 2));
877 }
David Neto22f144c2017-06-12 14:26:21 -0400878 }
879 }
880 }
881
882 if (M.getTypeByName("opencl.image2d_ro_t") ||
883 M.getTypeByName("opencl.image2d_wo_t") ||
884 M.getTypeByName("opencl.image3d_ro_t") ||
885 M.getTypeByName("opencl.image3d_wo_t")) {
886 // Assume Image type's sampled type is float type.
887 FindType(Type::getFloatTy(Context));
888 }
889
890 if (const MDNode *MD =
891 dyn_cast<Function>(&F)->getMetadata("reqd_work_group_size")) {
892 // We generate constants if the WorkgroupSize builtin is being used.
893 if (HasWorkGroupBuiltin) {
894 // Collect constant information for work group size.
895 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(0)));
896 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(1)));
897 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(2)));
898 }
899 }
900
901 // Wrap up all argument types with struct type and create global variables
902 // with them.
903 bool HasArgUser = false;
904 unsigned Idx = 0;
905
906 for (const Argument &Arg : F.args()) {
907 Type *ArgTy = Arg.getType();
David Neto22f144c2017-06-12 14:26:21 -0400908
David Netoe439d702018-03-23 13:14:08 -0700909 // The pointee type of the module scope variable we will make.
910 Type *GVTy = nullptr;
David Neto22f144c2017-06-12 14:26:21 -0400911
912 Type *TmpArgTy = ArgTy;
913
914 // sampler_t and image types have pointer type of struct type with
David Netoe439d702018-03-23 13:14:08 -0700915 // opaque type as field. Extract the struct type. It will be used by
916 // global variable for argument.
David Neto22f144c2017-06-12 14:26:21 -0400917 bool IsSamplerType = false;
918 bool IsImageType = false;
919 if (PointerType *TmpArgPTy = dyn_cast<PointerType>(TmpArgTy)) {
920 if (StructType *STy =
921 dyn_cast<StructType>(TmpArgPTy->getElementType())) {
922 if (STy->isOpaque()) {
923 if (STy->getName().equals("opencl.sampler_t")) {
David Neto22f144c2017-06-12 14:26:21 -0400924 IsSamplerType = true;
925 TmpArgTy = STy;
926 } else if (STy->getName().equals("opencl.image2d_ro_t") ||
927 STy->getName().equals("opencl.image2d_wo_t") ||
928 STy->getName().equals("opencl.image3d_ro_t") ||
929 STy->getName().equals("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -0400930 IsImageType = true;
931 TmpArgTy = STy;
932 } else {
933 llvm_unreachable("Argument has opaque type unsupported???");
934 }
935 }
936 }
937 }
David Netoc6f3ab22018-04-06 18:02:31 -0400938 const bool IsPointerToLocal = IsLocalPtr(ArgTy);
939 // Can't both be pointer-to-local and (sampler or image).
940 assert(!((IsSamplerType || IsImageType) && IsPointerToLocal));
David Neto22f144c2017-06-12 14:26:21 -0400941
David Netoe439d702018-03-23 13:14:08 -0700942 // Determine the address space for the module-scope variable.
943 unsigned AddrSpace = AddressSpace::Global;
944 if (IsSamplerType || IsImageType) {
945 AddrSpace = AddressSpace::UniformConstant;
946 } else if (PointerType *ArgPTy = dyn_cast<PointerType>(ArgTy)) {
947 AddrSpace = ArgPTy->getAddressSpace();
David Neto482550a2018-03-24 05:21:07 -0700948 } else if (clspv::Option::PodArgsInUniformBuffer()) {
David Netoe439d702018-03-23 13:14:08 -0700949 // Use a uniform buffer for POD arguments.
950 AddrSpace = AddressSpace::Uniform;
951 }
952
David Neto22f144c2017-06-12 14:26:21 -0400953 // LLVM's pointer type is distinguished by address space but we need to
954 // regard constant and global address space as same here. If pointer
955 // type has constant address space, generate new pointer type
956 // temporarily to check previous struct type for argument.
957 if (PointerType *TmpArgPTy = dyn_cast<PointerType>(TmpArgTy)) {
David Netoe439d702018-03-23 13:14:08 -0700958 if (TmpArgPTy->getAddressSpace() == AddressSpace::Constant) {
David Neto22f144c2017-06-12 14:26:21 -0400959 TmpArgTy = PointerType::get(TmpArgPTy->getElementType(),
960 AddressSpace::Global);
961 }
962 }
963
964 if (IsSamplerType || IsImageType) {
965 GVTy = TmpArgTy;
David Netoc6f3ab22018-04-06 18:02:31 -0400966 } else if (IsPointerToLocal) {
967 assert(ArgTy == TmpArgTy);
968 auto spec_id = ArgSpecIdMap[&Arg];
969 assert(spec_id > 0);
970 LocalArgMap[&Arg] =
971 LocalArgInfo{nextID, ArgTy->getPointerElementType(),
972 nextID + 1, nextID + 2,
973 nextID + 3, nextID + 4,
974 spec_id};
975 LocalArgs.push_back(&Arg);
976 nextID += 5;
David Neto22f144c2017-06-12 14:26:21 -0400977 } else if (ArgTyMap.count(TmpArgTy)) {
978 // If there are arguments handled previously, use its type.
979 GVTy = ArgTyMap[TmpArgTy];
980 } else {
981 // Wrap up argument type with struct type.
David Neto83add0a2017-10-23 15:30:59 -0400982 // Reuse struct types where possible.
David Neto7b2abea2017-10-23 20:02:02 -0400983 SmallVector<Type*,1> members{ArgTy};
David Neto83add0a2017-10-23 15:30:59 -0400984 StructType *STy = StructType::get(Context, members);
David Neto22f144c2017-06-12 14:26:21 -0400985
986 GVTy = STy;
987 ArgTyMap[TmpArgTy] = STy;
988 }
989
David Netoc6f3ab22018-04-06 18:02:31 -0400990 if (!IsPointerToLocal) {
991 // In order to build type map between llvm type and spirv id, LLVM
992 // global variable is needed. It has llvm type and other instructions
993 // can access it with its type.
994 //
995 // Reuse a global variable if it was created for a different entry
996 // point.
David Neto26aaf622017-10-23 18:11:53 -0400997
David Netoc6f3ab22018-04-06 18:02:31 -0400998 // Returns a new global variable for this kernel argument, and remembers
999 // it in KernelArgVarOrdinal.
1000 auto make_gvar = [&]() {
1001 auto result = new GlobalVariable(
1002 M, GVTy, false, GlobalValue::ExternalLinkage,
1003 UndefValue::get(GVTy),
1004 F.getName() + ".arg." + std::to_string(Idx), nullptr,
1005 GlobalValue::ThreadLocalMode::NotThreadLocal, AddrSpace);
1006 KernelArgVarOrdinal.insert(result);
1007 return result;
1008 };
David Neto26aaf622017-10-23 18:11:53 -04001009
David Netoc6f3ab22018-04-06 18:02:31 -04001010 // Make a new variable if there was none for this type, or if we can
1011 // reuse one created for a different function but not yet reused for
1012 // the current function, *and* the binding is the same.
1013 // Always make a new variable if we're forcing distinct descriptor sets.
1014 GlobalVariable *GV = nullptr;
1015 auto which_set = GVarsForType.find(GVTy);
1016 if (IsSamplerType || IsImageType || which_set == GVarsForType.end() ||
1017 clspv::Option::DistinctKernelDescriptorSets()) {
1018 GV = make_gvar();
1019 } else {
1020 auto &set = which_set->second;
1021 // Reuse a variable if it was associated with a different function.
1022 for (auto iter = set.begin(), end = set.end(); iter != end; ++iter) {
1023 const unsigned fn_ordinal = std::get<0>(*iter);
1024 const unsigned binding = std::get<1>(*iter);
1025 if (fn_ordinal != KernelOrdinal.idFor(&F) && binding == Idx) {
1026 GV = KernelArgVarOrdinal[std::get<2>(*iter)];
1027 // Remove it from the set. We'll add it back later.
1028 set.erase(iter);
1029 break;
1030 }
1031 }
1032 if (!GV) {
1033 GV = make_gvar();
David Neto26aaf622017-10-23 18:11:53 -04001034 }
1035 }
David Netoc6f3ab22018-04-06 18:02:31 -04001036 assert(GV);
1037 GVarsForType[GVTy].insert(std::make_tuple(
1038 KernelOrdinal.idFor(&F), Idx, KernelArgVarOrdinal.idFor(GV)));
1039
1040 // Generate type info for argument global variable.
1041 FindType(GV->getType());
1042
1043 ArgGVMap[&Arg] = GV;
1044
1045 Idx++;
David Neto26aaf622017-10-23 18:11:53 -04001046 }
David Neto22f144c2017-06-12 14:26:21 -04001047
1048 // Generate pointer type of argument type for OpAccessChain of argument.
1049 if (!Arg.use_empty()) {
1050 if (!isa<PointerType>(ArgTy)) {
David Netoe439d702018-03-23 13:14:08 -07001051 auto ty = PointerType::get(ArgTy, AddrSpace);
1052 FindType(ty);
David Neto22f144c2017-06-12 14:26:21 -04001053 }
1054 HasArgUser = true;
1055 }
1056 }
1057
1058 if (HasArgUser) {
1059 // Generate constant 0 for OpAccessChain of argument.
1060 Type *IdxTy = Type::getInt32Ty(Context);
1061 FindConstant(ConstantInt::get(IdxTy, 0));
1062 FindType(IdxTy);
1063 }
1064
1065 // Collect types' information from function.
1066 FindTypePerFunc(F);
1067
1068 // Collect constant information from function.
1069 FindConstantPerFunc(F);
1070 }
1071
1072 for (Function &F : M) {
1073 // Handle non-kernel functions.
1074 if (F.isDeclaration() || F.getCallingConv() == CallingConv::SPIR_KERNEL) {
1075 continue;
1076 }
1077
1078 for (BasicBlock &BB : F) {
1079 for (Instruction &I : BB) {
1080 if (I.getOpcode() == Instruction::ZExt ||
1081 I.getOpcode() == Instruction::SExt ||
1082 I.getOpcode() == Instruction::UIToFP) {
1083 // If there is zext with i1 type, it will be changed to OpSelect. The
1084 // OpSelect needs constant 0 and 1 so the constants are added here.
1085
1086 auto OpTy = I.getOperand(0)->getType();
1087
1088 if (OpTy->isIntegerTy(1) ||
1089 (OpTy->isVectorTy() &&
1090 OpTy->getVectorElementType()->isIntegerTy(1))) {
1091 if (I.getOpcode() == Instruction::ZExt) {
1092 APInt One(32, 1);
1093 FindConstant(Constant::getNullValue(I.getType()));
1094 FindConstant(Constant::getIntegerValue(I.getType(), One));
1095 } else if (I.getOpcode() == Instruction::SExt) {
1096 APInt MinusOne(32, UINT64_MAX, true);
1097 FindConstant(Constant::getNullValue(I.getType()));
1098 FindConstant(Constant::getIntegerValue(I.getType(), MinusOne));
1099 } else {
1100 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
1101 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
1102 }
1103 }
1104 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1105 Function *Callee = Call->getCalledFunction();
1106
1107 // Handle image type specially.
1108 if (Callee->getName().equals(
1109 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
1110 Callee->getName().equals(
1111 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
1112 TypeMapType &OpImageTypeMap = getImageTypeMap();
1113 Type *ImageTy =
1114 Call->getArgOperand(0)->getType()->getPointerElementType();
1115 OpImageTypeMap[ImageTy] = 0;
1116
1117 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
1118 }
1119 }
1120 }
1121 }
1122
1123 if (M.getTypeByName("opencl.image2d_ro_t") ||
1124 M.getTypeByName("opencl.image2d_wo_t") ||
1125 M.getTypeByName("opencl.image3d_ro_t") ||
1126 M.getTypeByName("opencl.image3d_wo_t")) {
1127 // Assume Image type's sampled type is float type.
1128 FindType(Type::getFloatTy(Context));
1129 }
1130
1131 // Collect types' information from function.
1132 FindTypePerFunc(F);
1133
1134 // Collect constant information from function.
1135 FindConstantPerFunc(F);
1136 }
1137}
1138
1139bool SPIRVProducerPass::FindExtInst(Module &M) {
1140 LLVMContext &Context = M.getContext();
1141 bool HasExtInst = false;
1142
1143 for (Function &F : M) {
1144 for (BasicBlock &BB : F) {
1145 for (Instruction &I : BB) {
1146 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1147 Function *Callee = Call->getCalledFunction();
1148 // Check whether this call is for extend instructions.
David Neto3fbb4072017-10-16 11:28:14 -04001149 auto callee_name = Callee->getName();
1150 const glsl::ExtInst EInst = getExtInstEnum(callee_name);
1151 const glsl::ExtInst IndirectEInst =
1152 getIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04001153
David Neto3fbb4072017-10-16 11:28:14 -04001154 HasExtInst |=
1155 (EInst != kGlslExtInstBad) || (IndirectEInst != kGlslExtInstBad);
1156
1157 if (IndirectEInst) {
1158 // Register extra constants if needed.
1159
1160 // Registers a type and constant for computing the result of the
1161 // given instruction. If the result of the instruction is a vector,
1162 // then make a splat vector constant with the same number of
1163 // elements.
1164 auto register_constant = [this, &I](Constant *constant) {
1165 FindType(constant->getType());
1166 FindConstant(constant);
1167 if (auto *vectorTy = dyn_cast<VectorType>(I.getType())) {
1168 // Register the splat vector of the value with the same
1169 // width as the result of the instruction.
1170 auto *vec_constant = ConstantVector::getSplat(
1171 static_cast<unsigned>(vectorTy->getNumElements()),
1172 constant);
1173 FindConstant(vec_constant);
1174 FindType(vec_constant->getType());
1175 }
1176 };
1177 switch (IndirectEInst) {
1178 case glsl::ExtInstFindUMsb:
1179 // clz needs OpExtInst and OpISub with constant 31, or splat
1180 // vector of 31. Add it to the constant list here.
1181 register_constant(
1182 ConstantInt::get(Type::getInt32Ty(Context), 31));
1183 break;
1184 case glsl::ExtInstAcos:
1185 case glsl::ExtInstAsin:
1186 case glsl::ExtInstAtan2:
1187 // We need 1/pi for acospi, asinpi, atan2pi.
1188 register_constant(
1189 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
1190 break;
1191 default:
1192 assert(false && "internally inconsistent");
1193 }
David Neto22f144c2017-06-12 14:26:21 -04001194 }
1195 }
1196 }
1197 }
1198 }
1199
1200 return HasExtInst;
1201}
1202
1203void SPIRVProducerPass::FindTypePerGlobalVar(GlobalVariable &GV) {
1204 // Investigate global variable's type.
1205 FindType(GV.getType());
1206}
1207
1208void SPIRVProducerPass::FindTypePerFunc(Function &F) {
1209 // Investigate function's type.
1210 FunctionType *FTy = F.getFunctionType();
1211
1212 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
1213 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
David Neto9ed8e2f2018-03-24 06:47:24 -07001214 // Handle a regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04001215 if (GlobalConstFuncTyMap.count(FTy)) {
1216 uint32_t GVCstArgIdx = GlobalConstFuncTypeMap[FTy].second;
1217 SmallVector<Type *, 4> NewFuncParamTys;
1218 for (unsigned i = 0; i < FTy->getNumParams(); i++) {
1219 Type *ParamTy = FTy->getParamType(i);
1220 if (i == GVCstArgIdx) {
1221 Type *EleTy = ParamTy->getPointerElementType();
1222 ParamTy = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1223 }
1224
1225 NewFuncParamTys.push_back(ParamTy);
1226 }
1227
1228 FunctionType *NewFTy =
1229 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1230 GlobalConstFuncTyMap[FTy] = std::make_pair(NewFTy, GVCstArgIdx);
1231 FTy = NewFTy;
1232 }
1233
1234 FindType(FTy);
1235 } else {
1236 // As kernel functions do not have parameters, create new function type and
1237 // add it to type map.
1238 SmallVector<Type *, 4> NewFuncParamTys;
1239 FunctionType *NewFTy =
1240 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1241 FindType(NewFTy);
1242 }
1243
1244 // Investigate instructions' type in function body.
1245 for (BasicBlock &BB : F) {
1246 for (Instruction &I : BB) {
1247 if (isa<ShuffleVectorInst>(I)) {
1248 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1249 // Ignore type for mask of shuffle vector instruction.
1250 if (i == 2) {
1251 continue;
1252 }
1253
1254 Value *Op = I.getOperand(i);
1255 if (!isa<MetadataAsValue>(Op)) {
1256 FindType(Op->getType());
1257 }
1258 }
1259
1260 FindType(I.getType());
1261 continue;
1262 }
1263
1264 // Work through the operands of the instruction.
1265 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1266 Value *const Op = I.getOperand(i);
1267 // If any of the operands is a constant, find the type!
1268 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1269 FindType(Op->getType());
1270 }
1271 }
1272
1273 for (Use &Op : I.operands()) {
1274 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1275 // Avoid to check call instruction's type.
1276 break;
1277 }
1278 if (!isa<MetadataAsValue>(&Op)) {
1279 FindType(Op->getType());
1280 continue;
1281 }
1282 }
1283
1284 CallInst *Call = dyn_cast<CallInst>(&I);
1285
1286 // We don't want to track the type of this call as we are going to replace
1287 // it.
1288 if (Call && ("__translate_sampler_initializer" ==
1289 Call->getCalledFunction()->getName())) {
1290 continue;
1291 }
1292
1293 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1294 // If gep's base operand has ModuleScopePrivate address space, make gep
1295 // return ModuleScopePrivate address space.
1296 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate) {
1297 // Add pointer type with private address space for global constant to
1298 // type list.
1299 Type *EleTy = I.getType()->getPointerElementType();
1300 Type *NewPTy =
1301 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1302
1303 FindType(NewPTy);
1304 continue;
1305 }
1306 }
1307
1308 FindType(I.getType());
1309 }
1310 }
1311}
1312
1313void SPIRVProducerPass::FindType(Type *Ty) {
1314 TypeList &TyList = getTypeList();
1315
1316 if (0 != TyList.idFor(Ty)) {
1317 return;
1318 }
1319
1320 if (Ty->isPointerTy()) {
1321 auto AddrSpace = Ty->getPointerAddressSpace();
1322 if ((AddressSpace::Constant == AddrSpace) ||
1323 (AddressSpace::Global == AddrSpace)) {
1324 auto PointeeTy = Ty->getPointerElementType();
1325
1326 if (PointeeTy->isStructTy() &&
1327 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1328 FindType(PointeeTy);
1329 auto ActualPointerTy =
1330 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1331 FindType(ActualPointerTy);
1332 return;
1333 }
1334 }
1335 }
1336
1337 // OpTypeArray has constant and we need to support type of the constant.
1338 if (isa<ArrayType>(Ty)) {
1339 LLVMContext &Context = Ty->getContext();
1340 FindType(Type::getInt32Ty(Context));
1341 }
1342
1343 for (Type *SubTy : Ty->subtypes()) {
1344 FindType(SubTy);
1345 }
1346
1347 TyList.insert(Ty);
1348}
1349
1350void SPIRVProducerPass::FindConstantPerGlobalVar(GlobalVariable &GV) {
1351 // If the global variable has a (non undef) initializer.
1352 if (GV.hasInitializer() && !isa<UndefValue>(GV.getInitializer())) {
1353 FindConstant(GV.getInitializer());
1354 }
1355}
1356
1357void SPIRVProducerPass::FindConstantPerFunc(Function &F) {
1358 // Investigate constants in function body.
1359 for (BasicBlock &BB : F) {
1360 for (Instruction &I : BB) {
1361 CallInst *Call = dyn_cast<CallInst>(&I);
1362
1363 if (Call && ("__translate_sampler_initializer" ==
1364 Call->getCalledFunction()->getName())) {
1365 // We've handled these constants elsewhere, so skip it.
1366 continue;
1367 }
1368
1369 if (isa<AllocaInst>(I)) {
1370 // Alloca instruction has constant for the number of element. Ignore it.
1371 continue;
1372 } else if (isa<ShuffleVectorInst>(I)) {
1373 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1374 // Ignore constant for mask of shuffle vector instruction.
1375 if (i == 2) {
1376 continue;
1377 }
1378
1379 if (isa<Constant>(I.getOperand(i)) &&
1380 !isa<GlobalValue>(I.getOperand(i))) {
1381 FindConstant(I.getOperand(i));
1382 }
1383 }
1384
1385 continue;
1386 } else if (isa<InsertElementInst>(I)) {
1387 // Handle InsertElement with <4 x i8> specially.
1388 Type *CompositeTy = I.getOperand(0)->getType();
1389 if (is4xi8vec(CompositeTy)) {
1390 LLVMContext &Context = CompositeTy->getContext();
1391 if (isa<Constant>(I.getOperand(0))) {
1392 FindConstant(I.getOperand(0));
1393 }
1394
1395 if (isa<Constant>(I.getOperand(1))) {
1396 FindConstant(I.getOperand(1));
1397 }
1398
1399 // Add mask constant 0xFF.
1400 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1401 FindConstant(CstFF);
1402
1403 // Add shift amount constant.
1404 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
1405 uint64_t Idx = CI->getZExtValue();
1406 Constant *CstShiftAmount =
1407 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1408 FindConstant(CstShiftAmount);
1409 }
1410
1411 continue;
1412 }
1413
1414 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1415 // Ignore constant for index of InsertElement instruction.
1416 if (i == 2) {
1417 continue;
1418 }
1419
1420 if (isa<Constant>(I.getOperand(i)) &&
1421 !isa<GlobalValue>(I.getOperand(i))) {
1422 FindConstant(I.getOperand(i));
1423 }
1424 }
1425
1426 continue;
1427 } else if (isa<ExtractElementInst>(I)) {
1428 // Handle ExtractElement with <4 x i8> specially.
1429 Type *CompositeTy = I.getOperand(0)->getType();
1430 if (is4xi8vec(CompositeTy)) {
1431 LLVMContext &Context = CompositeTy->getContext();
1432 if (isa<Constant>(I.getOperand(0))) {
1433 FindConstant(I.getOperand(0));
1434 }
1435
1436 // Add mask constant 0xFF.
1437 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1438 FindConstant(CstFF);
1439
1440 // Add shift amount constant.
1441 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1442 uint64_t Idx = CI->getZExtValue();
1443 Constant *CstShiftAmount =
1444 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1445 FindConstant(CstShiftAmount);
1446 } else {
1447 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
1448 FindConstant(Cst8);
1449 }
1450
1451 continue;
1452 }
1453
1454 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1455 // Ignore constant for index of ExtractElement instruction.
1456 if (i == 1) {
1457 continue;
1458 }
1459
1460 if (isa<Constant>(I.getOperand(i)) &&
1461 !isa<GlobalValue>(I.getOperand(i))) {
1462 FindConstant(I.getOperand(i));
1463 }
1464 }
1465
1466 continue;
1467 } else if ((Instruction::Xor == I.getOpcode()) && I.getType()->isIntegerTy(1)) {
1468 // 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
1469 bool foundConstantTrue = false;
1470 for (Use &Op : I.operands()) {
1471 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1472 auto CI = cast<ConstantInt>(Op);
1473
1474 if (CI->isZero() || foundConstantTrue) {
1475 // 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.
1476 FindConstant(Op);
1477 } else {
1478 foundConstantTrue = true;
1479 }
1480 }
1481 }
1482
1483 continue;
David Netod2de94a2017-08-28 17:27:47 -04001484 } else if (isa<TruncInst>(I)) {
1485 // For truncation to i8 we mask against 255.
1486 Type *ToTy = I.getType();
1487 if (8u == ToTy->getPrimitiveSizeInBits()) {
1488 LLVMContext &Context = ToTy->getContext();
1489 Constant *Cst255 = ConstantInt::get(Type::getInt32Ty(Context), 0xff);
1490 FindConstant(Cst255);
1491 }
1492 // Fall through.
Neil Henning39672102017-09-29 14:33:13 +01001493 } else if (isa<AtomicRMWInst>(I)) {
1494 LLVMContext &Context = I.getContext();
1495
1496 FindConstant(
1497 ConstantInt::get(Type::getInt32Ty(Context), spv::ScopeDevice));
1498 FindConstant(ConstantInt::get(
1499 Type::getInt32Ty(Context),
1500 spv::MemorySemanticsUniformMemoryMask |
1501 spv::MemorySemanticsSequentiallyConsistentMask));
David Neto22f144c2017-06-12 14:26:21 -04001502 }
1503
1504 for (Use &Op : I.operands()) {
1505 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1506 FindConstant(Op);
1507 }
1508 }
1509 }
1510 }
1511}
1512
1513void SPIRVProducerPass::FindConstant(Value *V) {
David Neto22f144c2017-06-12 14:26:21 -04001514 ValueList &CstList = getConstantList();
1515
David Netofb9a7972017-08-25 17:08:24 -04001516 // If V is already tracked, ignore it.
1517 if (0 != CstList.idFor(V)) {
David Neto22f144c2017-06-12 14:26:21 -04001518 return;
1519 }
1520
1521 Constant *Cst = cast<Constant>(V);
1522
1523 // Handle constant with <4 x i8> type specially.
1524 Type *CstTy = Cst->getType();
1525 if (is4xi8vec(CstTy)) {
1526 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001527 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001528 }
1529 }
1530
1531 if (Cst->getNumOperands()) {
1532 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end(); I != E;
1533 ++I) {
1534 FindConstant(*I);
1535 }
1536
David Netofb9a7972017-08-25 17:08:24 -04001537 CstList.insert(Cst);
David Neto22f144c2017-06-12 14:26:21 -04001538 return;
1539 } else if (const ConstantDataSequential *CDS =
1540 dyn_cast<ConstantDataSequential>(Cst)) {
1541 // Add constants for each element to constant list.
1542 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
1543 Constant *EleCst = CDS->getElementAsConstant(i);
1544 FindConstant(EleCst);
1545 }
1546 }
1547
1548 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001549 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001550 }
1551}
1552
1553spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1554 switch (AddrSpace) {
1555 default:
1556 llvm_unreachable("Unsupported OpenCL address space");
1557 case AddressSpace::Private:
1558 return spv::StorageClassFunction;
1559 case AddressSpace::Global:
1560 case AddressSpace::Constant:
1561 return spv::StorageClassStorageBuffer;
1562 case AddressSpace::Input:
1563 return spv::StorageClassInput;
1564 case AddressSpace::Local:
1565 return spv::StorageClassWorkgroup;
1566 case AddressSpace::UniformConstant:
1567 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001568 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001569 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001570 case AddressSpace::ModuleScopePrivate:
1571 return spv::StorageClassPrivate;
1572 }
1573}
1574
1575spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1576 return StringSwitch<spv::BuiltIn>(Name)
1577 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1578 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1579 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1580 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1581 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
1582 .Default(spv::BuiltInMax);
1583}
1584
1585void SPIRVProducerPass::GenerateExtInstImport() {
1586 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1587 uint32_t &ExtInstImportID = getOpExtInstImportID();
1588
1589 //
1590 // Generate OpExtInstImport.
1591 //
1592 // Ops[0] ... Ops[n] = Name (Literal String)
David Neto22f144c2017-06-12 14:26:21 -04001593 ExtInstImportID = nextID;
David Neto87846742018-04-11 17:36:22 -04001594 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpExtInstImport, nextID++,
1595 MkString("GLSL.std.450")));
David Neto22f144c2017-06-12 14:26:21 -04001596}
1597
David Netoc6f3ab22018-04-06 18:02:31 -04001598void SPIRVProducerPass::GenerateSPIRVTypes(LLVMContext& Context, const DataLayout &DL) {
David Neto22f144c2017-06-12 14:26:21 -04001599 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1600 ValueMapType &VMap = getValueMap();
1601 ValueMapType &AllocatedVMap = getAllocatedValueMap();
1602 ValueToValueMapTy &ArgGVMap = getArgumentGVMap();
1603
1604 // Map for OpTypeRuntimeArray. If argument has pointer type, 2 spirv type
1605 // instructions are generated. They are OpTypePointer and OpTypeRuntimeArray.
1606 DenseMap<Type *, uint32_t> OpRuntimeTyMap;
1607
1608 for (Type *Ty : getTypeList()) {
1609 // Update TypeMap with nextID for reference later.
1610 TypeMap[Ty] = nextID;
1611
1612 switch (Ty->getTypeID()) {
1613 default: {
1614 Ty->print(errs());
1615 llvm_unreachable("Unsupported type???");
1616 break;
1617 }
1618 case Type::MetadataTyID:
1619 case Type::LabelTyID: {
1620 // Ignore these types.
1621 break;
1622 }
1623 case Type::PointerTyID: {
1624 PointerType *PTy = cast<PointerType>(Ty);
1625 unsigned AddrSpace = PTy->getAddressSpace();
1626
1627 // For the purposes of our Vulkan SPIR-V type system, constant and global
1628 // are conflated.
1629 bool UseExistingOpTypePointer = false;
1630 if (AddressSpace::Constant == AddrSpace) {
1631 AddrSpace = AddressSpace::Global;
1632
1633 // Check to see if we already created this type (for instance, if we had
1634 // a constant <type>* and a global <type>*, the type would be created by
1635 // one of these types, and shared by both).
1636 auto GlobalTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1637 if (0 < TypeMap.count(GlobalTy)) {
1638 TypeMap[PTy] = TypeMap[GlobalTy];
David Netoe439d702018-03-23 13:14:08 -07001639 UseExistingOpTypePointer = true;
David Neto22f144c2017-06-12 14:26:21 -04001640 break;
1641 }
1642 } else if (AddressSpace::Global == AddrSpace) {
1643 AddrSpace = AddressSpace::Constant;
1644
1645 // Check to see if we already created this type (for instance, if we had
1646 // a constant <type>* and a global <type>*, the type would be created by
1647 // one of these types, and shared by both).
1648 auto ConstantTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1649 if (0 < TypeMap.count(ConstantTy)) {
1650 TypeMap[PTy] = TypeMap[ConstantTy];
1651 UseExistingOpTypePointer = true;
1652 }
1653 }
1654
1655 bool IsOpTypeRuntimeArray = false;
1656 bool HasArgUser = false;
1657
1658 for (auto ArgGV : ArgGVMap) {
1659 auto Arg = ArgGV.first;
1660
1661 Type *ArgTy = Arg->getType();
1662 if (ArgTy == PTy) {
1663 if (AddrSpace != AddressSpace::UniformConstant) {
1664 IsOpTypeRuntimeArray = true;
1665 }
1666
1667 for (auto U : Arg->users()) {
1668 if (!isa<GetElementPtrInst>(U) || (U->getType() == PTy)) {
1669 HasArgUser = true;
1670 break;
1671 }
1672 }
1673 }
1674 }
1675
1676 if ((!IsOpTypeRuntimeArray || HasArgUser) && !UseExistingOpTypePointer) {
1677 //
1678 // Generate OpTypePointer.
1679 //
1680
1681 // OpTypePointer
1682 // Ops[0] = Storage Class
1683 // Ops[1] = Element Type ID
1684 SPIRVOperandList Ops;
1685
David Neto257c3892018-04-11 13:19:45 -04001686 Ops << MkNum(GetStorageClass(AddrSpace))
1687 << MkId(lookupType(PTy->getElementType()));
David Neto22f144c2017-06-12 14:26:21 -04001688
David Neto87846742018-04-11 17:36:22 -04001689 auto *Inst = new SPIRVInstruction(spv::OpTypePointer, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001690 SPIRVInstList.push_back(Inst);
1691 }
1692
1693 if (IsOpTypeRuntimeArray) {
1694 //
1695 // Generate OpTypeRuntimeArray.
1696 //
1697
1698 // OpTypeRuntimeArray
1699 // Ops[0] = Element Type ID
1700 SPIRVOperandList Ops;
1701
David Neto257c3892018-04-11 13:19:45 -04001702 Type *EleTy = PTy->getElementType();
1703 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04001704
David Neto22f144c2017-06-12 14:26:21 -04001705 uint32_t OpTypeRuntimeArrayID = nextID;
1706 assert(0 == OpRuntimeTyMap.count(Ty));
1707 OpRuntimeTyMap[Ty] = nextID;
1708
David Neto87846742018-04-11 17:36:22 -04001709 auto *Inst =
1710 new SPIRVInstruction(spv::OpTypeRuntimeArray, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001711 SPIRVInstList.push_back(Inst);
1712
1713 // Generate OpDecorate.
1714 auto DecoInsertPoint =
1715 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
1716 [](SPIRVInstruction *Inst) -> bool {
1717 return Inst->getOpcode() != spv::OpDecorate &&
1718 Inst->getOpcode() != spv::OpMemberDecorate &&
1719 Inst->getOpcode() != spv::OpExtInstImport;
1720 });
1721
1722 // Ops[0] = Target ID
1723 // Ops[1] = Decoration (ArrayStride)
1724 // Ops[2] = Stride Number(Literal Number)
1725 Ops.clear();
1726
David Neto257c3892018-04-11 13:19:45 -04001727 Ops << MkId(OpTypeRuntimeArrayID) << MkNum(spv::DecorationArrayStride)
1728 << MkNum(static_cast<uint32_t>(DL.getTypeAllocSize(EleTy)));
David Neto22f144c2017-06-12 14:26:21 -04001729
David Neto87846742018-04-11 17:36:22 -04001730 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001731 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
1732 }
1733 break;
1734 }
1735 case Type::StructTyID: {
1736 LLVMContext &Context = Ty->getContext();
1737
1738 StructType *STy = cast<StructType>(Ty);
1739
1740 // Handle sampler type.
1741 if (STy->isOpaque()) {
1742 if (STy->getName().equals("opencl.sampler_t")) {
1743 //
1744 // Generate OpTypeSampler
1745 //
1746 // Empty Ops.
1747 SPIRVOperandList Ops;
1748
David Neto87846742018-04-11 17:36:22 -04001749 auto *Inst = new SPIRVInstruction(spv::OpTypeSampler, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001750 SPIRVInstList.push_back(Inst);
1751 break;
1752 } else if (STy->getName().equals("opencl.image2d_ro_t") ||
1753 STy->getName().equals("opencl.image2d_wo_t") ||
1754 STy->getName().equals("opencl.image3d_ro_t") ||
1755 STy->getName().equals("opencl.image3d_wo_t")) {
1756 //
1757 // Generate OpTypeImage
1758 //
1759 // Ops[0] = Sampled Type ID
1760 // Ops[1] = Dim ID
1761 // Ops[2] = Depth (Literal Number)
1762 // Ops[3] = Arrayed (Literal Number)
1763 // Ops[4] = MS (Literal Number)
1764 // Ops[5] = Sampled (Literal Number)
1765 // Ops[6] = Image Format ID
1766 //
1767 SPIRVOperandList Ops;
1768
1769 // TODO: Changed Sampled Type according to situations.
1770 uint32_t SampledTyID = lookupType(Type::getFloatTy(Context));
David Neto257c3892018-04-11 13:19:45 -04001771 Ops << MkId(SampledTyID);
David Neto22f144c2017-06-12 14:26:21 -04001772
1773 spv::Dim DimID = spv::Dim2D;
1774 if (STy->getName().equals("opencl.image3d_ro_t") ||
1775 STy->getName().equals("opencl.image3d_wo_t")) {
1776 DimID = spv::Dim3D;
1777 }
David Neto257c3892018-04-11 13:19:45 -04001778 Ops << MkNum(DimID);
David Neto22f144c2017-06-12 14:26:21 -04001779
1780 // TODO: Set up Depth.
David Neto257c3892018-04-11 13:19:45 -04001781 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001782
1783 // TODO: Set up Arrayed.
David Neto257c3892018-04-11 13:19:45 -04001784 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001785
1786 // TODO: Set up MS.
David Neto257c3892018-04-11 13:19:45 -04001787 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001788
1789 // TODO: Set up Sampled.
1790 //
1791 // From Spec
1792 //
1793 // 0 indicates this is only known at run time, not at compile time
1794 // 1 indicates will be used with sampler
1795 // 2 indicates will be used without a sampler (a storage image)
1796 uint32_t Sampled = 1;
1797 if (STy->getName().equals("opencl.image2d_wo_t") ||
1798 STy->getName().equals("opencl.image3d_wo_t")) {
1799 Sampled = 2;
1800 }
David Neto257c3892018-04-11 13:19:45 -04001801 Ops << MkNum(Sampled);
David Neto22f144c2017-06-12 14:26:21 -04001802
1803 // TODO: Set up Image Format.
David Neto257c3892018-04-11 13:19:45 -04001804 Ops << MkNum(spv::ImageFormatUnknown);
David Neto22f144c2017-06-12 14:26:21 -04001805
David Neto87846742018-04-11 17:36:22 -04001806 auto *Inst = new SPIRVInstruction(spv::OpTypeImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001807 SPIRVInstList.push_back(Inst);
1808 break;
1809 }
1810 }
1811
1812 //
1813 // Generate OpTypeStruct
1814 //
1815 // Ops[0] ... Ops[n] = Member IDs
1816 SPIRVOperandList Ops;
1817
1818 for (auto *EleTy : STy->elements()) {
1819 uint32_t EleTyID = lookupType(EleTy);
1820
1821 // Check OpTypeRuntimeArray.
1822 if (isa<PointerType>(EleTy)) {
David Netoc6f3ab22018-04-06 18:02:31 -04001823 // TODO(dneto): Isn't this a straight lookup instead of a loop?
David Neto22f144c2017-06-12 14:26:21 -04001824 for (auto ArgGV : ArgGVMap) {
1825 Type *ArgTy = ArgGV.first->getType();
1826 if (ArgTy == EleTy) {
1827 assert(0 != OpRuntimeTyMap.count(EleTy));
1828 EleTyID = OpRuntimeTyMap[EleTy];
1829 }
1830 }
1831 }
1832
David Neto257c3892018-04-11 13:19:45 -04001833 Ops << MkId(EleTyID);
David Neto22f144c2017-06-12 14:26:21 -04001834 }
1835
David Neto22f144c2017-06-12 14:26:21 -04001836 uint32_t STyID = nextID;
1837
David Neto87846742018-04-11 17:36:22 -04001838 auto *Inst =
1839 new SPIRVInstruction(spv::OpTypeStruct, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001840 SPIRVInstList.push_back(Inst);
1841
1842 // Generate OpMemberDecorate.
1843 auto DecoInsertPoint =
1844 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
1845 [](SPIRVInstruction *Inst) -> bool {
1846 return Inst->getOpcode() != spv::OpDecorate &&
1847 Inst->getOpcode() != spv::OpMemberDecorate &&
1848 Inst->getOpcode() != spv::OpExtInstImport;
1849 });
1850
David Netoc463b372017-08-10 15:32:21 -04001851 const auto StructLayout = DL.getStructLayout(STy);
1852
David Neto22f144c2017-06-12 14:26:21 -04001853 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
1854 MemberIdx++) {
1855 // Ops[0] = Structure Type ID
1856 // Ops[1] = Member Index(Literal Number)
1857 // Ops[2] = Decoration (Offset)
1858 // Ops[3] = Byte Offset (Literal Number)
1859 Ops.clear();
1860
David Neto257c3892018-04-11 13:19:45 -04001861 Ops << MkId(STyID) << MkNum(MemberIdx) << MkNum(spv::DecorationOffset);
David Neto22f144c2017-06-12 14:26:21 -04001862
David Netoc463b372017-08-10 15:32:21 -04001863 const auto ByteOffset =
1864 uint32_t(StructLayout->getElementOffset(MemberIdx));
David Neto257c3892018-04-11 13:19:45 -04001865 Ops << MkNum(ByteOffset);
David Neto22f144c2017-06-12 14:26:21 -04001866
David Neto87846742018-04-11 17:36:22 -04001867 auto *DecoInst = new SPIRVInstruction(spv::OpMemberDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001868 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04001869 }
1870
1871 // Generate OpDecorate.
1872 for (auto ArgGV : ArgGVMap) {
1873 Type *ArgGVTy = ArgGV.second->getType();
1874 PointerType *PTy = cast<PointerType>(ArgGVTy);
1875 Type *ArgTy = PTy->getElementType();
1876
1877 // Struct type from argument is already distinguished with the other
1878 // struct types on llvm types. As a result, if current processing struct
1879 // type is same with argument type, we can generate OpDecorate with
1880 // Block or BufferBlock.
1881 if (ArgTy == STy) {
1882 // Ops[0] = Target ID
1883 // Ops[1] = Decoration (Block or BufferBlock)
1884 Ops.clear();
1885
David Neto6e392822017-08-04 14:06:10 -04001886 // Use Block decorations with StorageBuffer storage class.
David Neto257c3892018-04-11 13:19:45 -04001887 Ops << MkId(STyID) << MkNum(spv::DecorationBlock);
David Neto22f144c2017-06-12 14:26:21 -04001888
David Neto87846742018-04-11 17:36:22 -04001889 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001890 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
1891 break;
1892 }
1893 }
1894 break;
1895 }
1896 case Type::IntegerTyID: {
1897 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
1898
1899 if (BitWidth == 1) {
David Neto87846742018-04-11 17:36:22 -04001900 auto *Inst = new SPIRVInstruction(spv::OpTypeBool, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04001901 SPIRVInstList.push_back(Inst);
1902 } else {
1903 // i8 is added to TypeMap as i32.
David Neto391aeb12017-08-26 15:51:58 -04001904 // No matter what LLVM type is requested first, always alias the
1905 // second one's SPIR-V type to be the same as the one we generated
1906 // first.
Neil Henning39672102017-09-29 14:33:13 +01001907 unsigned aliasToWidth = 0;
David Neto22f144c2017-06-12 14:26:21 -04001908 if (BitWidth == 8) {
David Neto391aeb12017-08-26 15:51:58 -04001909 aliasToWidth = 32;
David Neto22f144c2017-06-12 14:26:21 -04001910 BitWidth = 32;
David Neto391aeb12017-08-26 15:51:58 -04001911 } else if (BitWidth == 32) {
1912 aliasToWidth = 8;
1913 }
1914 if (aliasToWidth) {
1915 Type* otherType = Type::getIntNTy(Ty->getContext(), aliasToWidth);
1916 auto where = TypeMap.find(otherType);
1917 if (where == TypeMap.end()) {
1918 // Go ahead and make it, but also map the other type to it.
1919 TypeMap[otherType] = nextID;
1920 } else {
1921 // Alias this SPIR-V type the existing type.
1922 TypeMap[Ty] = where->second;
1923 break;
1924 }
David Neto22f144c2017-06-12 14:26:21 -04001925 }
1926
David Neto257c3892018-04-11 13:19:45 -04001927 SPIRVOperandList Ops;
1928 Ops << MkNum(BitWidth) << MkNum(0 /* not signed */);
David Neto22f144c2017-06-12 14:26:21 -04001929
1930 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04001931 new SPIRVInstruction(spv::OpTypeInt, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04001932 }
1933 break;
1934 }
1935 case Type::HalfTyID:
1936 case Type::FloatTyID:
1937 case Type::DoubleTyID: {
1938 SPIRVOperand *WidthOp = new SPIRVOperand(
1939 SPIRVOperandType::LITERAL_INTEGER, Ty->getPrimitiveSizeInBits());
1940
1941 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04001942 new SPIRVInstruction(spv::OpTypeFloat, nextID++, WidthOp));
David Neto22f144c2017-06-12 14:26:21 -04001943 break;
1944 }
1945 case Type::ArrayTyID: {
1946 LLVMContext &Context = Ty->getContext();
1947 ArrayType *ArrTy = cast<ArrayType>(Ty);
1948 //
1949 // Generate OpConstant and OpTypeArray.
1950 //
1951
1952 //
1953 // Generate OpConstant for array length.
1954 //
1955 // Ops[0] = Result Type ID
1956 // Ops[1] .. Ops[n] = Values LiteralNumber
1957 SPIRVOperandList Ops;
1958
1959 Type *LengthTy = Type::getInt32Ty(Context);
1960 uint32_t ResTyID = lookupType(LengthTy);
David Neto257c3892018-04-11 13:19:45 -04001961 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04001962
1963 uint64_t Length = ArrTy->getArrayNumElements();
1964 assert(Length < UINT32_MAX);
David Neto257c3892018-04-11 13:19:45 -04001965 Ops << MkNum(static_cast<uint32_t>(Length));
David Neto22f144c2017-06-12 14:26:21 -04001966
1967 // Add constant for length to constant list.
1968 Constant *CstLength = ConstantInt::get(LengthTy, Length);
1969 AllocatedVMap[CstLength] = nextID;
1970 VMap[CstLength] = nextID;
1971 uint32_t LengthID = nextID;
1972
David Neto87846742018-04-11 17:36:22 -04001973 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001974 SPIRVInstList.push_back(CstInst);
1975
David Neto85082642018-03-24 06:55:20 -07001976 // Remember to generate ArrayStride later
1977 getTypesNeedingArrayStride().insert(Ty);
1978
David Neto22f144c2017-06-12 14:26:21 -04001979 //
1980 // Generate OpTypeArray.
1981 //
1982 // Ops[0] = Element Type ID
1983 // Ops[1] = Array Length Constant ID
1984 Ops.clear();
1985
1986 uint32_t EleTyID = lookupType(ArrTy->getElementType());
David Neto257c3892018-04-11 13:19:45 -04001987 Ops << MkId(EleTyID) << MkId(LengthID);
David Neto22f144c2017-06-12 14:26:21 -04001988
1989 // Update TypeMap with nextID.
1990 TypeMap[Ty] = nextID;
1991
David Neto87846742018-04-11 17:36:22 -04001992 auto *ArrayInst = new SPIRVInstruction(spv::OpTypeArray, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001993 SPIRVInstList.push_back(ArrayInst);
1994 break;
1995 }
1996 case Type::VectorTyID: {
1997 // <4 x i8> is changed to i32.
1998 LLVMContext &Context = Ty->getContext();
1999 if (Ty->getVectorElementType() == Type::getInt8Ty(Context)) {
2000 if (Ty->getVectorNumElements() == 4) {
2001 TypeMap[Ty] = lookupType(Ty->getVectorElementType());
2002 break;
2003 } else {
2004 Ty->print(errs());
2005 llvm_unreachable("Support above i8 vector type");
2006 }
2007 }
2008
2009 // Ops[0] = Component Type ID
2010 // Ops[1] = Component Count (Literal Number)
David Neto257c3892018-04-11 13:19:45 -04002011 SPIRVOperandList Ops;
2012 Ops << MkId(lookupType(Ty->getVectorElementType()))
2013 << MkNum(Ty->getVectorNumElements());
David Neto22f144c2017-06-12 14:26:21 -04002014
David Neto87846742018-04-11 17:36:22 -04002015 SPIRVInstruction* inst = new SPIRVInstruction(spv::OpTypeVector, nextID++, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002016 SPIRVInstList.push_back(inst);
David Neto22f144c2017-06-12 14:26:21 -04002017 break;
2018 }
2019 case Type::VoidTyID: {
David Neto87846742018-04-11 17:36:22 -04002020 auto *Inst = new SPIRVInstruction(spv::OpTypeVoid, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04002021 SPIRVInstList.push_back(Inst);
2022 break;
2023 }
2024 case Type::FunctionTyID: {
2025 // Generate SPIRV instruction for function type.
2026 FunctionType *FTy = cast<FunctionType>(Ty);
2027
2028 // Ops[0] = Return Type ID
2029 // Ops[1] ... Ops[n] = Parameter Type IDs
2030 SPIRVOperandList Ops;
2031
2032 // Find SPIRV instruction for return type
David Netoc6f3ab22018-04-06 18:02:31 -04002033 Ops << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04002034
2035 // Find SPIRV instructions for parameter types
2036 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
2037 // Find SPIRV instruction for parameter type.
2038 auto ParamTy = FTy->getParamType(k);
2039 if (ParamTy->isPointerTy()) {
2040 auto PointeeTy = ParamTy->getPointerElementType();
2041 if (PointeeTy->isStructTy() &&
2042 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
2043 ParamTy = PointeeTy;
2044 }
2045 }
2046
David Netoc6f3ab22018-04-06 18:02:31 -04002047 Ops << MkId(lookupType(ParamTy));
David Neto22f144c2017-06-12 14:26:21 -04002048 }
2049
David Neto87846742018-04-11 17:36:22 -04002050 auto *Inst = new SPIRVInstruction(spv::OpTypeFunction, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002051 SPIRVInstList.push_back(Inst);
2052 break;
2053 }
2054 }
2055 }
2056
2057 // Generate OpTypeSampledImage.
2058 TypeMapType &OpImageTypeMap = getImageTypeMap();
2059 for (auto &ImageType : OpImageTypeMap) {
2060 //
2061 // Generate OpTypeSampledImage.
2062 //
2063 // Ops[0] = Image Type ID
2064 //
2065 SPIRVOperandList Ops;
2066
2067 Type *ImgTy = ImageType.first;
David Netoc6f3ab22018-04-06 18:02:31 -04002068 Ops << MkId(TypeMap[ImgTy]);
David Neto22f144c2017-06-12 14:26:21 -04002069
2070 // Update OpImageTypeMap.
2071 ImageType.second = nextID;
2072
David Neto87846742018-04-11 17:36:22 -04002073 auto *Inst = new SPIRVInstruction(spv::OpTypeSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002074 SPIRVInstList.push_back(Inst);
2075 }
David Netoc6f3ab22018-04-06 18:02:31 -04002076
2077 // Generate types for pointer-to-local arguments.
2078 for (auto* arg : LocalArgs) {
2079
2080 LocalArgInfo& arg_info = LocalArgMap[arg];
2081
2082 // Generate the spec constant.
2083 SPIRVOperandList Ops;
2084 Ops << MkId(lookupType(Type::getInt32Ty(Context))) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04002085 SPIRVInstList.push_back(
2086 new SPIRVInstruction(spv::OpSpecConstant, arg_info.array_size_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002087
2088 // Generate the array type.
2089 Ops.clear();
2090 // The element type must have been created.
2091 uint32_t elem_ty_id = lookupType(arg_info.elem_type);
2092 assert(elem_ty_id);
2093 Ops << MkId(elem_ty_id) << MkId(arg_info.array_size_id);
2094
2095 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002096 new SPIRVInstruction(spv::OpTypeArray, arg_info.array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002097
2098 Ops.clear();
2099 Ops << MkNum(spv::StorageClassWorkgroup) << MkId(arg_info.array_type_id);
David Neto87846742018-04-11 17:36:22 -04002100 SPIRVInstList.push_back(new SPIRVInstruction(
2101 spv::OpTypePointer, arg_info.ptr_array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002102 }
David Neto22f144c2017-06-12 14:26:21 -04002103}
2104
2105void SPIRVProducerPass::GenerateSPIRVConstants() {
2106 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2107 ValueMapType &VMap = getValueMap();
2108 ValueMapType &AllocatedVMap = getAllocatedValueMap();
2109 ValueList &CstList = getConstantList();
David Neto482550a2018-03-24 05:21:07 -07002110 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04002111
2112 for (uint32_t i = 0; i < CstList.size(); i++) {
David Netofb9a7972017-08-25 17:08:24 -04002113 // UniqueVector ids are 1-based.
2114 Constant *Cst = cast<Constant>(CstList[i+1]);
David Neto22f144c2017-06-12 14:26:21 -04002115
2116 // OpTypeArray's constant was already generated.
David Netofb9a7972017-08-25 17:08:24 -04002117 if (AllocatedVMap.find_as(Cst) != AllocatedVMap.end()) {
David Neto22f144c2017-06-12 14:26:21 -04002118 continue;
2119 }
2120
David Netofb9a7972017-08-25 17:08:24 -04002121 // Set ValueMap with nextID for reference later.
David Neto22f144c2017-06-12 14:26:21 -04002122 VMap[Cst] = nextID;
2123
2124 //
2125 // Generate OpConstant.
2126 //
2127
2128 // Ops[0] = Result Type ID
2129 // Ops[1] .. Ops[n] = Values LiteralNumber
2130 SPIRVOperandList Ops;
2131
David Neto257c3892018-04-11 13:19:45 -04002132 Ops << MkId(lookupType(Cst->getType()));
David Neto22f144c2017-06-12 14:26:21 -04002133
2134 std::vector<uint32_t> LiteralNum;
David Neto22f144c2017-06-12 14:26:21 -04002135 spv::Op Opcode = spv::OpNop;
2136
2137 if (isa<UndefValue>(Cst)) {
2138 // Ops[0] = Result Type ID
David Netoc66b3352017-10-20 14:28:46 -04002139 Opcode = spv::OpUndef;
2140 if (hack_undef) {
2141 Type *type = Cst->getType();
2142 if (type->isFPOrFPVectorTy() || type->isIntOrIntVectorTy()) {
2143 Opcode = spv::OpConstantNull;
2144 }
2145 }
David Neto22f144c2017-06-12 14:26:21 -04002146 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
2147 unsigned BitWidth = CI->getBitWidth();
2148 if (BitWidth == 1) {
2149 // If the bitwidth of constant is 1, generate OpConstantTrue or
2150 // OpConstantFalse.
2151 if (CI->getZExtValue()) {
2152 // Ops[0] = Result Type ID
2153 Opcode = spv::OpConstantTrue;
2154 } else {
2155 // Ops[0] = Result Type ID
2156 Opcode = spv::OpConstantFalse;
2157 }
David Neto22f144c2017-06-12 14:26:21 -04002158 } else {
2159 auto V = CI->getZExtValue();
2160 LiteralNum.push_back(V & 0xFFFFFFFF);
2161
2162 if (BitWidth > 32) {
2163 LiteralNum.push_back(V >> 32);
2164 }
2165
2166 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002167
David Neto257c3892018-04-11 13:19:45 -04002168 Ops << MkInteger(LiteralNum);
2169
2170 if (BitWidth == 32 && V == 0) {
2171 constant_i32_zero_id_ = nextID;
2172 }
David Neto22f144c2017-06-12 14:26:21 -04002173 }
2174 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2175 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2176 Type *CFPTy = CFP->getType();
2177 if (CFPTy->isFloatTy()) {
2178 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2179 } else {
2180 CFPTy->print(errs());
2181 llvm_unreachable("Implement this ConstantFP Type");
2182 }
2183
2184 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002185
David Neto257c3892018-04-11 13:19:45 -04002186 Ops << MkFloat(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002187 } else if (isa<ConstantDataSequential>(Cst) &&
2188 cast<ConstantDataSequential>(Cst)->isString()) {
2189 Cst->print(errs());
2190 llvm_unreachable("Implement this Constant");
2191
2192 } else if (const ConstantDataSequential *CDS =
2193 dyn_cast<ConstantDataSequential>(Cst)) {
David Neto49351ac2017-08-26 17:32:20 -04002194 // Let's convert <4 x i8> constant to int constant specially.
2195 // This case occurs when all the values are specified as constant
2196 // ints.
2197 Type *CstTy = Cst->getType();
2198 if (is4xi8vec(CstTy)) {
2199 LLVMContext &Context = CstTy->getContext();
2200
2201 //
2202 // Generate OpConstant with OpTypeInt 32 0.
2203 //
Neil Henning39672102017-09-29 14:33:13 +01002204 uint32_t IntValue = 0;
2205 for (unsigned k = 0; k < 4; k++) {
2206 const uint64_t Val = CDS->getElementAsInteger(k);
David Neto49351ac2017-08-26 17:32:20 -04002207 IntValue = (IntValue << 8) | (Val & 0xffu);
2208 }
2209
2210 Type *i32 = Type::getInt32Ty(Context);
2211 Constant *CstInt = ConstantInt::get(i32, IntValue);
2212 // If this constant is already registered on VMap, use it.
2213 if (VMap.count(CstInt)) {
2214 uint32_t CstID = VMap[CstInt];
2215 VMap[Cst] = CstID;
2216 continue;
2217 }
2218
David Neto257c3892018-04-11 13:19:45 -04002219 Ops << MkNum(IntValue);
David Neto49351ac2017-08-26 17:32:20 -04002220
David Neto87846742018-04-11 17:36:22 -04002221 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto49351ac2017-08-26 17:32:20 -04002222 SPIRVInstList.push_back(CstInst);
2223
2224 continue;
2225 }
2226
2227 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002228 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
2229 Constant *EleCst = CDS->getElementAsConstant(k);
2230 uint32_t EleCstID = VMap[EleCst];
David Neto257c3892018-04-11 13:19:45 -04002231 Ops << MkId(EleCstID);
David Neto22f144c2017-06-12 14:26:21 -04002232 }
2233
2234 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002235 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2236 // Let's convert <4 x i8> constant to int constant specially.
David Neto49351ac2017-08-26 17:32:20 -04002237 // This case occurs when at least one of the values is an undef.
David Neto22f144c2017-06-12 14:26:21 -04002238 Type *CstTy = Cst->getType();
2239 if (is4xi8vec(CstTy)) {
2240 LLVMContext &Context = CstTy->getContext();
2241
2242 //
2243 // Generate OpConstant with OpTypeInt 32 0.
2244 //
Neil Henning39672102017-09-29 14:33:13 +01002245 uint32_t IntValue = 0;
David Neto22f144c2017-06-12 14:26:21 -04002246 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2247 I != E; ++I) {
2248 uint64_t Val = 0;
David Neto49351ac2017-08-26 17:32:20 -04002249 const Value* CV = *I;
Neil Henning39672102017-09-29 14:33:13 +01002250 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2251 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002252 }
David Neto49351ac2017-08-26 17:32:20 -04002253 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002254 }
2255
David Neto49351ac2017-08-26 17:32:20 -04002256 Type *i32 = Type::getInt32Ty(Context);
2257 Constant *CstInt = ConstantInt::get(i32, IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002258 // If this constant is already registered on VMap, use it.
2259 if (VMap.count(CstInt)) {
2260 uint32_t CstID = VMap[CstInt];
2261 VMap[Cst] = CstID;
David Neto19a1bad2017-08-25 15:01:41 -04002262 continue;
David Neto22f144c2017-06-12 14:26:21 -04002263 }
2264
David Neto257c3892018-04-11 13:19:45 -04002265 Ops << MkNum(IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002266
David Neto87846742018-04-11 17:36:22 -04002267 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002268 SPIRVInstList.push_back(CstInst);
2269
David Neto19a1bad2017-08-25 15:01:41 -04002270 continue;
David Neto22f144c2017-06-12 14:26:21 -04002271 }
2272
2273 // We use a constant composite in SPIR-V for our constant aggregate in
2274 // LLVM.
2275 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002276
2277 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
2278 // Look up the ID of the element of this aggregate (which we will
2279 // previously have created a constant for).
2280 uint32_t ElementConstantID = VMap[CA->getAggregateElement(k)];
2281
2282 // And add an operand to the composite we are constructing
David Neto257c3892018-04-11 13:19:45 -04002283 Ops << MkId(ElementConstantID);
David Neto22f144c2017-06-12 14:26:21 -04002284 }
2285 } else if (Cst->isNullValue()) {
2286 Opcode = spv::OpConstantNull;
David Neto22f144c2017-06-12 14:26:21 -04002287 } else {
2288 Cst->print(errs());
2289 llvm_unreachable("Unsupported Constant???");
2290 }
2291
David Neto87846742018-04-11 17:36:22 -04002292 auto *CstInst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002293 SPIRVInstList.push_back(CstInst);
2294 }
2295}
2296
2297void SPIRVProducerPass::GenerateSamplers(Module &M) {
2298 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2299 ValueMapType &VMap = getValueMap();
2300
2301 DenseMap<unsigned, unsigned> SamplerLiteralToIDMap;
2302
2303 unsigned BindingIdx = 0;
2304
2305 // Generate the sampler map.
2306 for (auto SamplerLiteral : getSamplerMap()) {
2307 // Generate OpVariable.
2308 //
2309 // GIDOps[0] : Result Type ID
2310 // GIDOps[1] : Storage Class
2311 SPIRVOperandList Ops;
2312
David Neto257c3892018-04-11 13:19:45 -04002313 Ops << MkId(lookupType(SamplerTy))
2314 << MkNum(spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002315
David Neto87846742018-04-11 17:36:22 -04002316 auto *Inst = new SPIRVInstruction(spv::OpVariable, nextID, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002317 SPIRVInstList.push_back(Inst);
2318
David Neto44795152017-07-13 15:45:28 -04002319 SamplerLiteralToIDMap[SamplerLiteral.first] = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04002320
2321 // Find Insert Point for OpDecorate.
2322 auto DecoInsertPoint =
2323 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2324 [](SPIRVInstruction *Inst) -> bool {
2325 return Inst->getOpcode() != spv::OpDecorate &&
2326 Inst->getOpcode() != spv::OpMemberDecorate &&
2327 Inst->getOpcode() != spv::OpExtInstImport;
2328 });
2329
2330 // Ops[0] = Target ID
2331 // Ops[1] = Decoration (DescriptorSet)
2332 // Ops[2] = LiteralNumber according to Decoration
2333 Ops.clear();
2334
David Neto257c3892018-04-11 13:19:45 -04002335 uint32_t ArgID = SamplerLiteralToIDMap[SamplerLiteral.first];
2336 Ops << MkId(ArgID) << MkNum(spv::DecorationDescriptorSet)
2337 << MkNum(NextDescriptorSetIndex);
David Neto22f144c2017-06-12 14:26:21 -04002338
David Neto44795152017-07-13 15:45:28 -04002339 descriptorMapOut << "sampler," << SamplerLiteral.first << ",samplerExpr,\""
David Neto257c3892018-04-11 13:19:45 -04002340 << SamplerLiteral.second << "\",descriptorSet,"
2341 << NextDescriptorSetIndex << ",binding," << BindingIdx
2342 << "\n";
David Neto22f144c2017-06-12 14:26:21 -04002343
David Neto87846742018-04-11 17:36:22 -04002344 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002345 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2346
2347 // Ops[0] = Target ID
2348 // Ops[1] = Decoration (Binding)
2349 // Ops[2] = LiteralNumber according to Decoration
2350 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002351 Ops << MkId(ArgID) << MkNum(spv::DecorationBinding) << MkNum(BindingIdx);
2352 BindingIdx++;
David Neto22f144c2017-06-12 14:26:21 -04002353
David Neto87846742018-04-11 17:36:22 -04002354 auto *BindDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002355 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
2356 }
David Neto85082642018-03-24 06:55:20 -07002357 if (BindingIdx > 0) {
2358 // We generated something.
2359 ++NextDescriptorSetIndex;
2360 }
David Neto22f144c2017-06-12 14:26:21 -04002361
2362 const char *TranslateSamplerFunctionName = "__translate_sampler_initializer";
2363
2364 auto SamplerFunction = M.getFunction(TranslateSamplerFunctionName);
2365
2366 // If there are no uses of the sampler function, no work to do!
2367 if (!SamplerFunction) {
2368 return;
2369 }
2370
2371 // Iterate through the users of the sampler function.
2372 for (auto User : SamplerFunction->users()) {
2373 if (auto CI = dyn_cast<CallInst>(User)) {
2374 // Get the literal used to initialize the sampler.
2375 auto Constant = dyn_cast<ConstantInt>(CI->getArgOperand(0));
2376
2377 if (!Constant) {
2378 CI->getArgOperand(0)->print(errs());
2379 llvm_unreachable("Argument of sampler initializer was non-constant!");
2380 }
2381
2382 auto SamplerLiteral = static_cast<unsigned>(Constant->getZExtValue());
2383
2384 if (0 == SamplerLiteralToIDMap.count(SamplerLiteral)) {
2385 Constant->print(errs());
2386 llvm_unreachable("Sampler literal was not found in sampler map!");
2387 }
2388
2389 // Calls to the sampler literal function to initialize a sampler are
2390 // re-routed to the global variables declared for the sampler.
2391 VMap[CI] = SamplerLiteralToIDMap[SamplerLiteral];
2392 }
2393 }
2394}
2395
2396void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
2397 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2398 ValueMapType &VMap = getValueMap();
2399 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07002400 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002401
2402 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2403 Type *Ty = GV.getType();
2404 PointerType *PTy = cast<PointerType>(Ty);
2405
2406 uint32_t InitializerID = 0;
2407
2408 // Workgroup size is handled differently (it goes into a constant)
2409 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2410 std::vector<bool> HasMDVec;
2411 uint32_t PrevXDimCst = 0xFFFFFFFF;
2412 uint32_t PrevYDimCst = 0xFFFFFFFF;
2413 uint32_t PrevZDimCst = 0xFFFFFFFF;
2414 for (Function &Func : *GV.getParent()) {
2415 if (Func.isDeclaration()) {
2416 continue;
2417 }
2418
2419 // We only need to check kernels.
2420 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2421 continue;
2422 }
2423
2424 if (const MDNode *MD =
2425 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2426 uint32_t CurXDimCst = static_cast<uint32_t>(
2427 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2428 uint32_t CurYDimCst = static_cast<uint32_t>(
2429 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2430 uint32_t CurZDimCst = static_cast<uint32_t>(
2431 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2432
2433 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2434 PrevZDimCst == 0xFFFFFFFF) {
2435 PrevXDimCst = CurXDimCst;
2436 PrevYDimCst = CurYDimCst;
2437 PrevZDimCst = CurZDimCst;
2438 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2439 CurZDimCst != PrevZDimCst) {
2440 llvm_unreachable(
2441 "reqd_work_group_size must be the same across all kernels");
2442 } else {
2443 continue;
2444 }
2445
2446 //
2447 // Generate OpConstantComposite.
2448 //
2449 // Ops[0] : Result Type ID
2450 // Ops[1] : Constant size for x dimension.
2451 // Ops[2] : Constant size for y dimension.
2452 // Ops[3] : Constant size for z dimension.
2453 SPIRVOperandList Ops;
2454
2455 uint32_t XDimCstID =
2456 VMap[mdconst::extract<ConstantInt>(MD->getOperand(0))];
2457 uint32_t YDimCstID =
2458 VMap[mdconst::extract<ConstantInt>(MD->getOperand(1))];
2459 uint32_t ZDimCstID =
2460 VMap[mdconst::extract<ConstantInt>(MD->getOperand(2))];
2461
2462 InitializerID = nextID;
2463
David Neto257c3892018-04-11 13:19:45 -04002464 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2465 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002466
David Neto87846742018-04-11 17:36:22 -04002467 auto *Inst =
2468 new SPIRVInstruction(spv::OpConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002469 SPIRVInstList.push_back(Inst);
2470
2471 HasMDVec.push_back(true);
2472 } else {
2473 HasMDVec.push_back(false);
2474 }
2475 }
2476
2477 // Check all kernels have same definitions for work_group_size.
2478 bool HasMD = false;
2479 if (!HasMDVec.empty()) {
2480 HasMD = HasMDVec[0];
2481 for (uint32_t i = 1; i < HasMDVec.size(); i++) {
2482 if (HasMD != HasMDVec[i]) {
2483 llvm_unreachable(
2484 "Kernels should have consistent work group size definition");
2485 }
2486 }
2487 }
2488
2489 // If all kernels do not have metadata for reqd_work_group_size, generate
2490 // OpSpecConstants for x/y/z dimension.
2491 if (!HasMD) {
2492 //
2493 // Generate OpSpecConstants for x/y/z dimension.
2494 //
2495 // Ops[0] : Result Type ID
2496 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
2497 uint32_t XDimCstID = 0;
2498 uint32_t YDimCstID = 0;
2499 uint32_t ZDimCstID = 0;
2500
David Neto22f144c2017-06-12 14:26:21 -04002501 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04002502 uint32_t result_type_id =
2503 lookupType(Ty->getPointerElementType()->getSequentialElementType());
David Neto22f144c2017-06-12 14:26:21 -04002504
David Neto257c3892018-04-11 13:19:45 -04002505 // X Dimension
2506 Ops << MkId(result_type_id) << MkNum(1);
2507 XDimCstID = nextID++;
2508 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002509 new SPIRVInstruction(spv::OpSpecConstant, XDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002510
2511 // Y Dimension
2512 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002513 Ops << MkId(result_type_id) << MkNum(1);
2514 YDimCstID = nextID++;
2515 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002516 new SPIRVInstruction(spv::OpSpecConstant, YDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002517
2518 // Z Dimension
2519 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002520 Ops << MkId(result_type_id) << MkNum(1);
2521 ZDimCstID = nextID++;
2522 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002523 new SPIRVInstruction(spv::OpSpecConstant, ZDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002524
David Neto22f144c2017-06-12 14:26:21 -04002525
David Neto257c3892018-04-11 13:19:45 -04002526 BuiltinDimVec.push_back(XDimCstID);
2527 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002528 BuiltinDimVec.push_back(ZDimCstID);
2529
David Neto22f144c2017-06-12 14:26:21 -04002530
2531 //
2532 // Generate OpSpecConstantComposite.
2533 //
2534 // Ops[0] : Result Type ID
2535 // Ops[1] : Constant size for x dimension.
2536 // Ops[2] : Constant size for y dimension.
2537 // Ops[3] : Constant size for z dimension.
2538 InitializerID = nextID;
2539
2540 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002541 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2542 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002543
David Neto87846742018-04-11 17:36:22 -04002544 auto *Inst =
2545 new SPIRVInstruction(spv::OpSpecConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002546 SPIRVInstList.push_back(Inst);
2547 }
2548 }
2549
David Neto22f144c2017-06-12 14:26:21 -04002550 VMap[&GV] = nextID;
2551
2552 //
2553 // Generate OpVariable.
2554 //
2555 // GIDOps[0] : Result Type ID
2556 // GIDOps[1] : Storage Class
2557 SPIRVOperandList Ops;
2558
David Neto85082642018-03-24 06:55:20 -07002559 const auto AS = PTy->getAddressSpace();
David Netoc6f3ab22018-04-06 18:02:31 -04002560 Ops << MkId(lookupType(Ty)) << MkNum(GetStorageClass(AS));
David Neto22f144c2017-06-12 14:26:21 -04002561
David Neto85082642018-03-24 06:55:20 -07002562 if (GV.hasInitializer()) {
2563 InitializerID = VMap[GV.getInitializer()];
David Neto22f144c2017-06-12 14:26:21 -04002564 }
2565
David Neto85082642018-03-24 06:55:20 -07002566 const bool module_scope_constant_external_init =
2567 (0 != InitializerID) && (AS == AddressSpace::Constant) &&
2568 clspv::Option::ModuleConstantsInStorageBuffer();
2569
2570 if (0 != InitializerID) {
2571 if (!module_scope_constant_external_init) {
2572 // Emit the ID of the intiializer as part of the variable definition.
David Netoc6f3ab22018-04-06 18:02:31 -04002573 Ops << MkId(InitializerID);
David Neto85082642018-03-24 06:55:20 -07002574 }
2575 }
2576 const uint32_t var_id = nextID++;
2577
David Neto87846742018-04-11 17:36:22 -04002578 auto *Inst = new SPIRVInstruction(spv::OpVariable, var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002579 SPIRVInstList.push_back(Inst);
2580
2581 // If we have a builtin.
2582 if (spv::BuiltInMax != BuiltinType) {
2583 // Find Insert Point for OpDecorate.
2584 auto DecoInsertPoint =
2585 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2586 [](SPIRVInstruction *Inst) -> bool {
2587 return Inst->getOpcode() != spv::OpDecorate &&
2588 Inst->getOpcode() != spv::OpMemberDecorate &&
2589 Inst->getOpcode() != spv::OpExtInstImport;
2590 });
2591 //
2592 // Generate OpDecorate.
2593 //
2594 // DOps[0] = Target ID
2595 // DOps[1] = Decoration (Builtin)
2596 // DOps[2] = BuiltIn ID
2597 uint32_t ResultID;
2598
2599 // WorkgroupSize is different, we decorate the constant composite that has
2600 // its value, rather than the variable that we use to access the value.
2601 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2602 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04002603 // Save both the value and variable IDs for later.
2604 WorkgroupSizeValueID = InitializerID;
2605 WorkgroupSizeVarID = VMap[&GV];
David Neto22f144c2017-06-12 14:26:21 -04002606 } else {
2607 ResultID = VMap[&GV];
2608 }
2609
2610 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002611 DOps << MkId(ResultID) << MkNum(spv::DecorationBuiltIn)
2612 << MkNum(BuiltinType);
David Neto22f144c2017-06-12 14:26:21 -04002613
David Neto87846742018-04-11 17:36:22 -04002614 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, DOps);
David Neto22f144c2017-06-12 14:26:21 -04002615 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
David Neto85082642018-03-24 06:55:20 -07002616 } else if (module_scope_constant_external_init) {
2617 // This module scope constant is initialized from a storage buffer with data
2618 // provided by the host at binding 0 of the next descriptor set.
2619 const uint32_t descriptor_set = NextDescriptorSetIndex++;
2620
2621 // Emit the intiialier to the descriptor map file.
2622 // Use "kind,buffer" to indicate storage buffer. We might want to expand
2623 // that later to other types, like uniform buffer.
2624 descriptorMapOut << "constant,descriptorSet," << descriptor_set
2625 << ",binding,0,kind,buffer,hexbytes,";
2626 clspv::ConstantEmitter(DL, descriptorMapOut).Emit(GV.getInitializer());
2627 descriptorMapOut << "\n";
2628
2629 // Find Insert Point for OpDecorate.
2630 auto DecoInsertPoint =
2631 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2632 [](SPIRVInstruction *Inst) -> bool {
2633 return Inst->getOpcode() != spv::OpDecorate &&
2634 Inst->getOpcode() != spv::OpMemberDecorate &&
2635 Inst->getOpcode() != spv::OpExtInstImport;
2636 });
2637
David Neto257c3892018-04-11 13:19:45 -04002638 // OpDecorate %var Binding <binding>
David Neto85082642018-03-24 06:55:20 -07002639 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002640 DOps << MkId(var_id) << MkNum(spv::DecorationBinding) << MkNum(0);
2641 DecoInsertPoint = SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04002642 DecoInsertPoint, new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto85082642018-03-24 06:55:20 -07002643
2644 // OpDecorate %var DescriptorSet <descriptor_set>
2645 DOps.clear();
David Neto257c3892018-04-11 13:19:45 -04002646 DOps << MkId(var_id) << MkNum(spv::DecorationDescriptorSet)
2647 << MkNum(descriptor_set);
David Netoc6f3ab22018-04-06 18:02:31 -04002648 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04002649 new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto22f144c2017-06-12 14:26:21 -04002650 }
2651}
2652
David Netoc6f3ab22018-04-06 18:02:31 -04002653void SPIRVProducerPass::GenerateWorkgroupVars() {
2654 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2655 for (auto* arg : LocalArgs) {
2656 const auto& info = LocalArgMap[arg];
2657
2658 // Generate OpVariable.
2659 //
2660 // GIDOps[0] : Result Type ID
2661 // GIDOps[1] : Storage Class
2662 SPIRVOperandList Ops;
2663 Ops << MkId(info.ptr_array_type_id) << MkNum(spv::StorageClassWorkgroup);
2664
2665 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002666 new SPIRVInstruction(spv::OpVariable, info.variable_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002667 }
2668}
2669
David Neto22f144c2017-06-12 14:26:21 -04002670void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
David Netoc6f3ab22018-04-06 18:02:31 -04002671 const DataLayout &DL = F.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002672 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2673 ValueMapType &VMap = getValueMap();
2674 EntryPointVecType &EntryPoints = getEntryPointVec();
2675 ValueToValueMapTy &ArgGVMap = getArgumentGVMap();
2676 ValueMapType &ArgGVIDMap = getArgumentGVIDMap();
2677 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
2678 auto &GlobalConstArgSet = getGlobalConstArgSet();
2679
2680 FunctionType *FTy = F.getFunctionType();
2681
2682 //
2683 // Generate OpVariable and OpDecorate for kernel function with arguments.
2684 //
2685 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
2686
2687 // Find Insert Point for OpDecorate.
2688 auto DecoInsertPoint =
2689 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2690 [](SPIRVInstruction *Inst) -> bool {
2691 return Inst->getOpcode() != spv::OpDecorate &&
2692 Inst->getOpcode() != spv::OpMemberDecorate &&
2693 Inst->getOpcode() != spv::OpExtInstImport;
2694 });
2695
David Neto85082642018-03-24 06:55:20 -07002696 const uint32_t DescriptorSetIdx = NextDescriptorSetIndex;
David Neto482550a2018-03-24 05:21:07 -07002697 if (clspv::Option::DistinctKernelDescriptorSets()) {
David Neto85082642018-03-24 06:55:20 -07002698 ++NextDescriptorSetIndex;
David Neto22f144c2017-06-12 14:26:21 -04002699 }
2700
David Netoe439d702018-03-23 13:14:08 -07002701 auto remap_arg_kind = [](StringRef argKind) {
David Neto482550a2018-03-24 05:21:07 -07002702 return clspv::Option::PodArgsInUniformBuffer() && argKind.equals("pod")
2703 ? "pod_ubo"
2704 : argKind;
David Netoe439d702018-03-23 13:14:08 -07002705 };
2706
David Neto156783e2017-07-05 15:39:41 -04002707 const auto *ArgMap = F.getMetadata("kernel_arg_map");
2708 // Emit descriptor map entries, if there was explicit metadata
2709 // attached.
2710 if (ArgMap) {
David Netoc6f3ab22018-04-06 18:02:31 -04002711 // The binding number is the new argument index minus the number
2712 // pointer-to-local arguments. Do this adjustment here rather than
2713 // adding yet another data member to the metadata for each argument.
2714 int num_ptr_local = 0;
2715
David Neto156783e2017-07-05 15:39:41 -04002716 for (const auto &arg : ArgMap->operands()) {
2717 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
David Netoc6f3ab22018-04-06 18:02:31 -04002718 assert(arg_node->getNumOperands() == 6);
David Neto156783e2017-07-05 15:39:41 -04002719 const auto name =
2720 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
2721 const auto old_index =
2722 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
2723 const auto new_index =
2724 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getZExtValue();
2725 const auto offset =
2726 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
David Netoc6f3ab22018-04-06 18:02:31 -04002727 const auto argKind = remap_arg_kind(
2728 dyn_cast<MDString>(arg_node->getOperand(4))->getString());
2729 const auto spec_id =
2730 dyn_extract<ConstantInt>(arg_node->getOperand(5))->getSExtValue();
2731 if (spec_id > 0) {
2732 num_ptr_local++;
2733 FunctionType *fTy =
2734 cast<FunctionType>(F.getType()->getPointerElementType());
2735 descriptorMapOut
2736 << "kernel," << F.getName() << ",arg," << name << ",argOrdinal,"
2737 << old_index << ",argKind," << argKind << ",arrayElemSize,"
2738 << DL.getTypeAllocSize(
2739 fTy->getParamType(new_index)->getPointerElementType())
2740 << ",arrayNumElemSpecId," << spec_id << "\n";
2741 } else {
2742 descriptorMapOut << "kernel," << F.getName() << ",arg," << name
2743 << ",argOrdinal," << old_index << ",descriptorSet,"
2744 << DescriptorSetIdx << ",binding,"
2745 << (new_index - num_ptr_local) << ",offset,"
2746 << offset << ",argKind," << argKind << "\n";
2747 }
David Neto156783e2017-07-05 15:39:41 -04002748 }
2749 }
2750
David Neto22f144c2017-06-12 14:26:21 -04002751 uint32_t BindingIdx = 0;
David Netoc6f3ab22018-04-06 18:02:31 -04002752 uint32_t arg_index = 0;
David Neto22f144c2017-06-12 14:26:21 -04002753 for (auto &Arg : F.args()) {
David Netoc6f3ab22018-04-06 18:02:31 -04002754 // Always use a binding, unless it's pointer-to-local.
2755 const bool uses_binding = !IsLocalPtr(Arg.getType());
David Neto22f144c2017-06-12 14:26:21 -04002756
David Neto156783e2017-07-05 15:39:41 -04002757 // Emit a descriptor map entry for this arg, in case there was no explicit
2758 // kernel arg mapping metadata.
David Netoc6f3ab22018-04-06 18:02:31 -04002759 auto argKind = remap_arg_kind(clspv::GetArgKindForType(Arg.getType()));
David Neto156783e2017-07-05 15:39:41 -04002760 if (!ArgMap) {
David Netoc6f3ab22018-04-06 18:02:31 -04002761 if (uses_binding) {
2762 descriptorMapOut << "kernel," << F.getName() << ",arg,"
2763 << Arg.getName() << ",argOrdinal," << arg_index
2764 << ",descriptorSet," << DescriptorSetIdx
2765 << ",binding," << BindingIdx << ",offset,0,argKind,"
2766 << argKind << "\n";
2767 } else {
2768 descriptorMapOut << "kernel," << F.getName() << ",arg,"
2769 << Arg.getName() << ",argOrdinal," << arg_index
2770 << ",argKind," << argKind << ",arrayElemSize,"
2771 << DL.getTypeAllocSize(
2772 Arg.getType()->getPointerElementType())
2773 << ",arrayNumElemSpecId," << ArgSpecIdMap[&Arg]
2774 << "\n";
2775 }
David Netoc2c368d2017-06-30 16:50:17 -04002776 }
2777
David Netoc6f3ab22018-04-06 18:02:31 -04002778 if (uses_binding) {
2779 Value *NewGV = ArgGVMap[&Arg];
2780 VMap[&Arg] = VMap[NewGV];
2781 ArgGVIDMap[&Arg] = VMap[&Arg];
David Neto26aaf622017-10-23 18:11:53 -04002782
David Netoc6f3ab22018-04-06 18:02:31 -04002783 if (0 == GVarWithEmittedBindingInfo.count(NewGV)) {
2784 // Generate a new global variable for this argument.
2785 GVarWithEmittedBindingInfo.insert(NewGV);
David Neto22f144c2017-06-12 14:26:21 -04002786
David Netoc6f3ab22018-04-06 18:02:31 -04002787 SPIRVOperandList Ops;
2788 SPIRVOperand *ArgIDOp = nullptr;
David Neto257c3892018-04-11 13:19:45 -04002789 uint32_t ArgID = 0;
David Neto22f144c2017-06-12 14:26:21 -04002790
David Netoc6f3ab22018-04-06 18:02:31 -04002791 if (uses_binding) {
2792 // Ops[0] = Target ID
2793 // Ops[1] = Decoration (DescriptorSet)
2794 // Ops[2] = LiteralNumber according to Decoration
David Neto22f144c2017-06-12 14:26:21 -04002795
David Neto257c3892018-04-11 13:19:45 -04002796 ArgID = VMap[&Arg];
2797 Ops << MkId(ArgID) << MkNum(spv::DecorationDescriptorSet)
2798 << MkNum(DescriptorSetIdx);
David Neto22f144c2017-06-12 14:26:21 -04002799
David Neto87846742018-04-11 17:36:22 -04002800 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002801 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
David Neto22f144c2017-06-12 14:26:21 -04002802
David Netoc6f3ab22018-04-06 18:02:31 -04002803 // Ops[0] = Target ID
2804 // Ops[1] = Decoration (Binding)
2805 // Ops[2] = LiteralNumber according to Decoration
2806 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002807 Ops << MkId(ArgID) << MkNum(spv::DecorationBinding)
2808 << MkNum(BindingIdx);
David Netoc6f3ab22018-04-06 18:02:31 -04002809
David Neto87846742018-04-11 17:36:22 -04002810 auto *BindDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002811 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
2812 }
2813
2814 // Handle image type argument.
2815 bool HasReadOnlyImageType = false;
2816 bool HasWriteOnlyImageType = false;
2817 if (PointerType *ArgPTy = dyn_cast<PointerType>(Arg.getType())) {
2818 if (StructType *STy =
2819 dyn_cast<StructType>(ArgPTy->getElementType())) {
2820 if (STy->isOpaque()) {
2821 if (STy->getName().equals("opencl.image2d_ro_t") ||
2822 STy->getName().equals("opencl.image3d_ro_t")) {
2823 HasReadOnlyImageType = true;
2824 } else if (STy->getName().equals("opencl.image2d_wo_t") ||
2825 STy->getName().equals("opencl.image3d_wo_t")) {
2826 HasWriteOnlyImageType = true;
2827 }
2828 }
David Neto22f144c2017-06-12 14:26:21 -04002829 }
2830 }
David Netoc6f3ab22018-04-06 18:02:31 -04002831
2832 if (HasReadOnlyImageType || HasWriteOnlyImageType) {
2833 // Ops[0] = Target ID
2834 // Ops[1] = Decoration (NonReadable or NonWritable)
2835 Ops.clear();
2836
David Neto257c3892018-04-11 13:19:45 -04002837 Ops << MkId(VMap[&Arg]);
David Netoc6f3ab22018-04-06 18:02:31 -04002838
David Neto257c3892018-04-11 13:19:45 -04002839 // In OpenCL 1.2 an image is either read-only or write-only, but
2840 // never both.
2841 Ops << MkNum(HasReadOnlyImageType ? spv::DecorationNonWritable
2842 : spv::DecorationNonReadable);
David Netoc6f3ab22018-04-06 18:02:31 -04002843
David Neto87846742018-04-11 17:36:22 -04002844 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002845 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2846 }
2847
2848 // Handle const address space.
2849 if (uses_binding && NewGV->getType()->getPointerAddressSpace() ==
2850 AddressSpace::Constant) {
2851 // Ops[0] = Target ID
2852 // Ops[1] = Decoration (NonWriteable)
2853 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002854 assert(ArgID > 0);
2855 Ops << MkId(ArgID) << MkNum(spv::DecorationNonWritable);
David Netoc6f3ab22018-04-06 18:02:31 -04002856
David Neto87846742018-04-11 17:36:22 -04002857 auto *BindDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002858 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
2859 }
David Neto22f144c2017-06-12 14:26:21 -04002860 }
David Netoc6f3ab22018-04-06 18:02:31 -04002861 BindingIdx++;
David Neto22f144c2017-06-12 14:26:21 -04002862 }
David Netoc6f3ab22018-04-06 18:02:31 -04002863 arg_index++;
David Neto22f144c2017-06-12 14:26:21 -04002864 }
2865 }
2866
2867 //
2868 // Generate OPFunction.
2869 //
2870
2871 // FOps[0] : Result Type ID
2872 // FOps[1] : Function Control
2873 // FOps[2] : Function Type ID
2874 SPIRVOperandList FOps;
2875
2876 // Find SPIRV instruction for return type.
David Neto257c3892018-04-11 13:19:45 -04002877 FOps << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04002878
2879 // Check function attributes for SPIRV Function Control.
2880 uint32_t FuncControl = spv::FunctionControlMaskNone;
2881 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
2882 FuncControl |= spv::FunctionControlInlineMask;
2883 }
2884 if (F.hasFnAttribute(Attribute::NoInline)) {
2885 FuncControl |= spv::FunctionControlDontInlineMask;
2886 }
2887 // TODO: Check llvm attribute for Function Control Pure.
2888 if (F.hasFnAttribute(Attribute::ReadOnly)) {
2889 FuncControl |= spv::FunctionControlPureMask;
2890 }
2891 // TODO: Check llvm attribute for Function Control Const.
2892 if (F.hasFnAttribute(Attribute::ReadNone)) {
2893 FuncControl |= spv::FunctionControlConstMask;
2894 }
2895
David Neto257c3892018-04-11 13:19:45 -04002896 FOps << MkNum(FuncControl);
David Neto22f144c2017-06-12 14:26:21 -04002897
2898 uint32_t FTyID;
2899 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
2900 SmallVector<Type *, 4> NewFuncParamTys;
2901 FunctionType *NewFTy =
2902 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
2903 FTyID = lookupType(NewFTy);
2904 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07002905 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04002906 if (GlobalConstFuncTyMap.count(FTy)) {
2907 FTyID = lookupType(GlobalConstFuncTyMap[FTy].first);
2908 } else {
2909 FTyID = lookupType(FTy);
2910 }
2911 }
2912
David Neto257c3892018-04-11 13:19:45 -04002913 FOps << MkId(FTyID);
David Neto22f144c2017-06-12 14:26:21 -04002914
2915 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
2916 EntryPoints.push_back(std::make_pair(&F, nextID));
2917 }
2918
2919 VMap[&F] = nextID;
2920
David Neto482550a2018-03-24 05:21:07 -07002921 if (clspv::Option::ShowIDs()) {
David Netob05675d2018-02-16 12:37:49 -05002922 errs() << "Function " << F.getName() << " is " << nextID << "\n";
2923 }
David Neto22f144c2017-06-12 14:26:21 -04002924 // Generate SPIRV instruction for function.
David Neto87846742018-04-11 17:36:22 -04002925 auto *FuncInst = new SPIRVInstruction(spv::OpFunction, nextID++, FOps);
David Neto22f144c2017-06-12 14:26:21 -04002926 SPIRVInstList.push_back(FuncInst);
2927
2928 //
2929 // Generate OpFunctionParameter for Normal function.
2930 //
2931
2932 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2933 // Iterate Argument for name instead of param type from function type.
2934 unsigned ArgIdx = 0;
2935 for (Argument &Arg : F.args()) {
2936 VMap[&Arg] = nextID;
2937
2938 // ParamOps[0] : Result Type ID
2939 SPIRVOperandList ParamOps;
2940
2941 // Find SPIRV instruction for parameter type.
2942 uint32_t ParamTyID = lookupType(Arg.getType());
2943 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
2944 if (GlobalConstFuncTyMap.count(FTy)) {
2945 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
2946 Type *EleTy = PTy->getPointerElementType();
2947 Type *ArgTy =
2948 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
2949 ParamTyID = lookupType(ArgTy);
2950 GlobalConstArgSet.insert(&Arg);
2951 }
2952 }
2953 }
David Neto257c3892018-04-11 13:19:45 -04002954 ParamOps << MkId(ParamTyID);
David Neto22f144c2017-06-12 14:26:21 -04002955
2956 // Generate SPIRV instruction for parameter.
David Neto87846742018-04-11 17:36:22 -04002957 auto *ParamInst =
2958 new SPIRVInstruction(spv::OpFunctionParameter, nextID++, ParamOps);
David Neto22f144c2017-06-12 14:26:21 -04002959 SPIRVInstList.push_back(ParamInst);
2960
2961 ArgIdx++;
2962 }
2963 }
2964}
2965
David Neto5c22a252018-03-15 16:07:41 -04002966void SPIRVProducerPass::GenerateModuleInfo(Module& module) {
David Neto22f144c2017-06-12 14:26:21 -04002967 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2968 EntryPointVecType &EntryPoints = getEntryPointVec();
2969 ValueMapType &VMap = getValueMap();
2970 ValueList &EntryPointInterfaces = getEntryPointInterfacesVec();
2971 uint32_t &ExtInstImportID = getOpExtInstImportID();
2972 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
2973
2974 // Set up insert point.
2975 auto InsertPoint = SPIRVInstList.begin();
2976
2977 //
2978 // Generate OpCapability
2979 //
2980 // TODO: Which llvm information is mapped to SPIRV Capapbility?
2981
2982 // Ops[0] = Capability
2983 SPIRVOperandList Ops;
2984
David Neto87846742018-04-11 17:36:22 -04002985 auto *CapInst =
2986 new SPIRVInstruction(spv::OpCapability, {MkNum(spv::CapabilityShader)});
David Neto22f144c2017-06-12 14:26:21 -04002987 SPIRVInstList.insert(InsertPoint, CapInst);
2988
2989 for (Type *Ty : getTypeList()) {
2990 // Find the i16 type.
2991 if (Ty->isIntegerTy(16)) {
2992 // Generate OpCapability for i16 type.
David Neto87846742018-04-11 17:36:22 -04002993 SPIRVInstList.insert(InsertPoint,
2994 new SPIRVInstruction(spv::OpCapability,
2995 {MkNum(spv::CapabilityInt16)}));
David Neto22f144c2017-06-12 14:26:21 -04002996 } else if (Ty->isIntegerTy(64)) {
2997 // Generate OpCapability for i64 type.
David Neto87846742018-04-11 17:36:22 -04002998 SPIRVInstList.insert(InsertPoint,
2999 new SPIRVInstruction(spv::OpCapability,
3000 {MkNum(spv::CapabilityInt64)}));
David Neto22f144c2017-06-12 14:26:21 -04003001 } else if (Ty->isHalfTy()) {
3002 // Generate OpCapability for half type.
3003 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003004 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3005 {MkNum(spv::CapabilityFloat16)}));
David Neto22f144c2017-06-12 14:26:21 -04003006 } else if (Ty->isDoubleTy()) {
3007 // Generate OpCapability for double type.
3008 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003009 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3010 {MkNum(spv::CapabilityFloat64)}));
David Neto22f144c2017-06-12 14:26:21 -04003011 } else if (auto *STy = dyn_cast<StructType>(Ty)) {
3012 if (STy->isOpaque()) {
David Neto565571c2017-08-21 12:00:05 -04003013 if (STy->getName().equals("opencl.image2d_wo_t") ||
3014 STy->getName().equals("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04003015 // Generate OpCapability for write only image type.
3016 SPIRVInstList.insert(
3017 InsertPoint,
3018 new SPIRVInstruction(
David Neto87846742018-04-11 17:36:22 -04003019 spv::OpCapability,
3020 {MkNum(spv::CapabilityStorageImageWriteWithoutFormat)}));
David Neto22f144c2017-06-12 14:26:21 -04003021 }
3022 }
3023 }
3024 }
3025
David Neto5c22a252018-03-15 16:07:41 -04003026 { // OpCapability ImageQuery
3027 bool hasImageQuery = false;
3028 for (const char *imageQuery : {
3029 "_Z15get_image_width14ocl_image2d_ro",
3030 "_Z15get_image_width14ocl_image2d_wo",
3031 "_Z16get_image_height14ocl_image2d_ro",
3032 "_Z16get_image_height14ocl_image2d_wo",
3033 }) {
3034 if (module.getFunction(imageQuery)) {
3035 hasImageQuery = true;
3036 break;
3037 }
3038 }
3039 if (hasImageQuery) {
David Neto87846742018-04-11 17:36:22 -04003040 auto *ImageQueryCapInst = new SPIRVInstruction(
3041 spv::OpCapability, {MkNum(spv::CapabilityImageQuery)});
David Neto5c22a252018-03-15 16:07:41 -04003042 SPIRVInstList.insert(InsertPoint, ImageQueryCapInst);
3043 }
3044 }
3045
David Neto22f144c2017-06-12 14:26:21 -04003046 if (hasVariablePointers()) {
3047 //
3048 // Generate OpCapability and OpExtension
3049 //
3050
3051 //
3052 // Generate OpCapability.
3053 //
3054 // Ops[0] = Capability
3055 //
3056 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003057 Ops << MkNum(spv::CapabilityVariablePointers);
David Neto22f144c2017-06-12 14:26:21 -04003058
David Neto87846742018-04-11 17:36:22 -04003059 SPIRVInstList.insert(InsertPoint,
3060 new SPIRVInstruction(spv::OpCapability, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003061
3062 //
3063 // Generate OpExtension.
3064 //
3065 // Ops[0] = Name (Literal String)
3066 //
David Netoa772fd12017-08-04 14:17:33 -04003067 for (auto extension : {"SPV_KHR_storage_buffer_storage_class",
3068 "SPV_KHR_variable_pointers"}) {
David Neto22f144c2017-06-12 14:26:21 -04003069
David Neto87846742018-04-11 17:36:22 -04003070 auto *ExtensionInst =
3071 new SPIRVInstruction(spv::OpExtension, {MkString(extension)});
David Netoa772fd12017-08-04 14:17:33 -04003072 SPIRVInstList.insert(InsertPoint, ExtensionInst);
David Neto22f144c2017-06-12 14:26:21 -04003073 }
David Neto22f144c2017-06-12 14:26:21 -04003074 }
3075
3076 if (ExtInstImportID) {
3077 ++InsertPoint;
3078 }
3079
3080 //
3081 // Generate OpMemoryModel
3082 //
3083 // Memory model for Vulkan will always be GLSL450.
3084
3085 // Ops[0] = Addressing Model
3086 // Ops[1] = Memory Model
3087 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003088 Ops << MkNum(spv::AddressingModelLogical) << MkNum(spv::MemoryModelGLSL450);
David Neto22f144c2017-06-12 14:26:21 -04003089
David Neto87846742018-04-11 17:36:22 -04003090 auto *MemModelInst = new SPIRVInstruction(spv::OpMemoryModel, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003091 SPIRVInstList.insert(InsertPoint, MemModelInst);
3092
3093 //
3094 // Generate OpEntryPoint
3095 //
3096 for (auto EntryPoint : EntryPoints) {
3097 // Ops[0] = Execution Model
3098 // Ops[1] = EntryPoint ID
3099 // Ops[2] = Name (Literal String)
3100 // ...
3101 //
3102 // TODO: Do we need to consider Interface ID for forward references???
3103 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003104 const StringRef& name = EntryPoint.first->getName();
3105 Ops << MkNum(spv::ExecutionModelGLCompute) << MkId(EntryPoint.second)
3106 << MkString(name);
David Neto22f144c2017-06-12 14:26:21 -04003107
David Neto22f144c2017-06-12 14:26:21 -04003108 for (Value *Interface : EntryPointInterfaces) {
David Neto257c3892018-04-11 13:19:45 -04003109 Ops << MkId(VMap[Interface]);
David Neto22f144c2017-06-12 14:26:21 -04003110 }
3111
David Neto87846742018-04-11 17:36:22 -04003112 auto *EntryPointInst = new SPIRVInstruction(spv::OpEntryPoint, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003113 SPIRVInstList.insert(InsertPoint, EntryPointInst);
3114 }
3115
3116 for (auto EntryPoint : EntryPoints) {
3117 if (const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
3118 ->getMetadata("reqd_work_group_size")) {
3119
3120 if (!BuiltinDimVec.empty()) {
3121 llvm_unreachable(
3122 "Kernels should have consistent work group size definition");
3123 }
3124
3125 //
3126 // Generate OpExecutionMode
3127 //
3128
3129 // Ops[0] = Entry Point ID
3130 // Ops[1] = Execution Mode
3131 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
3132 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003133 Ops << MkId(EntryPoint.second)
3134 << MkNum(spv::ExecutionModeLocalSize);
David Neto22f144c2017-06-12 14:26:21 -04003135
3136 uint32_t XDim = static_cast<uint32_t>(
3137 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3138 uint32_t YDim = static_cast<uint32_t>(
3139 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3140 uint32_t ZDim = static_cast<uint32_t>(
3141 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3142
David Neto257c3892018-04-11 13:19:45 -04003143 Ops << MkNum(XDim) << MkNum(YDim) << MkNum(ZDim);
David Neto22f144c2017-06-12 14:26:21 -04003144
David Neto87846742018-04-11 17:36:22 -04003145 auto *ExecModeInst = new SPIRVInstruction(spv::OpExecutionMode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003146 SPIRVInstList.insert(InsertPoint, ExecModeInst);
3147 }
3148 }
3149
3150 //
3151 // Generate OpSource.
3152 //
3153 // Ops[0] = SourceLanguage ID
3154 // Ops[1] = Version (LiteralNum)
3155 //
3156 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003157 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(120);
David Neto22f144c2017-06-12 14:26:21 -04003158
David Neto87846742018-04-11 17:36:22 -04003159 auto *OpenSourceInst = new SPIRVInstruction(spv::OpSource, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003160 SPIRVInstList.insert(InsertPoint, OpenSourceInst);
3161
3162 if (!BuiltinDimVec.empty()) {
3163 //
3164 // Generate OpDecorates for x/y/z dimension.
3165 //
3166 // Ops[0] = Target ID
3167 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04003168 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04003169
3170 // X Dimension
3171 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003172 Ops << MkId(BuiltinDimVec[0]) << MkNum(spv::DecorationSpecId) << MkNum(0);
David Neto87846742018-04-11 17:36:22 -04003173 SPIRVInstList.insert(InsertPoint,
3174 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003175
3176 // Y Dimension
3177 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003178 Ops << MkId(BuiltinDimVec[1]) << MkNum(spv::DecorationSpecId) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04003179 SPIRVInstList.insert(InsertPoint,
3180 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003181
3182 // Z Dimension
3183 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003184 Ops << MkId(BuiltinDimVec[2]) << MkNum(spv::DecorationSpecId) << MkNum(2);
David Neto87846742018-04-11 17:36:22 -04003185 SPIRVInstList.insert(InsertPoint,
3186 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003187 }
3188}
3189
3190void SPIRVProducerPass::GenerateInstForArg(Function &F) {
3191 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3192 ValueMapType &VMap = getValueMap();
3193 Module *Module = F.getParent();
3194 LLVMContext &Context = Module->getContext();
3195 ValueToValueMapTy &ArgGVMap = getArgumentGVMap();
3196
3197 for (Argument &Arg : F.args()) {
3198 if (Arg.use_empty()) {
3199 continue;
3200 }
3201
David Netoc6f3ab22018-04-06 18:02:31 -04003202 Type *ArgTy = Arg.getType();
3203 if (IsLocalPtr(ArgTy)) {
3204 // Generate OpAccessChain to point to the first element of the array.
3205 const LocalArgInfo &info = LocalArgMap[&Arg];
3206 VMap[&Arg] = info.first_elem_ptr_id;
3207
3208 SPIRVOperandList Ops;
3209 uint32_t zeroId = VMap[ConstantInt::get(Type::getInt32Ty(Context), 0)];
3210 Ops << MkId(lookupType(ArgTy)) << MkId(info.variable_id) << MkId(zeroId);
3211 SPIRVInstList.push_back(new SPIRVInstruction(
David Neto87846742018-04-11 17:36:22 -04003212 spv::OpAccessChain, info.first_elem_ptr_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04003213
3214 continue;
3215 }
3216
David Neto22f144c2017-06-12 14:26:21 -04003217 // Check the type of users of arguments.
3218 bool HasOnlyGEPUse = true;
3219 for (auto *U : Arg.users()) {
3220 if (!isa<GetElementPtrInst>(U) && isa<Instruction>(U)) {
3221 HasOnlyGEPUse = false;
3222 break;
3223 }
3224 }
3225
David Neto22f144c2017-06-12 14:26:21 -04003226 if (PointerType *PTy = dyn_cast<PointerType>(ArgTy)) {
3227 if (StructType *STy = dyn_cast<StructType>(PTy->getElementType())) {
3228 if (STy->isOpaque()) {
3229 // Generate OpLoad for sampler and image types.
3230 if (STy->getName().equals("opencl.sampler_t") ||
3231 STy->getName().equals("opencl.image2d_ro_t") ||
3232 STy->getName().equals("opencl.image2d_wo_t") ||
3233 STy->getName().equals("opencl.image3d_ro_t") ||
3234 STy->getName().equals("opencl.image3d_wo_t")) {
3235 //
3236 // Generate OpLoad.
3237 //
3238 // Ops[0] = Result Type ID
3239 // Ops[1] = Pointer ID
3240 // Ops[2] ... Ops[n] = Optional Memory Access
3241 //
3242 // TODO: Do we need to implement Optional Memory Access???
3243 SPIRVOperandList Ops;
3244
3245 // Use type with address space modified.
3246 ArgTy = ArgGVMap[&Arg]->getType()->getPointerElementType();
3247
David Neto257c3892018-04-11 13:19:45 -04003248 Ops << MkId(lookupType(ArgTy));
David Neto22f144c2017-06-12 14:26:21 -04003249
3250 uint32_t PointerID = VMap[&Arg];
David Neto257c3892018-04-11 13:19:45 -04003251 Ops << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04003252
3253 VMap[&Arg] = nextID;
David Neto87846742018-04-11 17:36:22 -04003254 auto *Inst = new SPIRVInstruction(spv::OpLoad, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003255 SPIRVInstList.push_back(Inst);
3256 continue;
3257 }
3258 }
3259 }
3260
3261 if (!HasOnlyGEPUse) {
3262 //
3263 // Generate OpAccessChain.
3264 //
3265 // Ops[0] = Result Type ID
3266 // Ops[1] = Base ID
3267 // Ops[2] ... Ops[n] = Indexes ID
3268 SPIRVOperandList Ops;
3269
3270 uint32_t ResTyID = lookupType(ArgTy);
3271 if (!isa<PointerType>(ArgTy)) {
3272 ResTyID = lookupType(PointerType::get(ArgTy, AddressSpace::Global));
3273 }
David Neto257c3892018-04-11 13:19:45 -04003274 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04003275
3276 uint32_t BaseID = VMap[&Arg];
David Neto257c3892018-04-11 13:19:45 -04003277 Ops << MkId(BaseID) << MkId(GetI32Zero())
3278 << MkId(GetI32Zero());
David Neto22f144c2017-06-12 14:26:21 -04003279
3280 // Generate SPIRV instruction for argument.
3281 VMap[&Arg] = nextID;
David Neto87846742018-04-11 17:36:22 -04003282 auto *ArgInst = new SPIRVInstruction(spv::OpAccessChain, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003283 SPIRVInstList.push_back(ArgInst);
3284 } else {
3285 // For GEP uses, generate OpAccessChain with folding GEP ahead of GEP.
3286 // Nothing to do here.
3287 }
3288 } else {
3289 //
3290 // Generate OpAccessChain and OpLoad for non-pointer type argument.
3291 //
3292
3293 //
3294 // Generate OpAccessChain.
3295 //
3296 // Ops[0] = Result Type ID
3297 // Ops[1] = Base ID
3298 // Ops[2] ... Ops[n] = Indexes ID
3299 SPIRVOperandList Ops;
3300
3301 uint32_t ResTyID = lookupType(ArgTy);
3302 if (!isa<PointerType>(ArgTy)) {
David Neto482550a2018-03-24 05:21:07 -07003303 auto AS = clspv::Option::PodArgsInUniformBuffer()
3304 ? AddressSpace::Uniform
3305 : AddressSpace::Global;
David Netoe439d702018-03-23 13:14:08 -07003306 ResTyID = lookupType(PointerType::get(ArgTy, AS));
David Neto22f144c2017-06-12 14:26:21 -04003307 }
David Neto257c3892018-04-11 13:19:45 -04003308 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04003309
3310 uint32_t BaseID = VMap[&Arg];
David Neto257c3892018-04-11 13:19:45 -04003311 Ops << MkId(BaseID) << MkId(GetI32Zero());
David Neto22f144c2017-06-12 14:26:21 -04003312
3313 // Generate SPIRV instruction for argument.
3314 uint32_t PointerID = nextID;
3315 VMap[&Arg] = nextID;
David Neto87846742018-04-11 17:36:22 -04003316 auto *ArgInst = new SPIRVInstruction(spv::OpAccessChain, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003317 SPIRVInstList.push_back(ArgInst);
3318
3319 //
3320 // Generate OpLoad.
3321 //
3322
3323 // Ops[0] = Result Type ID
3324 // Ops[1] = Pointer ID
3325 // Ops[2] ... Ops[n] = Optional Memory Access
3326 //
3327 // TODO: Do we need to implement Optional Memory Access???
3328 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003329 Ops << MkId(lookupType(ArgTy)) << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04003330
3331 VMap[&Arg] = nextID;
David Neto87846742018-04-11 17:36:22 -04003332 auto *Inst = new SPIRVInstruction(spv::OpLoad, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003333 SPIRVInstList.push_back(Inst);
3334 }
3335 }
3336}
3337
David Netob6e2e062018-04-25 10:32:06 -04003338void SPIRVProducerPass::GenerateEntryPointInitialStores() {
3339 // Work around a driver bug. Initializers on Private variables might not
3340 // work. So the start of the kernel should store the initializer value to the
3341 // variables. Yes, *every* entry point pays this cost if *any* entry point
3342 // uses this builtin. At this point I judge this to be an acceptable tradeoff
3343 // of complexity vs. runtime, for a broken driver.
3344 // TODO(dneto): Remove this at some point once fixed drivers are widely available.
3345 if (WorkgroupSizeVarID) {
3346 assert(WorkgroupSizeValueID);
3347
3348 SPIRVOperandList Ops;
3349 Ops << MkId(WorkgroupSizeVarID) << MkId(WorkgroupSizeValueID);
3350
3351 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
3352 getSPIRVInstList().push_back(Inst);
3353 }
3354}
3355
David Neto22f144c2017-06-12 14:26:21 -04003356void SPIRVProducerPass::GenerateFuncBody(Function &F) {
3357 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3358 ValueMapType &VMap = getValueMap();
3359
David Netob6e2e062018-04-25 10:32:06 -04003360 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04003361
3362 for (BasicBlock &BB : F) {
3363 // Register BasicBlock to ValueMap.
3364 VMap[&BB] = nextID;
3365
3366 //
3367 // Generate OpLabel for Basic Block.
3368 //
3369 SPIRVOperandList Ops;
David Neto87846742018-04-11 17:36:22 -04003370 auto *Inst = new SPIRVInstruction(spv::OpLabel, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003371 SPIRVInstList.push_back(Inst);
3372
David Neto6dcd4712017-06-23 11:06:47 -04003373 // OpVariable instructions must come first.
3374 for (Instruction &I : BB) {
3375 if (isa<AllocaInst>(I)) {
3376 GenerateInstruction(I);
3377 }
3378 }
3379
David Neto22f144c2017-06-12 14:26:21 -04003380 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04003381 if (clspv::Option::HackInitializers()) {
3382 GenerateEntryPointInitialStores();
3383 }
David Neto22f144c2017-06-12 14:26:21 -04003384 GenerateInstForArg(F);
3385 }
3386
3387 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003388 if (!isa<AllocaInst>(I)) {
3389 GenerateInstruction(I);
3390 }
David Neto22f144c2017-06-12 14:26:21 -04003391 }
3392 }
3393}
3394
3395spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3396 const std::map<CmpInst::Predicate, spv::Op> Map = {
3397 {CmpInst::ICMP_EQ, spv::OpIEqual},
3398 {CmpInst::ICMP_NE, spv::OpINotEqual},
3399 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3400 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3401 {CmpInst::ICMP_ULT, spv::OpULessThan},
3402 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3403 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3404 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3405 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3406 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3407 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3408 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3409 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3410 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3411 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3412 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3413 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3414 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3415 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3416 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3417 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3418 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3419
3420 assert(0 != Map.count(I->getPredicate()));
3421
3422 return Map.at(I->getPredicate());
3423}
3424
3425spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3426 const std::map<unsigned, spv::Op> Map{
3427 {Instruction::Trunc, spv::OpUConvert},
3428 {Instruction::ZExt, spv::OpUConvert},
3429 {Instruction::SExt, spv::OpSConvert},
3430 {Instruction::FPToUI, spv::OpConvertFToU},
3431 {Instruction::FPToSI, spv::OpConvertFToS},
3432 {Instruction::UIToFP, spv::OpConvertUToF},
3433 {Instruction::SIToFP, spv::OpConvertSToF},
3434 {Instruction::FPTrunc, spv::OpFConvert},
3435 {Instruction::FPExt, spv::OpFConvert},
3436 {Instruction::BitCast, spv::OpBitcast}};
3437
3438 assert(0 != Map.count(I.getOpcode()));
3439
3440 return Map.at(I.getOpcode());
3441}
3442
3443spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
3444 if (I.getType()->isIntegerTy(1)) {
3445 switch (I.getOpcode()) {
3446 default:
3447 break;
3448 case Instruction::Or:
3449 return spv::OpLogicalOr;
3450 case Instruction::And:
3451 return spv::OpLogicalAnd;
3452 case Instruction::Xor:
3453 return spv::OpLogicalNotEqual;
3454 }
3455 }
3456
3457 const std::map<unsigned, spv::Op> Map {
3458 {Instruction::Add, spv::OpIAdd},
3459 {Instruction::FAdd, spv::OpFAdd},
3460 {Instruction::Sub, spv::OpISub},
3461 {Instruction::FSub, spv::OpFSub},
3462 {Instruction::Mul, spv::OpIMul},
3463 {Instruction::FMul, spv::OpFMul},
3464 {Instruction::UDiv, spv::OpUDiv},
3465 {Instruction::SDiv, spv::OpSDiv},
3466 {Instruction::FDiv, spv::OpFDiv},
3467 {Instruction::URem, spv::OpUMod},
3468 {Instruction::SRem, spv::OpSRem},
3469 {Instruction::FRem, spv::OpFRem},
3470 {Instruction::Or, spv::OpBitwiseOr},
3471 {Instruction::Xor, spv::OpBitwiseXor},
3472 {Instruction::And, spv::OpBitwiseAnd},
3473 {Instruction::Shl, spv::OpShiftLeftLogical},
3474 {Instruction::LShr, spv::OpShiftRightLogical},
3475 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3476
3477 assert(0 != Map.count(I.getOpcode()));
3478
3479 return Map.at(I.getOpcode());
3480}
3481
3482void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
3483 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3484 ValueMapType &VMap = getValueMap();
3485 ValueToValueMapTy &ArgGVMap = getArgumentGVMap();
3486 ValueMapType &ArgGVIDMap = getArgumentGVIDMap();
3487 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
3488 LLVMContext &Context = I.getParent()->getParent()->getParent()->getContext();
3489
3490 // Register Instruction to ValueMap.
3491 if (0 == VMap[&I]) {
3492 VMap[&I] = nextID;
3493 }
3494
3495 switch (I.getOpcode()) {
3496 default: {
3497 if (Instruction::isCast(I.getOpcode())) {
3498 //
3499 // Generate SPIRV instructions for cast operators.
3500 //
3501
David Netod2de94a2017-08-28 17:27:47 -04003502
3503 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003504 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003505 auto toI8 = Ty == Type::getInt8Ty(Context);
3506 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003507 // Handle zext, sext and uitofp with i1 type specially.
3508 if ((I.getOpcode() == Instruction::ZExt ||
3509 I.getOpcode() == Instruction::SExt ||
3510 I.getOpcode() == Instruction::UIToFP) &&
3511 (OpTy->isIntegerTy(1) ||
3512 (OpTy->isVectorTy() &&
3513 OpTy->getVectorElementType()->isIntegerTy(1)))) {
3514 //
3515 // Generate OpSelect.
3516 //
3517
3518 // Ops[0] = Result Type ID
3519 // Ops[1] = Condition ID
3520 // Ops[2] = True Constant ID
3521 // Ops[3] = False Constant ID
3522 SPIRVOperandList Ops;
3523
David Neto257c3892018-04-11 13:19:45 -04003524 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003525
David Neto22f144c2017-06-12 14:26:21 -04003526 uint32_t CondID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003527 Ops << MkId(CondID);
David Neto22f144c2017-06-12 14:26:21 -04003528
3529 uint32_t TrueID = 0;
3530 if (I.getOpcode() == Instruction::ZExt) {
3531 APInt One(32, 1);
3532 TrueID = VMap[Constant::getIntegerValue(I.getType(), One)];
3533 } else if (I.getOpcode() == Instruction::SExt) {
3534 APInt MinusOne(32, UINT64_MAX, true);
3535 TrueID = VMap[Constant::getIntegerValue(I.getType(), MinusOne)];
3536 } else {
3537 TrueID = VMap[ConstantFP::get(Context, APFloat(1.0f))];
3538 }
David Neto257c3892018-04-11 13:19:45 -04003539 Ops << MkId(TrueID);
David Neto22f144c2017-06-12 14:26:21 -04003540
3541 uint32_t FalseID = 0;
3542 if (I.getOpcode() == Instruction::ZExt) {
3543 FalseID = VMap[Constant::getNullValue(I.getType())];
3544 } else if (I.getOpcode() == Instruction::SExt) {
3545 FalseID = VMap[Constant::getNullValue(I.getType())];
3546 } else {
3547 FalseID = VMap[ConstantFP::get(Context, APFloat(0.0f))];
3548 }
David Neto257c3892018-04-11 13:19:45 -04003549 Ops << MkId(FalseID);
David Neto22f144c2017-06-12 14:26:21 -04003550
David Neto87846742018-04-11 17:36:22 -04003551 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003552 SPIRVInstList.push_back(Inst);
David Netod2de94a2017-08-28 17:27:47 -04003553 } else if (I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
3554 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3555 // 8 bits.
3556 // Before:
3557 // %result = trunc i32 %a to i8
3558 // After
3559 // %result = OpBitwiseAnd %uint %a %uint_255
3560
3561 SPIRVOperandList Ops;
3562
David Neto257c3892018-04-11 13:19:45 -04003563 Ops << MkId(lookupType(OpTy)) << MkId(VMap[I.getOperand(0)]);
David Netod2de94a2017-08-28 17:27:47 -04003564
3565 Type *UintTy = Type::getInt32Ty(Context);
3566 uint32_t MaskID = VMap[ConstantInt::get(UintTy, 255)];
David Neto257c3892018-04-11 13:19:45 -04003567 Ops << MkId(MaskID);
David Netod2de94a2017-08-28 17:27:47 -04003568
David Neto87846742018-04-11 17:36:22 -04003569 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Netod2de94a2017-08-28 17:27:47 -04003570 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003571 } else {
3572 // Ops[0] = Result Type ID
3573 // Ops[1] = Source Value ID
3574 SPIRVOperandList Ops;
3575
David Neto257c3892018-04-11 13:19:45 -04003576 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003577
David Neto87846742018-04-11 17:36:22 -04003578 auto *Inst = new SPIRVInstruction(GetSPIRVCastOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003579 SPIRVInstList.push_back(Inst);
3580 }
3581 } else if (isa<BinaryOperator>(I)) {
3582 //
3583 // Generate SPIRV instructions for binary operators.
3584 //
3585
3586 // Handle xor with i1 type specially.
3587 if (I.getOpcode() == Instruction::Xor &&
3588 I.getType() == Type::getInt1Ty(Context) &&
3589 (isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
3590 //
3591 // Generate OpLogicalNot.
3592 //
3593 // Ops[0] = Result Type ID
3594 // Ops[1] = Operand
3595 SPIRVOperandList Ops;
3596
David Neto257c3892018-04-11 13:19:45 -04003597 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003598
3599 Value *CondV = I.getOperand(0);
3600 if (isa<Constant>(I.getOperand(0))) {
3601 CondV = I.getOperand(1);
3602 }
David Neto257c3892018-04-11 13:19:45 -04003603 Ops << MkId(VMap[CondV]);
David Neto22f144c2017-06-12 14:26:21 -04003604
David Neto87846742018-04-11 17:36:22 -04003605 auto *Inst = new SPIRVInstruction(spv::OpLogicalNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003606 SPIRVInstList.push_back(Inst);
3607 } else {
3608 // Ops[0] = Result Type ID
3609 // Ops[1] = Operand 0
3610 // Ops[2] = Operand 1
3611 SPIRVOperandList Ops;
3612
David Neto257c3892018-04-11 13:19:45 -04003613 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
3614 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003615
David Neto87846742018-04-11 17:36:22 -04003616 auto *Inst =
3617 new SPIRVInstruction(GetSPIRVBinaryOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003618 SPIRVInstList.push_back(Inst);
3619 }
3620 } else {
3621 I.print(errs());
3622 llvm_unreachable("Unsupported instruction???");
3623 }
3624 break;
3625 }
3626 case Instruction::GetElementPtr: {
3627 auto &GlobalConstArgSet = getGlobalConstArgSet();
3628
3629 //
3630 // Generate OpAccessChain.
3631 //
3632 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
3633
3634 //
3635 // Generate OpAccessChain.
3636 //
3637
3638 // Ops[0] = Result Type ID
3639 // Ops[1] = Base ID
3640 // Ops[2] ... Ops[n] = Indexes ID
3641 SPIRVOperandList Ops;
3642
David Neto1a1a0582017-07-07 12:01:44 -04003643 PointerType* ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04003644 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
3645 GlobalConstArgSet.count(GEP->getPointerOperand())) {
3646 // Use pointer type with private address space for global constant.
3647 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04003648 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04003649 }
David Neto257c3892018-04-11 13:19:45 -04003650
3651 Ops << MkId(lookupType(ResultType));
David Neto22f144c2017-06-12 14:26:21 -04003652
3653 // Check whether GEP's pointer operand is pointer argument.
3654 bool HasArgBasePointer = false;
3655 for (auto ArgGV : ArgGVMap) {
3656 if (ArgGV.first == GEP->getPointerOperand()) {
3657 if (isa<PointerType>(ArgGV.first->getType())) {
3658 HasArgBasePointer = true;
3659 } else {
3660 llvm_unreachable(
3661 "GEP's pointer operand is argument of non-poninter type???");
3662 }
3663 }
3664 }
3665
3666 uint32_t BaseID;
3667 if (HasArgBasePointer) {
3668 // Point to global variable for argument directly.
3669 BaseID = ArgGVIDMap[GEP->getPointerOperand()];
3670 } else {
3671 BaseID = VMap[GEP->getPointerOperand()];
3672 }
3673
David Neto257c3892018-04-11 13:19:45 -04003674 Ops << MkId(BaseID);
David Neto22f144c2017-06-12 14:26:21 -04003675
David Neto22f144c2017-06-12 14:26:21 -04003676 if (HasArgBasePointer) {
3677 // If GEP's pointer operand is argument, add one more index for struct
3678 // type to wrap up argument type.
3679 Type *IdxTy = Type::getInt32Ty(Context);
David Neto257c3892018-04-11 13:19:45 -04003680 Ops << MkId(VMap[ConstantInt::get(IdxTy, 0)]);
David Neto22f144c2017-06-12 14:26:21 -04003681 }
3682
3683 //
3684 // Follows below rules for gep.
3685 //
3686 // 1. If gep's first index is 0 and gep's base is not kernel function's
3687 // argument, generate OpAccessChain and ignore gep's first index.
3688 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
3689 // first index.
3690 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
3691 // use gep's first index.
3692 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
3693 // gep's first index.
3694 //
3695 spv::Op Opcode = spv::OpAccessChain;
3696 unsigned offset = 0;
3697 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
3698 if (CstInt->getZExtValue() == 0 && !HasArgBasePointer) {
3699 offset = 1;
3700 } else if (CstInt->getZExtValue() != 0 && !HasArgBasePointer) {
3701 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04003702 }
3703 } else if (!HasArgBasePointer) {
3704 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04003705 }
3706
3707 if (Opcode == spv::OpPtrAccessChain) {
David Neto22f144c2017-06-12 14:26:21 -04003708 setVariablePointers(true);
David Neto1a1a0582017-07-07 12:01:44 -04003709 // Do we need to generate ArrayStride? Check against the GEP result type
3710 // rather than the pointer type of the base because when indexing into
3711 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
3712 // for something else in the SPIR-V.
3713 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
3714 if (GetStorageClass(ResultType->getAddressSpace()) ==
3715 spv::StorageClassStorageBuffer) {
3716 // Save the need to generate an ArrayStride decoration. But defer
3717 // generation until later, so we only make one decoration.
David Neto85082642018-03-24 06:55:20 -07003718 getTypesNeedingArrayStride().insert(ResultType);
David Neto1a1a0582017-07-07 12:01:44 -04003719 }
David Neto22f144c2017-06-12 14:26:21 -04003720 }
3721
3722 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
David Neto257c3892018-04-11 13:19:45 -04003723 Ops << MkId(VMap[*II]);
David Neto22f144c2017-06-12 14:26:21 -04003724 }
3725
David Neto87846742018-04-11 17:36:22 -04003726 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003727 SPIRVInstList.push_back(Inst);
3728 break;
3729 }
3730 case Instruction::ExtractValue: {
3731 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3732 // Ops[0] = Result Type ID
3733 // Ops[1] = Composite ID
3734 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3735 SPIRVOperandList Ops;
3736
David Neto257c3892018-04-11 13:19:45 -04003737 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003738
3739 uint32_t CompositeID = VMap[EVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003740 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003741
3742 for (auto &Index : EVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003743 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003744 }
3745
David Neto87846742018-04-11 17:36:22 -04003746 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003747 SPIRVInstList.push_back(Inst);
3748 break;
3749 }
3750 case Instruction::InsertValue: {
3751 InsertValueInst *IVI = cast<InsertValueInst>(&I);
3752 // Ops[0] = Result Type ID
3753 // Ops[1] = Object ID
3754 // Ops[2] = Composite ID
3755 // Ops[3] ... Ops[n] = Indexes (Literal Number)
3756 SPIRVOperandList Ops;
3757
3758 uint32_t ResTyID = lookupType(I.getType());
David Neto257c3892018-04-11 13:19:45 -04003759 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04003760
3761 uint32_t ObjectID = VMap[IVI->getInsertedValueOperand()];
David Neto257c3892018-04-11 13:19:45 -04003762 Ops << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04003763
3764 uint32_t CompositeID = VMap[IVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003765 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003766
3767 for (auto &Index : IVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003768 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003769 }
3770
David Neto87846742018-04-11 17:36:22 -04003771 auto *Inst = new SPIRVInstruction(spv::OpCompositeInsert, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003772 SPIRVInstList.push_back(Inst);
3773 break;
3774 }
3775 case Instruction::Select: {
3776 //
3777 // Generate OpSelect.
3778 //
3779
3780 // Ops[0] = Result Type ID
3781 // Ops[1] = Condition ID
3782 // Ops[2] = True Constant ID
3783 // Ops[3] = False Constant ID
3784 SPIRVOperandList Ops;
3785
3786 // Find SPIRV instruction for parameter type.
3787 auto Ty = I.getType();
3788 if (Ty->isPointerTy()) {
3789 auto PointeeTy = Ty->getPointerElementType();
3790 if (PointeeTy->isStructTy() &&
3791 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
3792 Ty = PointeeTy;
3793 }
3794 }
3795
David Neto257c3892018-04-11 13:19:45 -04003796 Ops << MkId(lookupType(Ty)) << MkId(VMap[I.getOperand(0)])
3797 << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003798
David Neto87846742018-04-11 17:36:22 -04003799 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003800 SPIRVInstList.push_back(Inst);
3801 break;
3802 }
3803 case Instruction::ExtractElement: {
3804 // Handle <4 x i8> type manually.
3805 Type *CompositeTy = I.getOperand(0)->getType();
3806 if (is4xi8vec(CompositeTy)) {
3807 //
3808 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
3809 // <4 x i8>.
3810 //
3811
3812 //
3813 // Generate OpShiftRightLogical
3814 //
3815 // Ops[0] = Result Type ID
3816 // Ops[1] = Operand 0
3817 // Ops[2] = Operand 1
3818 //
3819 SPIRVOperandList Ops;
3820
David Neto257c3892018-04-11 13:19:45 -04003821 Ops << MkId(lookupType(CompositeTy));
David Neto22f144c2017-06-12 14:26:21 -04003822
3823 uint32_t Op0ID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003824 Ops << MkId(Op0ID);
David Neto22f144c2017-06-12 14:26:21 -04003825
3826 uint32_t Op1ID = 0;
3827 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
3828 // Handle constant index.
3829 uint64_t Idx = CI->getZExtValue();
3830 Value *ShiftAmount =
3831 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3832 Op1ID = VMap[ShiftAmount];
3833 } else {
3834 // Handle variable index.
3835 SPIRVOperandList TmpOps;
3836
David Neto257c3892018-04-11 13:19:45 -04003837 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3838 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003839
3840 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003841 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003842
3843 Op1ID = nextID;
3844
David Neto87846742018-04-11 17:36:22 -04003845 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003846 SPIRVInstList.push_back(TmpInst);
3847 }
David Neto257c3892018-04-11 13:19:45 -04003848 Ops << MkId(Op1ID);
David Neto22f144c2017-06-12 14:26:21 -04003849
3850 uint32_t ShiftID = nextID;
3851
David Neto87846742018-04-11 17:36:22 -04003852 auto *Inst =
3853 new SPIRVInstruction(spv::OpShiftRightLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003854 SPIRVInstList.push_back(Inst);
3855
3856 //
3857 // Generate OpBitwiseAnd
3858 //
3859 // Ops[0] = Result Type ID
3860 // Ops[1] = Operand 0
3861 // Ops[2] = Operand 1
3862 //
3863 Ops.clear();
3864
David Neto257c3892018-04-11 13:19:45 -04003865 Ops << MkId(lookupType(CompositeTy)) << MkId(ShiftID);
David Neto22f144c2017-06-12 14:26:21 -04003866
3867 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
David Neto257c3892018-04-11 13:19:45 -04003868 Ops << MkId(VMap[CstFF]);
David Neto22f144c2017-06-12 14:26:21 -04003869
David Neto9b2d6252017-09-06 15:47:37 -04003870 // Reset mapping for this value to the result of the bitwise and.
3871 VMap[&I] = nextID;
3872
David Neto87846742018-04-11 17:36:22 -04003873 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003874 SPIRVInstList.push_back(Inst);
3875 break;
3876 }
3877
3878 // Ops[0] = Result Type ID
3879 // Ops[1] = Composite ID
3880 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3881 SPIRVOperandList Ops;
3882
David Neto257c3892018-04-11 13:19:45 -04003883 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003884
3885 spv::Op Opcode = spv::OpCompositeExtract;
3886 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
David Neto257c3892018-04-11 13:19:45 -04003887 Ops << MkNum(static_cast<uint32_t>(CI->getZExtValue()));
David Neto22f144c2017-06-12 14:26:21 -04003888 } else {
David Neto257c3892018-04-11 13:19:45 -04003889 Ops << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003890 Opcode = spv::OpVectorExtractDynamic;
3891 }
3892
David Neto87846742018-04-11 17:36:22 -04003893 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003894 SPIRVInstList.push_back(Inst);
3895 break;
3896 }
3897 case Instruction::InsertElement: {
3898 // Handle <4 x i8> type manually.
3899 Type *CompositeTy = I.getOperand(0)->getType();
3900 if (is4xi8vec(CompositeTy)) {
3901 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
3902 uint32_t CstFFID = VMap[CstFF];
3903
3904 uint32_t ShiftAmountID = 0;
3905 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
3906 // Handle constant index.
3907 uint64_t Idx = CI->getZExtValue();
3908 Value *ShiftAmount =
3909 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3910 ShiftAmountID = VMap[ShiftAmount];
3911 } else {
3912 // Handle variable index.
3913 SPIRVOperandList TmpOps;
3914
David Neto257c3892018-04-11 13:19:45 -04003915 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3916 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003917
3918 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003919 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003920
3921 ShiftAmountID = nextID;
3922
David Neto87846742018-04-11 17:36:22 -04003923 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003924 SPIRVInstList.push_back(TmpInst);
3925 }
3926
3927 //
3928 // Generate mask operations.
3929 //
3930
3931 // ShiftLeft mask according to index of insertelement.
3932 SPIRVOperandList Ops;
3933
David Neto257c3892018-04-11 13:19:45 -04003934 const uint32_t ResTyID = lookupType(CompositeTy);
3935 Ops << MkId(ResTyID) << MkId(CstFFID) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04003936
3937 uint32_t MaskID = nextID;
3938
David Neto87846742018-04-11 17:36:22 -04003939 auto *Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003940 SPIRVInstList.push_back(Inst);
3941
3942 // Inverse mask.
3943 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003944 Ops << MkId(ResTyID) << MkId(MaskID);
David Neto22f144c2017-06-12 14:26:21 -04003945
3946 uint32_t InvMaskID = nextID;
3947
David Neto87846742018-04-11 17:36:22 -04003948 Inst = new SPIRVInstruction(spv::OpNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003949 SPIRVInstList.push_back(Inst);
3950
3951 // Apply mask.
3952 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003953 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(0)]) << MkId(InvMaskID);
David Neto22f144c2017-06-12 14:26:21 -04003954
3955 uint32_t OrgValID = nextID;
3956
David Neto87846742018-04-11 17:36:22 -04003957 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003958 SPIRVInstList.push_back(Inst);
3959
3960 // Create correct value according to index of insertelement.
3961 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003962 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(1)]) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04003963
3964 uint32_t InsertValID = nextID;
3965
David Neto87846742018-04-11 17:36:22 -04003966 Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003967 SPIRVInstList.push_back(Inst);
3968
3969 // Insert value to original value.
3970 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003971 Ops << MkId(ResTyID) << MkId(OrgValID) << MkId(InsertValID);
David Neto22f144c2017-06-12 14:26:21 -04003972
David Netoa394f392017-08-26 20:45:29 -04003973 VMap[&I] = nextID;
3974
David Neto87846742018-04-11 17:36:22 -04003975 Inst = new SPIRVInstruction(spv::OpBitwiseOr, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003976 SPIRVInstList.push_back(Inst);
3977
3978 break;
3979 }
3980
David Neto22f144c2017-06-12 14:26:21 -04003981 SPIRVOperandList Ops;
3982
James Priced26efea2018-06-09 23:28:32 +01003983 // Ops[0] = Result Type ID
3984 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003985
3986 spv::Op Opcode = spv::OpCompositeInsert;
3987 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04003988 const auto value = CI->getZExtValue();
3989 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01003990 // Ops[1] = Object ID
3991 // Ops[2] = Composite ID
3992 // Ops[3] ... Ops[n] = Indexes (Literal Number)
3993 Ops << MkId(VMap[I.getOperand(1)])
3994 << MkId(VMap[I.getOperand(0)])
3995 << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04003996 } else {
James Priced26efea2018-06-09 23:28:32 +01003997 // Ops[1] = Composite ID
3998 // Ops[2] = Object ID
3999 // Ops[3] ... Ops[n] = Indexes (Literal Number)
4000 Ops << MkId(VMap[I.getOperand(0)])
4001 << MkId(VMap[I.getOperand(1)])
4002 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004003 Opcode = spv::OpVectorInsertDynamic;
4004 }
4005
David Neto87846742018-04-11 17:36:22 -04004006 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004007 SPIRVInstList.push_back(Inst);
4008 break;
4009 }
4010 case Instruction::ShuffleVector: {
4011 // Ops[0] = Result Type ID
4012 // Ops[1] = Vector 1 ID
4013 // Ops[2] = Vector 2 ID
4014 // Ops[3] ... Ops[n] = Components (Literal Number)
4015 SPIRVOperandList Ops;
4016
David Neto257c3892018-04-11 13:19:45 -04004017 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4018 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004019
4020 uint64_t NumElements = 0;
4021 if (Constant *Cst = dyn_cast<Constant>(I.getOperand(2))) {
4022 NumElements = cast<VectorType>(Cst->getType())->getNumElements();
4023
4024 if (Cst->isNullValue()) {
4025 for (unsigned i = 0; i < NumElements; i++) {
David Neto257c3892018-04-11 13:19:45 -04004026 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04004027 }
4028 } else if (const ConstantDataSequential *CDS =
4029 dyn_cast<ConstantDataSequential>(Cst)) {
4030 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
4031 std::vector<uint32_t> LiteralNum;
David Neto257c3892018-04-11 13:19:45 -04004032 const auto value = CDS->getElementAsInteger(i);
4033 assert(value <= UINT32_MAX);
4034 Ops << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004035 }
4036 } else if (const ConstantVector *CV = dyn_cast<ConstantVector>(Cst)) {
4037 for (unsigned i = 0; i < CV->getNumOperands(); i++) {
4038 auto Op = CV->getOperand(i);
4039
4040 uint32_t literal = 0;
4041
4042 if (auto CI = dyn_cast<ConstantInt>(Op)) {
4043 literal = static_cast<uint32_t>(CI->getZExtValue());
4044 } else if (auto UI = dyn_cast<UndefValue>(Op)) {
4045 literal = 0xFFFFFFFFu;
4046 } else {
4047 Op->print(errs());
4048 llvm_unreachable("Unsupported element in ConstantVector!");
4049 }
4050
David Neto257c3892018-04-11 13:19:45 -04004051 Ops << MkNum(literal);
David Neto22f144c2017-06-12 14:26:21 -04004052 }
4053 } else {
4054 Cst->print(errs());
4055 llvm_unreachable("Unsupported constant mask in ShuffleVector!");
4056 }
4057 }
4058
David Neto87846742018-04-11 17:36:22 -04004059 auto *Inst = new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004060 SPIRVInstList.push_back(Inst);
4061 break;
4062 }
4063 case Instruction::ICmp:
4064 case Instruction::FCmp: {
4065 CmpInst *CmpI = cast<CmpInst>(&I);
4066
David Netod4ca2e62017-07-06 18:47:35 -04004067 // Pointer equality is invalid.
4068 Type* ArgTy = CmpI->getOperand(0)->getType();
4069 if (isa<PointerType>(ArgTy)) {
4070 CmpI->print(errs());
4071 std::string name = I.getParent()->getParent()->getName();
4072 errs()
4073 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4074 << "in function " << name << "\n";
4075 llvm_unreachable("Pointer equality check is invalid");
4076 break;
4077 }
4078
David Neto257c3892018-04-11 13:19:45 -04004079 // Ops[0] = Result Type ID
4080 // Ops[1] = Operand 1 ID
4081 // Ops[2] = Operand 2 ID
4082 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004083
David Neto257c3892018-04-11 13:19:45 -04004084 Ops << MkId(lookupType(CmpI->getType())) << MkId(VMap[CmpI->getOperand(0)])
4085 << MkId(VMap[CmpI->getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004086
4087 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
David Neto87846742018-04-11 17:36:22 -04004088 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004089 SPIRVInstList.push_back(Inst);
4090 break;
4091 }
4092 case Instruction::Br: {
4093 // Branch instrucion is deferred because it needs label's ID. Record slot's
4094 // location on SPIRVInstructionList.
4095 DeferredInsts.push_back(
4096 std::make_tuple(&I, --SPIRVInstList.end(), 0 /* No id */));
4097 break;
4098 }
4099 case Instruction::Switch: {
4100 I.print(errs());
4101 llvm_unreachable("Unsupported instruction???");
4102 break;
4103 }
4104 case Instruction::IndirectBr: {
4105 I.print(errs());
4106 llvm_unreachable("Unsupported instruction???");
4107 break;
4108 }
4109 case Instruction::PHI: {
4110 // Branch instrucion is deferred because it needs label's ID. Record slot's
4111 // location on SPIRVInstructionList.
4112 DeferredInsts.push_back(
4113 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4114 break;
4115 }
4116 case Instruction::Alloca: {
4117 //
4118 // Generate OpVariable.
4119 //
4120 // Ops[0] : Result Type ID
4121 // Ops[1] : Storage Class
4122 SPIRVOperandList Ops;
4123
David Neto257c3892018-04-11 13:19:45 -04004124 Ops << MkId(lookupType(I.getType())) << MkNum(spv::StorageClassFunction);
David Neto22f144c2017-06-12 14:26:21 -04004125
David Neto87846742018-04-11 17:36:22 -04004126 auto *Inst = new SPIRVInstruction(spv::OpVariable, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004127 SPIRVInstList.push_back(Inst);
4128 break;
4129 }
4130 case Instruction::Load: {
4131 LoadInst *LD = cast<LoadInst>(&I);
4132 //
4133 // Generate OpLoad.
4134 //
4135
David Neto0a2f98d2017-09-15 19:38:40 -04004136 uint32_t ResTyID = lookupType(LD->getType());
David Netoa60b00b2017-09-15 16:34:09 -04004137 uint32_t PointerID = VMap[LD->getPointerOperand()];
4138
4139 // This is a hack to work around what looks like a driver bug.
4140 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004141 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4142 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004143 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004144 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004145 // Generate a bitwise-and of the original value with itself.
4146 // We should have been able to get away with just an OpCopyObject,
4147 // but we need something more complex to get past certain driver bugs.
4148 // This is ridiculous, but necessary.
4149 // TODO(dneto): Revisit this once drivers fix their bugs.
4150
4151 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004152 Ops << MkId(ResTyID) << MkId(WorkgroupSizeValueID)
4153 << MkId(WorkgroupSizeValueID);
David Neto0a2f98d2017-09-15 19:38:40 -04004154
David Neto87846742018-04-11 17:36:22 -04004155 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto0a2f98d2017-09-15 19:38:40 -04004156 SPIRVInstList.push_back(Inst);
David Netoa60b00b2017-09-15 16:34:09 -04004157 break;
4158 }
4159
4160 // This is the normal path. Generate a load.
4161
David Neto22f144c2017-06-12 14:26:21 -04004162 // Ops[0] = Result Type ID
4163 // Ops[1] = Pointer ID
4164 // Ops[2] ... Ops[n] = Optional Memory Access
4165 //
4166 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004167
David Neto22f144c2017-06-12 14:26:21 -04004168 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004169 Ops << MkId(ResTyID) << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04004170
David Neto87846742018-04-11 17:36:22 -04004171 auto *Inst = new SPIRVInstruction(spv::OpLoad, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004172 SPIRVInstList.push_back(Inst);
4173 break;
4174 }
4175 case Instruction::Store: {
4176 StoreInst *ST = cast<StoreInst>(&I);
4177 //
4178 // Generate OpStore.
4179 //
4180
4181 // Ops[0] = Pointer ID
4182 // Ops[1] = Object ID
4183 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4184 //
4185 // TODO: Do we need to implement Optional Memory Access???
David Neto257c3892018-04-11 13:19:45 -04004186 SPIRVOperandList Ops;
4187 Ops << MkId(VMap[ST->getPointerOperand()])
4188 << MkId(VMap[ST->getValueOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004189
David Neto87846742018-04-11 17:36:22 -04004190 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004191 SPIRVInstList.push_back(Inst);
4192 break;
4193 }
4194 case Instruction::AtomicCmpXchg: {
4195 I.print(errs());
4196 llvm_unreachable("Unsupported instruction???");
4197 break;
4198 }
4199 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004200 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4201
4202 spv::Op opcode;
4203
4204 switch (AtomicRMW->getOperation()) {
4205 default:
4206 I.print(errs());
4207 llvm_unreachable("Unsupported instruction???");
4208 case llvm::AtomicRMWInst::Add:
4209 opcode = spv::OpAtomicIAdd;
4210 break;
4211 case llvm::AtomicRMWInst::Sub:
4212 opcode = spv::OpAtomicISub;
4213 break;
4214 case llvm::AtomicRMWInst::Xchg:
4215 opcode = spv::OpAtomicExchange;
4216 break;
4217 case llvm::AtomicRMWInst::Min:
4218 opcode = spv::OpAtomicSMin;
4219 break;
4220 case llvm::AtomicRMWInst::Max:
4221 opcode = spv::OpAtomicSMax;
4222 break;
4223 case llvm::AtomicRMWInst::UMin:
4224 opcode = spv::OpAtomicUMin;
4225 break;
4226 case llvm::AtomicRMWInst::UMax:
4227 opcode = spv::OpAtomicUMax;
4228 break;
4229 case llvm::AtomicRMWInst::And:
4230 opcode = spv::OpAtomicAnd;
4231 break;
4232 case llvm::AtomicRMWInst::Or:
4233 opcode = spv::OpAtomicOr;
4234 break;
4235 case llvm::AtomicRMWInst::Xor:
4236 opcode = spv::OpAtomicXor;
4237 break;
4238 }
4239
4240 //
4241 // Generate OpAtomic*.
4242 //
4243 SPIRVOperandList Ops;
4244
David Neto257c3892018-04-11 13:19:45 -04004245 Ops << MkId(lookupType(I.getType()))
4246 << MkId(VMap[AtomicRMW->getPointerOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004247
4248 auto IntTy = Type::getInt32Ty(I.getContext());
Neil Henning39672102017-09-29 14:33:13 +01004249 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
David Neto257c3892018-04-11 13:19:45 -04004250 Ops << MkId(VMap[ConstantScopeDevice]);
Neil Henning39672102017-09-29 14:33:13 +01004251
4252 const auto ConstantMemorySemantics = ConstantInt::get(
4253 IntTy, spv::MemorySemanticsUniformMemoryMask |
4254 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto257c3892018-04-11 13:19:45 -04004255 Ops << MkId(VMap[ConstantMemorySemantics]);
Neil Henning39672102017-09-29 14:33:13 +01004256
David Neto257c3892018-04-11 13:19:45 -04004257 Ops << MkId(VMap[AtomicRMW->getValOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004258
4259 VMap[&I] = nextID;
4260
David Neto87846742018-04-11 17:36:22 -04004261 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
Neil Henning39672102017-09-29 14:33:13 +01004262 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004263 break;
4264 }
4265 case Instruction::Fence: {
4266 I.print(errs());
4267 llvm_unreachable("Unsupported instruction???");
4268 break;
4269 }
4270 case Instruction::Call: {
4271 CallInst *Call = dyn_cast<CallInst>(&I);
4272 Function *Callee = Call->getCalledFunction();
4273
4274 // Sampler initializers become a load of the corresponding sampler.
4275 if (Callee->getName().equals("__translate_sampler_initializer")) {
4276 // Check that the sampler map was definitely used though.
4277 if (0 == getSamplerMap().size()) {
David Netob050df02018-06-04 15:27:23 -07004278 errs() << "error: kernel uses a literal sampler but option -samplermap "
4279 "has not been specified\n";
David Neto22f144c2017-06-12 14:26:21 -04004280 llvm_unreachable("Sampler literal in source without sampler map!");
4281 }
4282
4283 SPIRVOperandList Ops;
4284
David Neto257c3892018-04-11 13:19:45 -04004285 Ops << MkId(lookupType(SamplerTy->getPointerElementType()))
4286 << MkId(VMap[Call]);
David Neto22f144c2017-06-12 14:26:21 -04004287
4288 VMap[Call] = nextID;
David Neto87846742018-04-11 17:36:22 -04004289 auto *Inst = new SPIRVInstruction(spv::OpLoad, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004290 SPIRVInstList.push_back(Inst);
4291
4292 break;
4293 }
4294
4295 if (Callee->getName().startswith("spirv.atomic")) {
4296 spv::Op opcode = StringSwitch<spv::Op>(Callee->getName())
4297 .Case("spirv.atomic_add", spv::OpAtomicIAdd)
4298 .Case("spirv.atomic_sub", spv::OpAtomicISub)
4299 .Case("spirv.atomic_exchange", spv::OpAtomicExchange)
4300 .Case("spirv.atomic_inc", spv::OpAtomicIIncrement)
4301 .Case("spirv.atomic_dec", spv::OpAtomicIDecrement)
4302 .Case("spirv.atomic_compare_exchange",
4303 spv::OpAtomicCompareExchange)
4304 .Case("spirv.atomic_umin", spv::OpAtomicUMin)
4305 .Case("spirv.atomic_smin", spv::OpAtomicSMin)
4306 .Case("spirv.atomic_umax", spv::OpAtomicUMax)
4307 .Case("spirv.atomic_smax", spv::OpAtomicSMax)
4308 .Case("spirv.atomic_and", spv::OpAtomicAnd)
4309 .Case("spirv.atomic_or", spv::OpAtomicOr)
4310 .Case("spirv.atomic_xor", spv::OpAtomicXor)
4311 .Default(spv::OpNop);
4312
4313 //
4314 // Generate OpAtomic*.
4315 //
4316 SPIRVOperandList Ops;
4317
David Neto257c3892018-04-11 13:19:45 -04004318 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004319
4320 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004321 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004322 }
4323
4324 VMap[&I] = nextID;
4325
David Neto87846742018-04-11 17:36:22 -04004326 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004327 SPIRVInstList.push_back(Inst);
4328 break;
4329 }
4330
4331 if (Callee->getName().startswith("_Z3dot")) {
4332 // If the argument is a vector type, generate OpDot
4333 if (Call->getArgOperand(0)->getType()->isVectorTy()) {
4334 //
4335 // Generate OpDot.
4336 //
4337 SPIRVOperandList Ops;
4338
David Neto257c3892018-04-11 13:19:45 -04004339 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004340
4341 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004342 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004343 }
4344
4345 VMap[&I] = nextID;
4346
David Neto87846742018-04-11 17:36:22 -04004347 auto *Inst = new SPIRVInstruction(spv::OpDot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004348 SPIRVInstList.push_back(Inst);
4349 } else {
4350 //
4351 // Generate OpFMul.
4352 //
4353 SPIRVOperandList Ops;
4354
David Neto257c3892018-04-11 13:19:45 -04004355 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004356
4357 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004358 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004359 }
4360
4361 VMap[&I] = nextID;
4362
David Neto87846742018-04-11 17:36:22 -04004363 auto *Inst = new SPIRVInstruction(spv::OpFMul, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004364 SPIRVInstList.push_back(Inst);
4365 }
4366 break;
4367 }
4368
David Neto8505ebf2017-10-13 18:50:50 -04004369 if (Callee->getName().startswith("_Z4fmod")) {
4370 // OpenCL fmod(x,y) is x - y * trunc(x/y)
4371 // The sign for a non-zero result is taken from x.
4372 // (Try an example.)
4373 // So translate to OpFRem
4374
4375 SPIRVOperandList Ops;
4376
David Neto257c3892018-04-11 13:19:45 -04004377 Ops << MkId(lookupType(I.getType()));
David Neto8505ebf2017-10-13 18:50:50 -04004378
4379 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004380 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto8505ebf2017-10-13 18:50:50 -04004381 }
4382
4383 VMap[&I] = nextID;
4384
David Neto87846742018-04-11 17:36:22 -04004385 auto *Inst = new SPIRVInstruction(spv::OpFRem, nextID++, Ops);
David Neto8505ebf2017-10-13 18:50:50 -04004386 SPIRVInstList.push_back(Inst);
4387 break;
4388 }
4389
David Neto22f144c2017-06-12 14:26:21 -04004390 // spirv.store_null.* intrinsics become OpStore's.
4391 if (Callee->getName().startswith("spirv.store_null")) {
4392 //
4393 // Generate OpStore.
4394 //
4395
4396 // Ops[0] = Pointer ID
4397 // Ops[1] = Object ID
4398 // Ops[2] ... Ops[n]
4399 SPIRVOperandList Ops;
4400
4401 uint32_t PointerID = VMap[Call->getArgOperand(0)];
David Neto22f144c2017-06-12 14:26:21 -04004402 uint32_t ObjectID = VMap[Call->getArgOperand(1)];
David Neto257c3892018-04-11 13:19:45 -04004403 Ops << MkId(PointerID) << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04004404
David Neto87846742018-04-11 17:36:22 -04004405 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpStore, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004406
4407 break;
4408 }
4409
4410 // spirv.copy_memory.* intrinsics become OpMemoryMemory's.
4411 if (Callee->getName().startswith("spirv.copy_memory")) {
4412 //
4413 // Generate OpCopyMemory.
4414 //
4415
4416 // Ops[0] = Dst ID
4417 // Ops[1] = Src ID
4418 // Ops[2] = Memory Access
4419 // Ops[3] = Alignment
4420
4421 auto IsVolatile =
4422 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
4423
4424 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
4425 : spv::MemoryAccessMaskNone;
4426
4427 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
4428
4429 auto Alignment =
4430 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4431
David Neto257c3892018-04-11 13:19:45 -04004432 SPIRVOperandList Ops;
4433 Ops << MkId(VMap[Call->getArgOperand(0)])
4434 << MkId(VMap[Call->getArgOperand(1)]) << MkNum(MemoryAccess)
4435 << MkNum(static_cast<uint32_t>(Alignment));
David Neto22f144c2017-06-12 14:26:21 -04004436
David Neto87846742018-04-11 17:36:22 -04004437 auto *Inst = new SPIRVInstruction(spv::OpCopyMemory, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004438
4439 SPIRVInstList.push_back(Inst);
4440
4441 break;
4442 }
4443
4444 // Nothing to do for abs with uint. Map abs's operand ID to VMap for abs
4445 // with unit.
4446 if (Callee->getName().equals("_Z3absj") ||
4447 Callee->getName().equals("_Z3absDv2_j") ||
4448 Callee->getName().equals("_Z3absDv3_j") ||
4449 Callee->getName().equals("_Z3absDv4_j")) {
4450 VMap[&I] = VMap[Call->getOperand(0)];
4451 break;
4452 }
4453
4454 // barrier is converted to OpControlBarrier
4455 if (Callee->getName().equals("__spirv_control_barrier")) {
4456 //
4457 // Generate OpControlBarrier.
4458 //
4459 // Ops[0] = Execution Scope ID
4460 // Ops[1] = Memory Scope ID
4461 // Ops[2] = Memory Semantics ID
4462 //
4463 Value *ExecutionScope = Call->getArgOperand(0);
4464 Value *MemoryScope = Call->getArgOperand(1);
4465 Value *MemorySemantics = Call->getArgOperand(2);
4466
David Neto257c3892018-04-11 13:19:45 -04004467 SPIRVOperandList Ops;
4468 Ops << MkId(VMap[ExecutionScope]) << MkId(VMap[MemoryScope])
4469 << MkId(VMap[MemorySemantics]);
David Neto22f144c2017-06-12 14:26:21 -04004470
David Neto87846742018-04-11 17:36:22 -04004471 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpControlBarrier, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004472 break;
4473 }
4474
4475 // memory barrier is converted to OpMemoryBarrier
4476 if (Callee->getName().equals("__spirv_memory_barrier")) {
4477 //
4478 // Generate OpMemoryBarrier.
4479 //
4480 // Ops[0] = Memory Scope ID
4481 // Ops[1] = Memory Semantics ID
4482 //
4483 SPIRVOperandList Ops;
4484
David Neto257c3892018-04-11 13:19:45 -04004485 uint32_t MemoryScopeID = VMap[Call->getArgOperand(0)];
4486 uint32_t MemorySemanticsID = VMap[Call->getArgOperand(1)];
David Neto22f144c2017-06-12 14:26:21 -04004487
David Neto257c3892018-04-11 13:19:45 -04004488 Ops << MkId(MemoryScopeID) << MkId(MemorySemanticsID);
David Neto22f144c2017-06-12 14:26:21 -04004489
David Neto87846742018-04-11 17:36:22 -04004490 auto *Inst = new SPIRVInstruction(spv::OpMemoryBarrier, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004491 SPIRVInstList.push_back(Inst);
4492 break;
4493 }
4494
4495 // isinf is converted to OpIsInf
4496 if (Callee->getName().equals("__spirv_isinff") ||
4497 Callee->getName().equals("__spirv_isinfDv2_f") ||
4498 Callee->getName().equals("__spirv_isinfDv3_f") ||
4499 Callee->getName().equals("__spirv_isinfDv4_f")) {
4500 //
4501 // Generate OpIsInf.
4502 //
4503 // Ops[0] = Result Type ID
4504 // Ops[1] = X ID
4505 //
4506 SPIRVOperandList Ops;
4507
David Neto257c3892018-04-11 13:19:45 -04004508 Ops << MkId(lookupType(I.getType()))
4509 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004510
4511 VMap[&I] = nextID;
4512
David Neto87846742018-04-11 17:36:22 -04004513 auto *Inst = new SPIRVInstruction(spv::OpIsInf, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004514 SPIRVInstList.push_back(Inst);
4515 break;
4516 }
4517
4518 // isnan is converted to OpIsNan
4519 if (Callee->getName().equals("__spirv_isnanf") ||
4520 Callee->getName().equals("__spirv_isnanDv2_f") ||
4521 Callee->getName().equals("__spirv_isnanDv3_f") ||
4522 Callee->getName().equals("__spirv_isnanDv4_f")) {
4523 //
4524 // Generate OpIsInf.
4525 //
4526 // Ops[0] = Result Type ID
4527 // Ops[1] = X ID
4528 //
4529 SPIRVOperandList Ops;
4530
David Neto257c3892018-04-11 13:19:45 -04004531 Ops << MkId(lookupType(I.getType()))
4532 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004533
4534 VMap[&I] = nextID;
4535
David Neto87846742018-04-11 17:36:22 -04004536 auto *Inst = new SPIRVInstruction(spv::OpIsNan, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004537 SPIRVInstList.push_back(Inst);
4538 break;
4539 }
4540
4541 // all is converted to OpAll
4542 if (Callee->getName().equals("__spirv_allDv2_i") ||
4543 Callee->getName().equals("__spirv_allDv3_i") ||
4544 Callee->getName().equals("__spirv_allDv4_i")) {
4545 //
4546 // Generate OpAll.
4547 //
4548 // Ops[0] = Result Type ID
4549 // Ops[1] = Vector ID
4550 //
4551 SPIRVOperandList Ops;
4552
David Neto257c3892018-04-11 13:19:45 -04004553 Ops << MkId(lookupType(I.getType()))
4554 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004555
4556 VMap[&I] = nextID;
4557
David Neto87846742018-04-11 17:36:22 -04004558 auto *Inst = new SPIRVInstruction(spv::OpAll, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004559 SPIRVInstList.push_back(Inst);
4560 break;
4561 }
4562
4563 // any is converted to OpAny
4564 if (Callee->getName().equals("__spirv_anyDv2_i") ||
4565 Callee->getName().equals("__spirv_anyDv3_i") ||
4566 Callee->getName().equals("__spirv_anyDv4_i")) {
4567 //
4568 // Generate OpAny.
4569 //
4570 // Ops[0] = Result Type ID
4571 // Ops[1] = Vector ID
4572 //
4573 SPIRVOperandList Ops;
4574
David Neto257c3892018-04-11 13:19:45 -04004575 Ops << MkId(lookupType(I.getType()))
4576 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004577
4578 VMap[&I] = nextID;
4579
David Neto87846742018-04-11 17:36:22 -04004580 auto *Inst = new SPIRVInstruction(spv::OpAny, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004581 SPIRVInstList.push_back(Inst);
4582 break;
4583 }
4584
4585 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
4586 // Additionally, OpTypeSampledImage is generated.
4587 if (Callee->getName().equals(
4588 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
4589 Callee->getName().equals(
4590 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
4591 //
4592 // Generate OpSampledImage.
4593 //
4594 // Ops[0] = Result Type ID
4595 // Ops[1] = Image ID
4596 // Ops[2] = Sampler ID
4597 //
4598 SPIRVOperandList Ops;
4599
4600 Value *Image = Call->getArgOperand(0);
4601 Value *Sampler = Call->getArgOperand(1);
4602 Value *Coordinate = Call->getArgOperand(2);
4603
4604 TypeMapType &OpImageTypeMap = getImageTypeMap();
4605 Type *ImageTy = Image->getType()->getPointerElementType();
4606 uint32_t ImageTyID = OpImageTypeMap[ImageTy];
David Neto22f144c2017-06-12 14:26:21 -04004607 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004608 uint32_t SamplerID = VMap[Sampler];
David Neto257c3892018-04-11 13:19:45 -04004609
4610 Ops << MkId(ImageTyID) << MkId(ImageID) << MkId(SamplerID);
David Neto22f144c2017-06-12 14:26:21 -04004611
4612 uint32_t SampledImageID = nextID;
4613
David Neto87846742018-04-11 17:36:22 -04004614 auto *Inst = new SPIRVInstruction(spv::OpSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004615 SPIRVInstList.push_back(Inst);
4616
4617 //
4618 // Generate OpImageSampleExplicitLod.
4619 //
4620 // Ops[0] = Result Type ID
4621 // Ops[1] = Sampled Image ID
4622 // Ops[2] = Coordinate ID
4623 // Ops[3] = Image Operands Type ID
4624 // Ops[4] ... Ops[n] = Operands ID
4625 //
4626 Ops.clear();
4627
David Neto257c3892018-04-11 13:19:45 -04004628 Ops << MkId(lookupType(Call->getType())) << MkId(SampledImageID)
4629 << MkId(VMap[Coordinate]) << MkNum(spv::ImageOperandsLodMask);
David Neto22f144c2017-06-12 14:26:21 -04004630
4631 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
David Neto257c3892018-04-11 13:19:45 -04004632 Ops << MkId(VMap[CstFP0]);
David Neto22f144c2017-06-12 14:26:21 -04004633
4634 VMap[&I] = nextID;
4635
David Neto87846742018-04-11 17:36:22 -04004636 Inst = new SPIRVInstruction(spv::OpImageSampleExplicitLod, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004637 SPIRVInstList.push_back(Inst);
4638 break;
4639 }
4640
4641 // write_imagef is mapped to OpImageWrite.
4642 if (Callee->getName().equals(
4643 "_Z12write_imagef14ocl_image2d_woDv2_iDv4_f") ||
4644 Callee->getName().equals(
4645 "_Z12write_imagef14ocl_image3d_woDv4_iDv4_f")) {
4646 //
4647 // Generate OpImageWrite.
4648 //
4649 // Ops[0] = Image ID
4650 // Ops[1] = Coordinate ID
4651 // Ops[2] = Texel ID
4652 // Ops[3] = (Optional) Image Operands Type (Literal Number)
4653 // Ops[4] ... Ops[n] = (Optional) Operands ID
4654 //
4655 SPIRVOperandList Ops;
4656
4657 Value *Image = Call->getArgOperand(0);
4658 Value *Coordinate = Call->getArgOperand(1);
4659 Value *Texel = Call->getArgOperand(2);
4660
4661 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004662 uint32_t CoordinateID = VMap[Coordinate];
David Neto22f144c2017-06-12 14:26:21 -04004663 uint32_t TexelID = VMap[Texel];
David Neto257c3892018-04-11 13:19:45 -04004664 Ops << MkId(ImageID) << MkId(CoordinateID) << MkId(TexelID);
David Neto22f144c2017-06-12 14:26:21 -04004665
David Neto87846742018-04-11 17:36:22 -04004666 auto *Inst = new SPIRVInstruction(spv::OpImageWrite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004667 SPIRVInstList.push_back(Inst);
4668 break;
4669 }
4670
David Neto5c22a252018-03-15 16:07:41 -04004671 // get_image_width is mapped to OpImageQuerySize
4672 if (Callee->getName().equals("_Z15get_image_width14ocl_image2d_ro") ||
4673 Callee->getName().equals("_Z15get_image_width14ocl_image2d_wo") ||
4674 Callee->getName().equals("_Z16get_image_height14ocl_image2d_ro") ||
4675 Callee->getName().equals("_Z16get_image_height14ocl_image2d_wo")) {
4676 //
4677 // Generate OpImageQuerySize, then pull out the right component.
4678 // Assume 2D image for now.
4679 //
4680 // Ops[0] = Image ID
4681 //
4682 // %sizes = OpImageQuerySizes %uint2 %im
4683 // %result = OpCompositeExtract %uint %sizes 0-or-1
4684 SPIRVOperandList Ops;
4685
4686 // Implement:
4687 // %sizes = OpImageQuerySizes %uint2 %im
4688 uint32_t SizesTypeID =
4689 TypeMap[VectorType::get(Type::getInt32Ty(Context), 2)];
David Neto5c22a252018-03-15 16:07:41 -04004690 Value *Image = Call->getArgOperand(0);
4691 uint32_t ImageID = VMap[Image];
David Neto257c3892018-04-11 13:19:45 -04004692 Ops << MkId(SizesTypeID) << MkId(ImageID);
David Neto5c22a252018-03-15 16:07:41 -04004693
4694 uint32_t SizesID = nextID++;
David Neto87846742018-04-11 17:36:22 -04004695 auto *QueryInst =
4696 new SPIRVInstruction(spv::OpImageQuerySize, SizesID, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004697 SPIRVInstList.push_back(QueryInst);
4698
4699 // Reset value map entry since we generated an intermediate instruction.
4700 VMap[&I] = nextID;
4701
4702 // Implement:
4703 // %result = OpCompositeExtract %uint %sizes 0-or-1
4704 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004705 Ops << MkId(TypeMap[I.getType()]) << MkId(SizesID);
David Neto5c22a252018-03-15 16:07:41 -04004706
4707 uint32_t component = Callee->getName().contains("height") ? 1 : 0;
David Neto257c3892018-04-11 13:19:45 -04004708 Ops << MkNum(component);
David Neto5c22a252018-03-15 16:07:41 -04004709
David Neto87846742018-04-11 17:36:22 -04004710 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004711 SPIRVInstList.push_back(Inst);
4712 break;
4713 }
4714
David Neto22f144c2017-06-12 14:26:21 -04004715 // Call instrucion is deferred because it needs function's ID. Record
4716 // slot's location on SPIRVInstructionList.
4717 DeferredInsts.push_back(
4718 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4719
David Neto3fbb4072017-10-16 11:28:14 -04004720 // Check whether the implementation of this call uses an extended
4721 // instruction plus one more value-producing instruction. If so, then
4722 // reserve the id for the extra value-producing slot.
4723 glsl::ExtInst EInst = getIndirectExtInstEnum(Callee->getName());
4724 if (EInst != kGlslExtInstBad) {
4725 // Reserve a spot for the extra value.
David Neto4d02a532017-09-17 12:57:44 -04004726 // Increase nextID.
David Neto22f144c2017-06-12 14:26:21 -04004727 VMap[&I] = nextID;
4728 nextID++;
4729 }
4730 break;
4731 }
4732 case Instruction::Ret: {
4733 unsigned NumOps = I.getNumOperands();
4734 if (NumOps == 0) {
4735 //
4736 // Generate OpReturn.
4737 //
David Neto87846742018-04-11 17:36:22 -04004738 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpReturn, {}));
David Neto22f144c2017-06-12 14:26:21 -04004739 } else {
4740 //
4741 // Generate OpReturnValue.
4742 //
4743
4744 // Ops[0] = Return Value ID
4745 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004746
4747 Ops << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004748
David Neto87846742018-04-11 17:36:22 -04004749 auto *Inst = new SPIRVInstruction(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004750 SPIRVInstList.push_back(Inst);
4751 break;
4752 }
4753 break;
4754 }
4755 }
4756}
4757
4758void SPIRVProducerPass::GenerateFuncEpilogue() {
4759 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4760
4761 //
4762 // Generate OpFunctionEnd
4763 //
4764
David Neto87846742018-04-11 17:36:22 -04004765 auto *Inst = new SPIRVInstruction(spv::OpFunctionEnd, {});
David Neto22f144c2017-06-12 14:26:21 -04004766 SPIRVInstList.push_back(Inst);
4767}
4768
4769bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
4770 LLVMContext &Context = Ty->getContext();
4771 if (Ty->isVectorTy()) {
4772 if (Ty->getVectorElementType() == Type::getInt8Ty(Context) &&
4773 Ty->getVectorNumElements() == 4) {
4774 return true;
4775 }
4776 }
4777
4778 return false;
4779}
4780
David Neto257c3892018-04-11 13:19:45 -04004781uint32_t SPIRVProducerPass::GetI32Zero() {
4782 if (0 == constant_i32_zero_id_) {
4783 llvm_unreachable("Requesting a 32-bit integer constant but it is not "
4784 "defined in the SPIR-V module");
4785 }
4786 return constant_i32_zero_id_;
4787}
4788
David Neto22f144c2017-06-12 14:26:21 -04004789void SPIRVProducerPass::HandleDeferredInstruction() {
4790 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4791 ValueMapType &VMap = getValueMap();
4792 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4793
4794 for (auto DeferredInst = DeferredInsts.rbegin();
4795 DeferredInst != DeferredInsts.rend(); ++DeferredInst) {
4796 Value *Inst = std::get<0>(*DeferredInst);
4797 SPIRVInstructionList::iterator InsertPoint = ++std::get<1>(*DeferredInst);
4798 if (InsertPoint != SPIRVInstList.end()) {
4799 while ((*InsertPoint)->getOpcode() == spv::OpPhi) {
4800 ++InsertPoint;
4801 }
4802 }
4803
4804 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
4805 // Check whether basic block, which has this branch instruction, is loop
4806 // header or not. If it is loop header, generate OpLoopMerge and
4807 // OpBranchConditional.
4808 Function *Func = Br->getParent()->getParent();
4809 DominatorTree &DT =
4810 getAnalysis<DominatorTreeWrapperPass>(*Func).getDomTree();
4811 const LoopInfo &LI =
4812 getAnalysis<LoopInfoWrapperPass>(*Func).getLoopInfo();
4813
4814 BasicBlock *BrBB = Br->getParent();
4815 if (LI.isLoopHeader(BrBB)) {
4816 Value *ContinueBB = nullptr;
4817 Value *MergeBB = nullptr;
4818
4819 Loop *L = LI.getLoopFor(BrBB);
4820 MergeBB = L->getExitBlock();
4821 if (!MergeBB) {
4822 // StructurizeCFG pass converts CFG into triangle shape and the cfg
4823 // has regions with single entry/exit. As a result, loop should not
4824 // have multiple exits.
4825 llvm_unreachable("Loop has multiple exits???");
4826 }
4827
4828 if (L->isLoopLatch(BrBB)) {
4829 ContinueBB = BrBB;
4830 } else {
4831 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
4832 // block.
4833 BasicBlock *Header = L->getHeader();
4834 BasicBlock *Latch = L->getLoopLatch();
4835 for (BasicBlock *BB : L->blocks()) {
4836 if (BB == Header) {
4837 continue;
4838 }
4839
4840 // Check whether block dominates block with back-edge.
4841 if (DT.dominates(BB, Latch)) {
4842 ContinueBB = BB;
4843 }
4844 }
4845
4846 if (!ContinueBB) {
4847 llvm_unreachable("Wrong continue block from loop");
4848 }
4849 }
4850
4851 //
4852 // Generate OpLoopMerge.
4853 //
4854 // Ops[0] = Merge Block ID
4855 // Ops[1] = Continue Target ID
4856 // Ops[2] = Selection Control
4857 SPIRVOperandList Ops;
4858
4859 // StructurizeCFG pass already manipulated CFG. Just use false block of
4860 // branch instruction as merge block.
4861 uint32_t MergeBBID = VMap[MergeBB];
David Neto22f144c2017-06-12 14:26:21 -04004862 uint32_t ContinueBBID = VMap[ContinueBB];
David Neto257c3892018-04-11 13:19:45 -04004863 Ops << MkId(MergeBBID) << MkId(ContinueBBID)
4864 << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004865
David Neto87846742018-04-11 17:36:22 -04004866 auto *MergeInst = new SPIRVInstruction(spv::OpLoopMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004867 SPIRVInstList.insert(InsertPoint, MergeInst);
4868
4869 } else if (Br->isConditional()) {
4870 bool HasBackEdge = false;
4871
4872 for (unsigned i = 0; i < Br->getNumSuccessors(); i++) {
4873 if (LI.isLoopHeader(Br->getSuccessor(i))) {
4874 HasBackEdge = true;
4875 }
4876 }
4877 if (!HasBackEdge) {
4878 //
4879 // Generate OpSelectionMerge.
4880 //
4881 // Ops[0] = Merge Block ID
4882 // Ops[1] = Selection Control
4883 SPIRVOperandList Ops;
4884
4885 // StructurizeCFG pass already manipulated CFG. Just use false block
4886 // of branch instruction as merge block.
4887 uint32_t MergeBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004888 Ops << MkId(MergeBBID) << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004889
David Neto87846742018-04-11 17:36:22 -04004890 auto *MergeInst = new SPIRVInstruction(spv::OpSelectionMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004891 SPIRVInstList.insert(InsertPoint, MergeInst);
4892 }
4893 }
4894
4895 if (Br->isConditional()) {
4896 //
4897 // Generate OpBranchConditional.
4898 //
4899 // Ops[0] = Condition ID
4900 // Ops[1] = True Label ID
4901 // Ops[2] = False Label ID
4902 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
4903 SPIRVOperandList Ops;
4904
4905 uint32_t CondID = VMap[Br->getCondition()];
David Neto22f144c2017-06-12 14:26:21 -04004906 uint32_t TrueBBID = VMap[Br->getSuccessor(0)];
David Neto22f144c2017-06-12 14:26:21 -04004907 uint32_t FalseBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004908
4909 Ops << MkId(CondID) << MkId(TrueBBID) << MkId(FalseBBID);
David Neto22f144c2017-06-12 14:26:21 -04004910
David Neto87846742018-04-11 17:36:22 -04004911 auto *BrInst = new SPIRVInstruction(spv::OpBranchConditional, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004912 SPIRVInstList.insert(InsertPoint, BrInst);
4913 } else {
4914 //
4915 // Generate OpBranch.
4916 //
4917 // Ops[0] = Target Label ID
4918 SPIRVOperandList Ops;
4919
4920 uint32_t TargetID = VMap[Br->getSuccessor(0)];
David Neto257c3892018-04-11 13:19:45 -04004921 Ops << MkId(TargetID);
David Neto22f144c2017-06-12 14:26:21 -04004922
David Neto87846742018-04-11 17:36:22 -04004923 SPIRVInstList.insert(InsertPoint,
4924 new SPIRVInstruction(spv::OpBranch, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004925 }
4926 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
4927 //
4928 // Generate OpPhi.
4929 //
4930 // Ops[0] = Result Type ID
4931 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
4932 SPIRVOperandList Ops;
4933
David Neto257c3892018-04-11 13:19:45 -04004934 Ops << MkId(lookupType(PHI->getType()));
David Neto22f144c2017-06-12 14:26:21 -04004935
David Neto22f144c2017-06-12 14:26:21 -04004936 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
4937 uint32_t VarID = VMap[PHI->getIncomingValue(i)];
David Neto22f144c2017-06-12 14:26:21 -04004938 uint32_t ParentID = VMap[PHI->getIncomingBlock(i)];
David Neto257c3892018-04-11 13:19:45 -04004939 Ops << MkId(VarID) << MkId(ParentID);
David Neto22f144c2017-06-12 14:26:21 -04004940 }
4941
4942 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04004943 InsertPoint,
4944 new SPIRVInstruction(spv::OpPhi, std::get<2>(*DeferredInst), Ops));
David Neto22f144c2017-06-12 14:26:21 -04004945 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
4946 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04004947 auto callee_name = Callee->getName();
4948 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04004949
4950 if (EInst) {
4951 uint32_t &ExtInstImportID = getOpExtInstImportID();
4952
4953 //
4954 // Generate OpExtInst.
4955 //
4956
4957 // Ops[0] = Result Type ID
4958 // Ops[1] = Set ID (OpExtInstImport ID)
4959 // Ops[2] = Instruction Number (Literal Number)
4960 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
4961 SPIRVOperandList Ops;
4962
David Neto257c3892018-04-11 13:19:45 -04004963 Ops << MkId(lookupType(Call->getType())) << MkId(ExtInstImportID) << MkNum(EInst);
David Neto22f144c2017-06-12 14:26:21 -04004964
David Neto22f144c2017-06-12 14:26:21 -04004965 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
4966 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004967 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004968 }
4969
David Neto87846742018-04-11 17:36:22 -04004970 auto *ExtInst = new SPIRVInstruction(spv::OpExtInst,
4971 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04004972 SPIRVInstList.insert(InsertPoint, ExtInst);
4973
David Neto3fbb4072017-10-16 11:28:14 -04004974 const auto IndirectExtInst = getIndirectExtInstEnum(callee_name);
4975 if (IndirectExtInst != kGlslExtInstBad) {
4976 // Generate one more instruction that uses the result of the extended
4977 // instruction. Its result id is one more than the id of the
4978 // extended instruction.
David Neto22f144c2017-06-12 14:26:21 -04004979 LLVMContext &Context =
4980 Call->getParent()->getParent()->getParent()->getContext();
David Neto22f144c2017-06-12 14:26:21 -04004981
David Neto3fbb4072017-10-16 11:28:14 -04004982 auto generate_extra_inst = [this, &Context, &Call, &DeferredInst,
4983 &VMap, &SPIRVInstList, &InsertPoint](
4984 spv::Op opcode, Constant *constant) {
4985 //
4986 // Generate instruction like:
4987 // result = opcode constant <extinst-result>
4988 //
4989 // Ops[0] = Result Type ID
4990 // Ops[1] = Operand 0 ;; the constant, suitably splatted
4991 // Ops[2] = Operand 1 ;; the result of the extended instruction
4992 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004993
David Neto3fbb4072017-10-16 11:28:14 -04004994 Type *resultTy = Call->getType();
David Neto257c3892018-04-11 13:19:45 -04004995 Ops << MkId(lookupType(resultTy));
David Neto3fbb4072017-10-16 11:28:14 -04004996
4997 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
4998 constant = ConstantVector::getSplat(
4999 static_cast<unsigned>(vectorTy->getNumElements()), constant);
5000 }
David Neto257c3892018-04-11 13:19:45 -04005001 Ops << MkId(VMap[constant]) << MkId(std::get<2>(*DeferredInst));
David Neto3fbb4072017-10-16 11:28:14 -04005002
5003 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005004 InsertPoint, new SPIRVInstruction(
5005 opcode, std::get<2>(*DeferredInst) + 1, Ops));
David Neto3fbb4072017-10-16 11:28:14 -04005006 };
5007
5008 switch (IndirectExtInst) {
5009 case glsl::ExtInstFindUMsb: // Implementing clz
5010 generate_extra_inst(
5011 spv::OpISub, ConstantInt::get(Type::getInt32Ty(Context), 31));
5012 break;
5013 case glsl::ExtInstAcos: // Implementing acospi
5014 case glsl::ExtInstAsin: // Implementing asinpi
5015 case glsl::ExtInstAtan2: // Implementing atan2pi
5016 generate_extra_inst(
5017 spv::OpFMul,
5018 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
5019 break;
5020
5021 default:
5022 assert(false && "internally inconsistent");
David Neto4d02a532017-09-17 12:57:44 -04005023 }
David Neto22f144c2017-06-12 14:26:21 -04005024 }
David Neto3fbb4072017-10-16 11:28:14 -04005025
David Neto22f144c2017-06-12 14:26:21 -04005026 } else if (Callee->getName().equals("_Z8popcounti") ||
5027 Callee->getName().equals("_Z8popcountj") ||
5028 Callee->getName().equals("_Z8popcountDv2_i") ||
5029 Callee->getName().equals("_Z8popcountDv3_i") ||
5030 Callee->getName().equals("_Z8popcountDv4_i") ||
5031 Callee->getName().equals("_Z8popcountDv2_j") ||
5032 Callee->getName().equals("_Z8popcountDv3_j") ||
5033 Callee->getName().equals("_Z8popcountDv4_j")) {
5034 //
5035 // Generate OpBitCount
5036 //
5037 // Ops[0] = Result Type ID
5038 // Ops[1] = Base ID
David Neto257c3892018-04-11 13:19:45 -04005039 SPIRVOperandList Ops;
5040 Ops << MkId(lookupType(Call->getType()))
5041 << MkId(VMap[Call->getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04005042
5043 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005044 InsertPoint, new SPIRVInstruction(spv::OpBitCount,
David Neto22f144c2017-06-12 14:26:21 -04005045 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005046
5047 } else if (Callee->getName().startswith(kCompositeConstructFunctionPrefix)) {
5048
5049 // Generate an OpCompositeConstruct
5050 SPIRVOperandList Ops;
5051
5052 // The result type.
David Neto257c3892018-04-11 13:19:45 -04005053 Ops << MkId(lookupType(Call->getType()));
David Netoab03f432017-11-03 17:00:44 -04005054
5055 for (Use &use : Call->arg_operands()) {
David Neto257c3892018-04-11 13:19:45 -04005056 Value *val = use.get();
5057 Ops << MkId(VMap[use.get()]);
David Netoab03f432017-11-03 17:00:44 -04005058 }
5059
5060 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005061 InsertPoint, new SPIRVInstruction(spv::OpCompositeConstruct,
5062 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005063
David Neto22f144c2017-06-12 14:26:21 -04005064 } else {
5065 //
5066 // Generate OpFunctionCall.
5067 //
5068
5069 // Ops[0] = Result Type ID
5070 // Ops[1] = Callee Function ID
5071 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
5072 SPIRVOperandList Ops;
5073
David Neto257c3892018-04-11 13:19:45 -04005074 Ops << MkId( lookupType(Call->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005075
5076 uint32_t CalleeID = VMap[Callee];
David Neto43568eb2017-10-13 18:25:25 -04005077 if (CalleeID == 0) {
5078 errs() << "Can't translate function call. Missing builtin? "
5079 << Callee->getName() << " in: " << *Call << "\n";
5080 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
5081 // causes an infinite loop. Instead, go ahead and generate
5082 // the bad function call. A validator will catch the 0-Id.
5083 // llvm_unreachable("Can't translate function call");
5084 }
David Neto22f144c2017-06-12 14:26:21 -04005085
David Neto257c3892018-04-11 13:19:45 -04005086 Ops << MkId(CalleeID);
David Neto22f144c2017-06-12 14:26:21 -04005087
David Neto22f144c2017-06-12 14:26:21 -04005088 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5089 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04005090 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04005091 }
5092
David Neto87846742018-04-11 17:36:22 -04005093 auto *CallInst = new SPIRVInstruction(spv::OpFunctionCall,
5094 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005095 SPIRVInstList.insert(InsertPoint, CallInst);
5096 }
5097 }
5098 }
5099}
5100
David Neto1a1a0582017-07-07 12:01:44 -04005101void SPIRVProducerPass::HandleDeferredDecorations(const DataLayout &DL) {
David Netoc6f3ab22018-04-06 18:02:31 -04005102 if (getTypesNeedingArrayStride().empty() && LocalArgs.empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04005103 return;
David Netoc6f3ab22018-04-06 18:02:31 -04005104 }
David Neto1a1a0582017-07-07 12:01:44 -04005105
5106 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto1a1a0582017-07-07 12:01:44 -04005107
5108 // Find an iterator pointing just past the last decoration.
5109 bool seen_decorations = false;
5110 auto DecoInsertPoint =
5111 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
5112 [&seen_decorations](SPIRVInstruction *Inst) -> bool {
5113 const bool is_decoration =
5114 Inst->getOpcode() == spv::OpDecorate ||
5115 Inst->getOpcode() == spv::OpMemberDecorate;
5116 if (is_decoration) {
5117 seen_decorations = true;
5118 return false;
5119 } else {
5120 return seen_decorations;
5121 }
5122 });
5123
David Netoc6f3ab22018-04-06 18:02:31 -04005124 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
5125 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07005126 for (auto *type : getTypesNeedingArrayStride()) {
5127 Type *elemTy = nullptr;
5128 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
5129 elemTy = ptrTy->getElementType();
5130 } else if (auto* arrayTy = dyn_cast<ArrayType>(type)) {
5131 elemTy = arrayTy->getArrayElementType();
5132 } else if (auto* seqTy = dyn_cast<SequentialType>(type)) {
5133 elemTy = seqTy->getSequentialElementType();
5134 } else {
5135 errs() << "Unhandled strided type " << *type << "\n";
5136 llvm_unreachable("Unhandled strided type");
5137 }
David Neto1a1a0582017-07-07 12:01:44 -04005138
5139 // Ops[0] = Target ID
5140 // Ops[1] = Decoration (ArrayStride)
5141 // Ops[2] = Stride number (Literal Number)
5142 SPIRVOperandList Ops;
5143
David Neto85082642018-03-24 06:55:20 -07005144 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Neil Henning39672102017-09-29 14:33:13 +01005145 const uint32_t stride = static_cast<uint32_t>(DL.getTypeAllocSize(elemTy));
David Neto257c3892018-04-11 13:19:45 -04005146
5147 Ops << MkId(lookupType(type)) << MkNum(spv::DecorationArrayStride)
5148 << MkNum(stride);
David Neto1a1a0582017-07-07 12:01:44 -04005149
David Neto87846742018-04-11 17:36:22 -04005150 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto1a1a0582017-07-07 12:01:44 -04005151 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
5152 }
David Netoc6f3ab22018-04-06 18:02:31 -04005153
5154 // Emit SpecId decorations targeting the array size value.
5155 for (const Argument *arg : LocalArgs) {
5156 const LocalArgInfo &arg_info = LocalArgMap[arg];
5157 SPIRVOperandList Ops;
5158 Ops << MkId(arg_info.array_size_id) << MkNum(spv::DecorationSpecId)
5159 << MkNum(arg_info.spec_id);
5160 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04005161 new SPIRVInstruction(spv::OpDecorate, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04005162 }
David Neto1a1a0582017-07-07 12:01:44 -04005163}
5164
David Neto22f144c2017-06-12 14:26:21 -04005165glsl::ExtInst SPIRVProducerPass::getExtInstEnum(StringRef Name) {
5166 return StringSwitch<glsl::ExtInst>(Name)
5167 .Case("_Z3absi", glsl::ExtInst::ExtInstSAbs)
5168 .Case("_Z3absDv2_i", glsl::ExtInst::ExtInstSAbs)
5169 .Case("_Z3absDv3_i", glsl::ExtInst::ExtInstSAbs)
5170 .Case("_Z3absDv4_i", glsl::ExtInst::ExtInstSAbs)
5171 .Case("_Z5clampiii", glsl::ExtInst::ExtInstSClamp)
5172 .Case("_Z5clampDv2_iS_S_", glsl::ExtInst::ExtInstSClamp)
5173 .Case("_Z5clampDv3_iS_S_", glsl::ExtInst::ExtInstSClamp)
5174 .Case("_Z5clampDv4_iS_S_", glsl::ExtInst::ExtInstSClamp)
5175 .Case("_Z5clampjjj", glsl::ExtInst::ExtInstUClamp)
5176 .Case("_Z5clampDv2_jS_S_", glsl::ExtInst::ExtInstUClamp)
5177 .Case("_Z5clampDv3_jS_S_", glsl::ExtInst::ExtInstUClamp)
5178 .Case("_Z5clampDv4_jS_S_", glsl::ExtInst::ExtInstUClamp)
5179 .Case("_Z5clampfff", glsl::ExtInst::ExtInstFClamp)
5180 .Case("_Z5clampDv2_fS_S_", glsl::ExtInst::ExtInstFClamp)
5181 .Case("_Z5clampDv3_fS_S_", glsl::ExtInst::ExtInstFClamp)
5182 .Case("_Z5clampDv4_fS_S_", glsl::ExtInst::ExtInstFClamp)
David Neto22f144c2017-06-12 14:26:21 -04005183 .Case("_Z3maxii", glsl::ExtInst::ExtInstSMax)
5184 .Case("_Z3maxDv2_iS_", glsl::ExtInst::ExtInstSMax)
5185 .Case("_Z3maxDv3_iS_", glsl::ExtInst::ExtInstSMax)
5186 .Case("_Z3maxDv4_iS_", glsl::ExtInst::ExtInstSMax)
5187 .Case("_Z3maxjj", glsl::ExtInst::ExtInstUMax)
5188 .Case("_Z3maxDv2_jS_", glsl::ExtInst::ExtInstUMax)
5189 .Case("_Z3maxDv3_jS_", glsl::ExtInst::ExtInstUMax)
5190 .Case("_Z3maxDv4_jS_", glsl::ExtInst::ExtInstUMax)
5191 .Case("_Z3maxff", glsl::ExtInst::ExtInstFMax)
5192 .Case("_Z3maxDv2_fS_", glsl::ExtInst::ExtInstFMax)
5193 .Case("_Z3maxDv3_fS_", glsl::ExtInst::ExtInstFMax)
5194 .Case("_Z3maxDv4_fS_", glsl::ExtInst::ExtInstFMax)
5195 .StartsWith("_Z4fmax", glsl::ExtInst::ExtInstFMax)
5196 .Case("_Z3minii", glsl::ExtInst::ExtInstSMin)
5197 .Case("_Z3minDv2_iS_", glsl::ExtInst::ExtInstSMin)
5198 .Case("_Z3minDv3_iS_", glsl::ExtInst::ExtInstSMin)
5199 .Case("_Z3minDv4_iS_", glsl::ExtInst::ExtInstSMin)
5200 .Case("_Z3minjj", glsl::ExtInst::ExtInstUMin)
5201 .Case("_Z3minDv2_jS_", glsl::ExtInst::ExtInstUMin)
5202 .Case("_Z3minDv3_jS_", glsl::ExtInst::ExtInstUMin)
5203 .Case("_Z3minDv4_jS_", glsl::ExtInst::ExtInstUMin)
5204 .Case("_Z3minff", glsl::ExtInst::ExtInstFMin)
5205 .Case("_Z3minDv2_fS_", glsl::ExtInst::ExtInstFMin)
5206 .Case("_Z3minDv3_fS_", glsl::ExtInst::ExtInstFMin)
5207 .Case("_Z3minDv4_fS_", glsl::ExtInst::ExtInstFMin)
5208 .StartsWith("_Z4fmin", glsl::ExtInst::ExtInstFMin)
5209 .StartsWith("_Z7degrees", glsl::ExtInst::ExtInstDegrees)
5210 .StartsWith("_Z7radians", glsl::ExtInst::ExtInstRadians)
5211 .StartsWith("_Z3mix", glsl::ExtInst::ExtInstFMix)
5212 .StartsWith("_Z4acos", glsl::ExtInst::ExtInstAcos)
5213 .StartsWith("_Z5acosh", glsl::ExtInst::ExtInstAcosh)
5214 .StartsWith("_Z4asin", glsl::ExtInst::ExtInstAsin)
5215 .StartsWith("_Z5asinh", glsl::ExtInst::ExtInstAsinh)
5216 .StartsWith("_Z4atan", glsl::ExtInst::ExtInstAtan)
5217 .StartsWith("_Z5atan2", glsl::ExtInst::ExtInstAtan2)
5218 .StartsWith("_Z5atanh", glsl::ExtInst::ExtInstAtanh)
5219 .StartsWith("_Z4ceil", glsl::ExtInst::ExtInstCeil)
5220 .StartsWith("_Z3sin", glsl::ExtInst::ExtInstSin)
5221 .StartsWith("_Z4sinh", glsl::ExtInst::ExtInstSinh)
5222 .StartsWith("_Z8half_sin", glsl::ExtInst::ExtInstSin)
5223 .StartsWith("_Z10native_sin", glsl::ExtInst::ExtInstSin)
5224 .StartsWith("_Z3cos", glsl::ExtInst::ExtInstCos)
5225 .StartsWith("_Z4cosh", glsl::ExtInst::ExtInstCosh)
5226 .StartsWith("_Z8half_cos", glsl::ExtInst::ExtInstCos)
5227 .StartsWith("_Z10native_cos", glsl::ExtInst::ExtInstCos)
5228 .StartsWith("_Z3tan", glsl::ExtInst::ExtInstTan)
5229 .StartsWith("_Z4tanh", glsl::ExtInst::ExtInstTanh)
5230 .StartsWith("_Z8half_tan", glsl::ExtInst::ExtInstTan)
5231 .StartsWith("_Z10native_tan", glsl::ExtInst::ExtInstTan)
5232 .StartsWith("_Z3exp", glsl::ExtInst::ExtInstExp)
5233 .StartsWith("_Z8half_exp", glsl::ExtInst::ExtInstExp)
5234 .StartsWith("_Z10native_exp", glsl::ExtInst::ExtInstExp)
5235 .StartsWith("_Z4exp2", glsl::ExtInst::ExtInstExp2)
5236 .StartsWith("_Z9half_exp2", glsl::ExtInst::ExtInstExp2)
5237 .StartsWith("_Z11native_exp2", glsl::ExtInst::ExtInstExp2)
5238 .StartsWith("_Z3log", glsl::ExtInst::ExtInstLog)
5239 .StartsWith("_Z8half_log", glsl::ExtInst::ExtInstLog)
5240 .StartsWith("_Z10native_log", glsl::ExtInst::ExtInstLog)
5241 .StartsWith("_Z4log2", glsl::ExtInst::ExtInstLog2)
5242 .StartsWith("_Z9half_log2", glsl::ExtInst::ExtInstLog2)
5243 .StartsWith("_Z11native_log2", glsl::ExtInst::ExtInstLog2)
5244 .StartsWith("_Z4fabs", glsl::ExtInst::ExtInstFAbs)
5245 .StartsWith("_Z5floor", glsl::ExtInst::ExtInstFloor)
5246 .StartsWith("_Z5ldexp", glsl::ExtInst::ExtInstLdexp)
5247 .StartsWith("_Z3pow", glsl::ExtInst::ExtInstPow)
5248 .StartsWith("_Z4powr", glsl::ExtInst::ExtInstPow)
5249 .StartsWith("_Z9half_powr", glsl::ExtInst::ExtInstPow)
5250 .StartsWith("_Z11native_powr", glsl::ExtInst::ExtInstPow)
5251 .StartsWith("_Z5round", glsl::ExtInst::ExtInstRound)
5252 .StartsWith("_Z4sqrt", glsl::ExtInst::ExtInstSqrt)
5253 .StartsWith("_Z9half_sqrt", glsl::ExtInst::ExtInstSqrt)
5254 .StartsWith("_Z11native_sqrt", glsl::ExtInst::ExtInstSqrt)
5255 .StartsWith("_Z5rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5256 .StartsWith("_Z10half_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5257 .StartsWith("_Z12native_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5258 .StartsWith("_Z5trunc", glsl::ExtInst::ExtInstTrunc)
5259 .StartsWith("_Z5frexp", glsl::ExtInst::ExtInstFrexp)
5260 .StartsWith("_Z4sign", glsl::ExtInst::ExtInstFSign)
5261 .StartsWith("_Z6length", glsl::ExtInst::ExtInstLength)
5262 .StartsWith("_Z8distance", glsl::ExtInst::ExtInstDistance)
David Netoe9a03512017-10-16 10:08:27 -04005263 .StartsWith("_Z4step", glsl::ExtInst::ExtInstStep)
David Neto22f144c2017-06-12 14:26:21 -04005264 .Case("_Z5crossDv3_fS_", glsl::ExtInst::ExtInstCross)
5265 .StartsWith("_Z9normalize", glsl::ExtInst::ExtInstNormalize)
5266 .StartsWith("llvm.fmuladd.", glsl::ExtInst::ExtInstFma)
5267 .Case("spirv.unpack.v2f16", glsl::ExtInst::ExtInstUnpackHalf2x16)
5268 .Case("spirv.pack.v2f16", glsl::ExtInst::ExtInstPackHalf2x16)
David Neto62653202017-10-16 19:05:18 -04005269 .Case("clspv.fract.f", glsl::ExtInst::ExtInstFract)
5270 .Case("clspv.fract.v2f", glsl::ExtInst::ExtInstFract)
5271 .Case("clspv.fract.v3f", glsl::ExtInst::ExtInstFract)
5272 .Case("clspv.fract.v4f", glsl::ExtInst::ExtInstFract)
David Neto3fbb4072017-10-16 11:28:14 -04005273 .Default(kGlslExtInstBad);
5274}
5275
5276glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(StringRef Name) {
5277 // Check indirect cases.
5278 return StringSwitch<glsl::ExtInst>(Name)
5279 .StartsWith("_Z3clz", glsl::ExtInst::ExtInstFindUMsb)
5280 // Use exact match on float arg because these need a multiply
5281 // of a constant of the right floating point type.
5282 .Case("_Z6acospif", glsl::ExtInst::ExtInstAcos)
5283 .Case("_Z6acospiDv2_f", glsl::ExtInst::ExtInstAcos)
5284 .Case("_Z6acospiDv3_f", glsl::ExtInst::ExtInstAcos)
5285 .Case("_Z6acospiDv4_f", glsl::ExtInst::ExtInstAcos)
5286 .Case("_Z6asinpif", glsl::ExtInst::ExtInstAsin)
5287 .Case("_Z6asinpiDv2_f", glsl::ExtInst::ExtInstAsin)
5288 .Case("_Z6asinpiDv3_f", glsl::ExtInst::ExtInstAsin)
5289 .Case("_Z6asinpiDv4_f", glsl::ExtInst::ExtInstAsin)
5290 .Case("_Z7atan2piff", glsl::ExtInst::ExtInstAtan2)
5291 .Case("_Z7atan2piDv2_fS_", glsl::ExtInst::ExtInstAtan2)
5292 .Case("_Z7atan2piDv3_fS_", glsl::ExtInst::ExtInstAtan2)
5293 .Case("_Z7atan2piDv4_fS_", glsl::ExtInst::ExtInstAtan2)
5294 .Default(kGlslExtInstBad);
5295}
5296
5297glsl::ExtInst SPIRVProducerPass::getDirectOrIndirectExtInstEnum(StringRef Name) {
5298 auto direct = getExtInstEnum(Name);
5299 if (direct != kGlslExtInstBad)
5300 return direct;
5301 return getIndirectExtInstEnum(Name);
David Neto22f144c2017-06-12 14:26:21 -04005302}
5303
5304void SPIRVProducerPass::PrintResID(SPIRVInstruction *Inst) {
5305 out << "%" << Inst->getResultID();
5306}
5307
5308void SPIRVProducerPass::PrintOpcode(SPIRVInstruction *Inst) {
5309 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5310 out << "\t" << spv::getOpName(Opcode);
5311}
5312
5313void SPIRVProducerPass::PrintOperand(SPIRVOperand *Op) {
5314 SPIRVOperandType OpTy = Op->getType();
5315 switch (OpTy) {
5316 default: {
5317 llvm_unreachable("Unsupported SPIRV Operand Type???");
5318 break;
5319 }
5320 case SPIRVOperandType::NUMBERID: {
5321 out << "%" << Op->getNumID();
5322 break;
5323 }
5324 case SPIRVOperandType::LITERAL_STRING: {
5325 out << "\"" << Op->getLiteralStr() << "\"";
5326 break;
5327 }
5328 case SPIRVOperandType::LITERAL_INTEGER: {
5329 // TODO: Handle LiteralNum carefully.
5330 for (auto Word : Op->getLiteralNum()) {
5331 out << Word;
5332 }
5333 break;
5334 }
5335 case SPIRVOperandType::LITERAL_FLOAT: {
5336 // TODO: Handle LiteralNum carefully.
5337 for (auto Word : Op->getLiteralNum()) {
5338 APFloat APF = APFloat(APFloat::IEEEsingle(), APInt(32, Word));
5339 SmallString<8> Str;
5340 APF.toString(Str, 6, 2);
5341 out << Str;
5342 }
5343 break;
5344 }
5345 }
5346}
5347
5348void SPIRVProducerPass::PrintCapability(SPIRVOperand *Op) {
5349 spv::Capability Cap = static_cast<spv::Capability>(Op->getNumID());
5350 out << spv::getCapabilityName(Cap);
5351}
5352
5353void SPIRVProducerPass::PrintExtInst(SPIRVOperand *Op) {
5354 auto LiteralNum = Op->getLiteralNum();
5355 glsl::ExtInst Ext = static_cast<glsl::ExtInst>(LiteralNum[0]);
5356 out << glsl::getExtInstName(Ext);
5357}
5358
5359void SPIRVProducerPass::PrintAddrModel(SPIRVOperand *Op) {
5360 spv::AddressingModel AddrModel =
5361 static_cast<spv::AddressingModel>(Op->getNumID());
5362 out << spv::getAddressingModelName(AddrModel);
5363}
5364
5365void SPIRVProducerPass::PrintMemModel(SPIRVOperand *Op) {
5366 spv::MemoryModel MemModel = static_cast<spv::MemoryModel>(Op->getNumID());
5367 out << spv::getMemoryModelName(MemModel);
5368}
5369
5370void SPIRVProducerPass::PrintExecModel(SPIRVOperand *Op) {
5371 spv::ExecutionModel ExecModel =
5372 static_cast<spv::ExecutionModel>(Op->getNumID());
5373 out << spv::getExecutionModelName(ExecModel);
5374}
5375
5376void SPIRVProducerPass::PrintExecMode(SPIRVOperand *Op) {
5377 spv::ExecutionMode ExecMode = static_cast<spv::ExecutionMode>(Op->getNumID());
5378 out << spv::getExecutionModeName(ExecMode);
5379}
5380
5381void SPIRVProducerPass::PrintSourceLanguage(SPIRVOperand *Op) {
5382 spv::SourceLanguage SourceLang = static_cast<spv::SourceLanguage>(Op->getNumID());
5383 out << spv::getSourceLanguageName(SourceLang);
5384}
5385
5386void SPIRVProducerPass::PrintFuncCtrl(SPIRVOperand *Op) {
5387 spv::FunctionControlMask FuncCtrl =
5388 static_cast<spv::FunctionControlMask>(Op->getNumID());
5389 out << spv::getFunctionControlName(FuncCtrl);
5390}
5391
5392void SPIRVProducerPass::PrintStorageClass(SPIRVOperand *Op) {
5393 spv::StorageClass StClass = static_cast<spv::StorageClass>(Op->getNumID());
5394 out << getStorageClassName(StClass);
5395}
5396
5397void SPIRVProducerPass::PrintDecoration(SPIRVOperand *Op) {
5398 spv::Decoration Deco = static_cast<spv::Decoration>(Op->getNumID());
5399 out << getDecorationName(Deco);
5400}
5401
5402void SPIRVProducerPass::PrintBuiltIn(SPIRVOperand *Op) {
5403 spv::BuiltIn BIn = static_cast<spv::BuiltIn>(Op->getNumID());
5404 out << getBuiltInName(BIn);
5405}
5406
5407void SPIRVProducerPass::PrintSelectionControl(SPIRVOperand *Op) {
5408 spv::SelectionControlMask BIn =
5409 static_cast<spv::SelectionControlMask>(Op->getNumID());
5410 out << getSelectionControlName(BIn);
5411}
5412
5413void SPIRVProducerPass::PrintLoopControl(SPIRVOperand *Op) {
5414 spv::LoopControlMask BIn = static_cast<spv::LoopControlMask>(Op->getNumID());
5415 out << getLoopControlName(BIn);
5416}
5417
5418void SPIRVProducerPass::PrintDimensionality(SPIRVOperand *Op) {
5419 spv::Dim DIM = static_cast<spv::Dim>(Op->getNumID());
5420 out << getDimName(DIM);
5421}
5422
5423void SPIRVProducerPass::PrintImageFormat(SPIRVOperand *Op) {
5424 spv::ImageFormat Format = static_cast<spv::ImageFormat>(Op->getNumID());
5425 out << getImageFormatName(Format);
5426}
5427
5428void SPIRVProducerPass::PrintMemoryAccess(SPIRVOperand *Op) {
5429 out << spv::getMemoryAccessName(
5430 static_cast<spv::MemoryAccessMask>(Op->getNumID()));
5431}
5432
5433void SPIRVProducerPass::PrintImageOperandsType(SPIRVOperand *Op) {
5434 auto LiteralNum = Op->getLiteralNum();
5435 spv::ImageOperandsMask Type =
5436 static_cast<spv::ImageOperandsMask>(LiteralNum[0]);
5437 out << getImageOperandsName(Type);
5438}
5439
5440void SPIRVProducerPass::WriteSPIRVAssembly() {
5441 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5442
5443 for (auto Inst : SPIRVInstList) {
5444 SPIRVOperandList Ops = Inst->getOperands();
5445 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5446
5447 switch (Opcode) {
5448 default: {
5449 llvm_unreachable("Unsupported SPIRV instruction");
5450 break;
5451 }
5452 case spv::OpCapability: {
5453 // Ops[0] = Capability
5454 PrintOpcode(Inst);
5455 out << " ";
5456 PrintCapability(Ops[0]);
5457 out << "\n";
5458 break;
5459 }
5460 case spv::OpMemoryModel: {
5461 // Ops[0] = Addressing Model
5462 // Ops[1] = Memory Model
5463 PrintOpcode(Inst);
5464 out << " ";
5465 PrintAddrModel(Ops[0]);
5466 out << " ";
5467 PrintMemModel(Ops[1]);
5468 out << "\n";
5469 break;
5470 }
5471 case spv::OpEntryPoint: {
5472 // Ops[0] = Execution Model
5473 // Ops[1] = EntryPoint ID
5474 // Ops[2] = Name (Literal String)
5475 // Ops[3] ... Ops[n] = Interface ID
5476 PrintOpcode(Inst);
5477 out << " ";
5478 PrintExecModel(Ops[0]);
5479 for (uint32_t i = 1; i < Ops.size(); i++) {
5480 out << " ";
5481 PrintOperand(Ops[i]);
5482 }
5483 out << "\n";
5484 break;
5485 }
5486 case spv::OpExecutionMode: {
5487 // Ops[0] = Entry Point ID
5488 // Ops[1] = Execution Mode
5489 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
5490 PrintOpcode(Inst);
5491 out << " ";
5492 PrintOperand(Ops[0]);
5493 out << " ";
5494 PrintExecMode(Ops[1]);
5495 for (uint32_t i = 2; i < Ops.size(); i++) {
5496 out << " ";
5497 PrintOperand(Ops[i]);
5498 }
5499 out << "\n";
5500 break;
5501 }
5502 case spv::OpSource: {
5503 // Ops[0] = SourceLanguage ID
5504 // Ops[1] = Version (LiteralNum)
5505 PrintOpcode(Inst);
5506 out << " ";
5507 PrintSourceLanguage(Ops[0]);
5508 out << " ";
5509 PrintOperand(Ops[1]);
5510 out << "\n";
5511 break;
5512 }
5513 case spv::OpDecorate: {
5514 // Ops[0] = Target ID
5515 // Ops[1] = Decoration (Block or BufferBlock)
5516 // Ops[2] ... Ops[n] = Optional literals according to Decoration
5517 PrintOpcode(Inst);
5518 out << " ";
5519 PrintOperand(Ops[0]);
5520 out << " ";
5521 PrintDecoration(Ops[1]);
5522 // Handle BuiltIn OpDecorate specially.
5523 if (Ops[1]->getNumID() == spv::DecorationBuiltIn) {
5524 out << " ";
5525 PrintBuiltIn(Ops[2]);
5526 } else {
5527 for (uint32_t i = 2; i < Ops.size(); i++) {
5528 out << " ";
5529 PrintOperand(Ops[i]);
5530 }
5531 }
5532 out << "\n";
5533 break;
5534 }
5535 case spv::OpMemberDecorate: {
5536 // Ops[0] = Structure Type ID
5537 // Ops[1] = Member Index(Literal Number)
5538 // Ops[2] = Decoration
5539 // Ops[3] ... Ops[n] = Optional literals according to Decoration
5540 PrintOpcode(Inst);
5541 out << " ";
5542 PrintOperand(Ops[0]);
5543 out << " ";
5544 PrintOperand(Ops[1]);
5545 out << " ";
5546 PrintDecoration(Ops[2]);
5547 for (uint32_t i = 3; i < Ops.size(); i++) {
5548 out << " ";
5549 PrintOperand(Ops[i]);
5550 }
5551 out << "\n";
5552 break;
5553 }
5554 case spv::OpTypePointer: {
5555 // Ops[0] = Storage Class
5556 // Ops[1] = Element Type ID
5557 PrintResID(Inst);
5558 out << " = ";
5559 PrintOpcode(Inst);
5560 out << " ";
5561 PrintStorageClass(Ops[0]);
5562 out << " ";
5563 PrintOperand(Ops[1]);
5564 out << "\n";
5565 break;
5566 }
5567 case spv::OpTypeImage: {
5568 // Ops[0] = Sampled Type ID
5569 // Ops[1] = Dim ID
5570 // Ops[2] = Depth (Literal Number)
5571 // Ops[3] = Arrayed (Literal Number)
5572 // Ops[4] = MS (Literal Number)
5573 // Ops[5] = Sampled (Literal Number)
5574 // Ops[6] = Image Format ID
5575 PrintResID(Inst);
5576 out << " = ";
5577 PrintOpcode(Inst);
5578 out << " ";
5579 PrintOperand(Ops[0]);
5580 out << " ";
5581 PrintDimensionality(Ops[1]);
5582 out << " ";
5583 PrintOperand(Ops[2]);
5584 out << " ";
5585 PrintOperand(Ops[3]);
5586 out << " ";
5587 PrintOperand(Ops[4]);
5588 out << " ";
5589 PrintOperand(Ops[5]);
5590 out << " ";
5591 PrintImageFormat(Ops[6]);
5592 out << "\n";
5593 break;
5594 }
5595 case spv::OpFunction: {
5596 // Ops[0] : Result Type ID
5597 // Ops[1] : Function Control
5598 // Ops[2] : Function Type ID
5599 PrintResID(Inst);
5600 out << " = ";
5601 PrintOpcode(Inst);
5602 out << " ";
5603 PrintOperand(Ops[0]);
5604 out << " ";
5605 PrintFuncCtrl(Ops[1]);
5606 out << " ";
5607 PrintOperand(Ops[2]);
5608 out << "\n";
5609 break;
5610 }
5611 case spv::OpSelectionMerge: {
5612 // Ops[0] = Merge Block ID
5613 // Ops[1] = Selection Control
5614 PrintOpcode(Inst);
5615 out << " ";
5616 PrintOperand(Ops[0]);
5617 out << " ";
5618 PrintSelectionControl(Ops[1]);
5619 out << "\n";
5620 break;
5621 }
5622 case spv::OpLoopMerge: {
5623 // Ops[0] = Merge Block ID
5624 // Ops[1] = Continue Target ID
5625 // Ops[2] = Selection Control
5626 PrintOpcode(Inst);
5627 out << " ";
5628 PrintOperand(Ops[0]);
5629 out << " ";
5630 PrintOperand(Ops[1]);
5631 out << " ";
5632 PrintLoopControl(Ops[2]);
5633 out << "\n";
5634 break;
5635 }
5636 case spv::OpImageSampleExplicitLod: {
5637 // Ops[0] = Result Type ID
5638 // Ops[1] = Sampled Image ID
5639 // Ops[2] = Coordinate ID
5640 // Ops[3] = Image Operands Type ID
5641 // Ops[4] ... Ops[n] = Operands ID
5642 PrintResID(Inst);
5643 out << " = ";
5644 PrintOpcode(Inst);
5645 for (uint32_t i = 0; i < 3; i++) {
5646 out << " ";
5647 PrintOperand(Ops[i]);
5648 }
5649 out << " ";
5650 PrintImageOperandsType(Ops[3]);
5651 for (uint32_t i = 4; i < Ops.size(); i++) {
5652 out << " ";
5653 PrintOperand(Ops[i]);
5654 }
5655 out << "\n";
5656 break;
5657 }
5658 case spv::OpVariable: {
5659 // Ops[0] : Result Type ID
5660 // Ops[1] : Storage Class
5661 // Ops[2] ... Ops[n] = Initializer IDs
5662 PrintResID(Inst);
5663 out << " = ";
5664 PrintOpcode(Inst);
5665 out << " ";
5666 PrintOperand(Ops[0]);
5667 out << " ";
5668 PrintStorageClass(Ops[1]);
5669 for (uint32_t i = 2; i < Ops.size(); i++) {
5670 out << " ";
5671 PrintOperand(Ops[i]);
5672 }
5673 out << "\n";
5674 break;
5675 }
5676 case spv::OpExtInst: {
5677 // Ops[0] = Result Type ID
5678 // Ops[1] = Set ID (OpExtInstImport ID)
5679 // Ops[2] = Instruction Number (Literal Number)
5680 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5681 PrintResID(Inst);
5682 out << " = ";
5683 PrintOpcode(Inst);
5684 out << " ";
5685 PrintOperand(Ops[0]);
5686 out << " ";
5687 PrintOperand(Ops[1]);
5688 out << " ";
5689 PrintExtInst(Ops[2]);
5690 for (uint32_t i = 3; i < Ops.size(); i++) {
5691 out << " ";
5692 PrintOperand(Ops[i]);
5693 }
5694 out << "\n";
5695 break;
5696 }
5697 case spv::OpCopyMemory: {
5698 // Ops[0] = Addressing Model
5699 // Ops[1] = Memory Model
5700 PrintOpcode(Inst);
5701 out << " ";
5702 PrintOperand(Ops[0]);
5703 out << " ";
5704 PrintOperand(Ops[1]);
5705 out << " ";
5706 PrintMemoryAccess(Ops[2]);
5707 out << " ";
5708 PrintOperand(Ops[3]);
5709 out << "\n";
5710 break;
5711 }
5712 case spv::OpExtension:
5713 case spv::OpControlBarrier:
5714 case spv::OpMemoryBarrier:
5715 case spv::OpBranch:
5716 case spv::OpBranchConditional:
5717 case spv::OpStore:
5718 case spv::OpImageWrite:
5719 case spv::OpReturnValue:
5720 case spv::OpReturn:
5721 case spv::OpFunctionEnd: {
5722 PrintOpcode(Inst);
5723 for (uint32_t i = 0; i < Ops.size(); i++) {
5724 out << " ";
5725 PrintOperand(Ops[i]);
5726 }
5727 out << "\n";
5728 break;
5729 }
5730 case spv::OpExtInstImport:
5731 case spv::OpTypeRuntimeArray:
5732 case spv::OpTypeStruct:
5733 case spv::OpTypeSampler:
5734 case spv::OpTypeSampledImage:
5735 case spv::OpTypeInt:
5736 case spv::OpTypeFloat:
5737 case spv::OpTypeArray:
5738 case spv::OpTypeVector:
5739 case spv::OpTypeBool:
5740 case spv::OpTypeVoid:
5741 case spv::OpTypeFunction:
5742 case spv::OpFunctionParameter:
5743 case spv::OpLabel:
5744 case spv::OpPhi:
5745 case spv::OpLoad:
5746 case spv::OpSelect:
5747 case spv::OpAccessChain:
5748 case spv::OpPtrAccessChain:
5749 case spv::OpInBoundsAccessChain:
5750 case spv::OpUConvert:
5751 case spv::OpSConvert:
5752 case spv::OpConvertFToU:
5753 case spv::OpConvertFToS:
5754 case spv::OpConvertUToF:
5755 case spv::OpConvertSToF:
5756 case spv::OpFConvert:
5757 case spv::OpConvertPtrToU:
5758 case spv::OpConvertUToPtr:
5759 case spv::OpBitcast:
5760 case spv::OpIAdd:
5761 case spv::OpFAdd:
5762 case spv::OpISub:
5763 case spv::OpFSub:
5764 case spv::OpIMul:
5765 case spv::OpFMul:
5766 case spv::OpUDiv:
5767 case spv::OpSDiv:
5768 case spv::OpFDiv:
5769 case spv::OpUMod:
5770 case spv::OpSRem:
5771 case spv::OpFRem:
5772 case spv::OpBitwiseOr:
5773 case spv::OpBitwiseXor:
5774 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005775 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005776 case spv::OpShiftLeftLogical:
5777 case spv::OpShiftRightLogical:
5778 case spv::OpShiftRightArithmetic:
5779 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04005780 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04005781 case spv::OpCompositeExtract:
5782 case spv::OpVectorExtractDynamic:
5783 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04005784 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04005785 case spv::OpVectorInsertDynamic:
5786 case spv::OpVectorShuffle:
5787 case spv::OpIEqual:
5788 case spv::OpINotEqual:
5789 case spv::OpUGreaterThan:
5790 case spv::OpUGreaterThanEqual:
5791 case spv::OpULessThan:
5792 case spv::OpULessThanEqual:
5793 case spv::OpSGreaterThan:
5794 case spv::OpSGreaterThanEqual:
5795 case spv::OpSLessThan:
5796 case spv::OpSLessThanEqual:
5797 case spv::OpFOrdEqual:
5798 case spv::OpFOrdGreaterThan:
5799 case spv::OpFOrdGreaterThanEqual:
5800 case spv::OpFOrdLessThan:
5801 case spv::OpFOrdLessThanEqual:
5802 case spv::OpFOrdNotEqual:
5803 case spv::OpFUnordEqual:
5804 case spv::OpFUnordGreaterThan:
5805 case spv::OpFUnordGreaterThanEqual:
5806 case spv::OpFUnordLessThan:
5807 case spv::OpFUnordLessThanEqual:
5808 case spv::OpFUnordNotEqual:
5809 case spv::OpSampledImage:
5810 case spv::OpFunctionCall:
5811 case spv::OpConstantTrue:
5812 case spv::OpConstantFalse:
5813 case spv::OpConstant:
5814 case spv::OpSpecConstant:
5815 case spv::OpConstantComposite:
5816 case spv::OpSpecConstantComposite:
5817 case spv::OpConstantNull:
5818 case spv::OpLogicalOr:
5819 case spv::OpLogicalAnd:
5820 case spv::OpLogicalNot:
5821 case spv::OpLogicalNotEqual:
5822 case spv::OpUndef:
5823 case spv::OpIsInf:
5824 case spv::OpIsNan:
5825 case spv::OpAny:
5826 case spv::OpAll:
David Neto5c22a252018-03-15 16:07:41 -04005827 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04005828 case spv::OpAtomicIAdd:
5829 case spv::OpAtomicISub:
5830 case spv::OpAtomicExchange:
5831 case spv::OpAtomicIIncrement:
5832 case spv::OpAtomicIDecrement:
5833 case spv::OpAtomicCompareExchange:
5834 case spv::OpAtomicUMin:
5835 case spv::OpAtomicSMin:
5836 case spv::OpAtomicUMax:
5837 case spv::OpAtomicSMax:
5838 case spv::OpAtomicAnd:
5839 case spv::OpAtomicOr:
5840 case spv::OpAtomicXor:
5841 case spv::OpDot: {
5842 PrintResID(Inst);
5843 out << " = ";
5844 PrintOpcode(Inst);
5845 for (uint32_t i = 0; i < Ops.size(); i++) {
5846 out << " ";
5847 PrintOperand(Ops[i]);
5848 }
5849 out << "\n";
5850 break;
5851 }
5852 }
5853 }
5854}
5855
5856void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04005857 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04005858}
5859
5860void SPIRVProducerPass::WriteResultID(SPIRVInstruction *Inst) {
5861 WriteOneWord(Inst->getResultID());
5862}
5863
5864void SPIRVProducerPass::WriteWordCountAndOpcode(SPIRVInstruction *Inst) {
5865 // High 16 bit : Word Count
5866 // Low 16 bit : Opcode
5867 uint32_t Word = Inst->getOpcode();
5868 Word |= Inst->getWordCount() << 16;
5869 WriteOneWord(Word);
5870}
5871
5872void SPIRVProducerPass::WriteOperand(SPIRVOperand *Op) {
5873 SPIRVOperandType OpTy = Op->getType();
5874 switch (OpTy) {
5875 default: {
5876 llvm_unreachable("Unsupported SPIRV Operand Type???");
5877 break;
5878 }
5879 case SPIRVOperandType::NUMBERID: {
5880 WriteOneWord(Op->getNumID());
5881 break;
5882 }
5883 case SPIRVOperandType::LITERAL_STRING: {
5884 std::string Str = Op->getLiteralStr();
5885 const char *Data = Str.c_str();
5886 size_t WordSize = Str.size() / 4;
5887 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
5888 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
5889 }
5890
5891 uint32_t Remainder = Str.size() % 4;
5892 uint32_t LastWord = 0;
5893 if (Remainder) {
5894 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
5895 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
5896 }
5897 }
5898
5899 WriteOneWord(LastWord);
5900 break;
5901 }
5902 case SPIRVOperandType::LITERAL_INTEGER:
5903 case SPIRVOperandType::LITERAL_FLOAT: {
5904 auto LiteralNum = Op->getLiteralNum();
5905 // TODO: Handle LiteranNum carefully.
5906 for (auto Word : LiteralNum) {
5907 WriteOneWord(Word);
5908 }
5909 break;
5910 }
5911 }
5912}
5913
5914void SPIRVProducerPass::WriteSPIRVBinary() {
5915 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5916
5917 for (auto Inst : SPIRVInstList) {
David Netoc6f3ab22018-04-06 18:02:31 -04005918 SPIRVOperandList Ops{Inst->getOperands()};
David Neto22f144c2017-06-12 14:26:21 -04005919 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5920
5921 switch (Opcode) {
5922 default: {
David Neto5c22a252018-03-15 16:07:41 -04005923 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04005924 llvm_unreachable("Unsupported SPIRV instruction");
5925 break;
5926 }
5927 case spv::OpCapability:
5928 case spv::OpExtension:
5929 case spv::OpMemoryModel:
5930 case spv::OpEntryPoint:
5931 case spv::OpExecutionMode:
5932 case spv::OpSource:
5933 case spv::OpDecorate:
5934 case spv::OpMemberDecorate:
5935 case spv::OpBranch:
5936 case spv::OpBranchConditional:
5937 case spv::OpSelectionMerge:
5938 case spv::OpLoopMerge:
5939 case spv::OpStore:
5940 case spv::OpImageWrite:
5941 case spv::OpReturnValue:
5942 case spv::OpControlBarrier:
5943 case spv::OpMemoryBarrier:
5944 case spv::OpReturn:
5945 case spv::OpFunctionEnd:
5946 case spv::OpCopyMemory: {
5947 WriteWordCountAndOpcode(Inst);
5948 for (uint32_t i = 0; i < Ops.size(); i++) {
5949 WriteOperand(Ops[i]);
5950 }
5951 break;
5952 }
5953 case spv::OpTypeBool:
5954 case spv::OpTypeVoid:
5955 case spv::OpTypeSampler:
5956 case spv::OpLabel:
5957 case spv::OpExtInstImport:
5958 case spv::OpTypePointer:
5959 case spv::OpTypeRuntimeArray:
5960 case spv::OpTypeStruct:
5961 case spv::OpTypeImage:
5962 case spv::OpTypeSampledImage:
5963 case spv::OpTypeInt:
5964 case spv::OpTypeFloat:
5965 case spv::OpTypeArray:
5966 case spv::OpTypeVector:
5967 case spv::OpTypeFunction: {
5968 WriteWordCountAndOpcode(Inst);
5969 WriteResultID(Inst);
5970 for (uint32_t i = 0; i < Ops.size(); i++) {
5971 WriteOperand(Ops[i]);
5972 }
5973 break;
5974 }
5975 case spv::OpFunction:
5976 case spv::OpFunctionParameter:
5977 case spv::OpAccessChain:
5978 case spv::OpPtrAccessChain:
5979 case spv::OpInBoundsAccessChain:
5980 case spv::OpUConvert:
5981 case spv::OpSConvert:
5982 case spv::OpConvertFToU:
5983 case spv::OpConvertFToS:
5984 case spv::OpConvertUToF:
5985 case spv::OpConvertSToF:
5986 case spv::OpFConvert:
5987 case spv::OpConvertPtrToU:
5988 case spv::OpConvertUToPtr:
5989 case spv::OpBitcast:
5990 case spv::OpIAdd:
5991 case spv::OpFAdd:
5992 case spv::OpISub:
5993 case spv::OpFSub:
5994 case spv::OpIMul:
5995 case spv::OpFMul:
5996 case spv::OpUDiv:
5997 case spv::OpSDiv:
5998 case spv::OpFDiv:
5999 case spv::OpUMod:
6000 case spv::OpSRem:
6001 case spv::OpFRem:
6002 case spv::OpBitwiseOr:
6003 case spv::OpBitwiseXor:
6004 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04006005 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04006006 case spv::OpShiftLeftLogical:
6007 case spv::OpShiftRightLogical:
6008 case spv::OpShiftRightArithmetic:
6009 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04006010 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04006011 case spv::OpCompositeExtract:
6012 case spv::OpVectorExtractDynamic:
6013 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04006014 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04006015 case spv::OpVectorInsertDynamic:
6016 case spv::OpVectorShuffle:
6017 case spv::OpIEqual:
6018 case spv::OpINotEqual:
6019 case spv::OpUGreaterThan:
6020 case spv::OpUGreaterThanEqual:
6021 case spv::OpULessThan:
6022 case spv::OpULessThanEqual:
6023 case spv::OpSGreaterThan:
6024 case spv::OpSGreaterThanEqual:
6025 case spv::OpSLessThan:
6026 case spv::OpSLessThanEqual:
6027 case spv::OpFOrdEqual:
6028 case spv::OpFOrdGreaterThan:
6029 case spv::OpFOrdGreaterThanEqual:
6030 case spv::OpFOrdLessThan:
6031 case spv::OpFOrdLessThanEqual:
6032 case spv::OpFOrdNotEqual:
6033 case spv::OpFUnordEqual:
6034 case spv::OpFUnordGreaterThan:
6035 case spv::OpFUnordGreaterThanEqual:
6036 case spv::OpFUnordLessThan:
6037 case spv::OpFUnordLessThanEqual:
6038 case spv::OpFUnordNotEqual:
6039 case spv::OpExtInst:
6040 case spv::OpIsInf:
6041 case spv::OpIsNan:
6042 case spv::OpAny:
6043 case spv::OpAll:
6044 case spv::OpUndef:
6045 case spv::OpConstantNull:
6046 case spv::OpLogicalOr:
6047 case spv::OpLogicalAnd:
6048 case spv::OpLogicalNot:
6049 case spv::OpLogicalNotEqual:
6050 case spv::OpConstantComposite:
6051 case spv::OpSpecConstantComposite:
6052 case spv::OpConstantTrue:
6053 case spv::OpConstantFalse:
6054 case spv::OpConstant:
6055 case spv::OpSpecConstant:
6056 case spv::OpVariable:
6057 case spv::OpFunctionCall:
6058 case spv::OpSampledImage:
6059 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04006060 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04006061 case spv::OpSelect:
6062 case spv::OpPhi:
6063 case spv::OpLoad:
6064 case spv::OpAtomicIAdd:
6065 case spv::OpAtomicISub:
6066 case spv::OpAtomicExchange:
6067 case spv::OpAtomicIIncrement:
6068 case spv::OpAtomicIDecrement:
6069 case spv::OpAtomicCompareExchange:
6070 case spv::OpAtomicUMin:
6071 case spv::OpAtomicSMin:
6072 case spv::OpAtomicUMax:
6073 case spv::OpAtomicSMax:
6074 case spv::OpAtomicAnd:
6075 case spv::OpAtomicOr:
6076 case spv::OpAtomicXor:
6077 case spv::OpDot: {
6078 WriteWordCountAndOpcode(Inst);
6079 WriteOperand(Ops[0]);
6080 WriteResultID(Inst);
6081 for (uint32_t i = 1; i < Ops.size(); i++) {
6082 WriteOperand(Ops[i]);
6083 }
6084 break;
6085 }
6086 }
6087 }
6088}