blob: 4bdb8ce6ffbf8252d0ac06bc90c575c038e110b3 [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
3981 // Ops[0] = Result Type ID
3982 // Ops[1] = Object ID
3983 // Ops[2] = Composite ID
3984 // Ops[3] ... Ops[n] = Indexes (Literal Number)
3985 SPIRVOperandList Ops;
3986
David Neto257c3892018-04-11 13:19:45 -04003987 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(1)])
3988 << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003989
3990 spv::Op Opcode = spv::OpCompositeInsert;
3991 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04003992 const auto value = CI->getZExtValue();
3993 assert(value <= UINT32_MAX);
3994 Ops << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04003995 } else {
David Neto257c3892018-04-11 13:19:45 -04003996 Ops << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003997 Opcode = spv::OpVectorInsertDynamic;
3998 }
3999
David Neto87846742018-04-11 17:36:22 -04004000 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004001 SPIRVInstList.push_back(Inst);
4002 break;
4003 }
4004 case Instruction::ShuffleVector: {
4005 // Ops[0] = Result Type ID
4006 // Ops[1] = Vector 1 ID
4007 // Ops[2] = Vector 2 ID
4008 // Ops[3] ... Ops[n] = Components (Literal Number)
4009 SPIRVOperandList Ops;
4010
David Neto257c3892018-04-11 13:19:45 -04004011 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4012 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004013
4014 uint64_t NumElements = 0;
4015 if (Constant *Cst = dyn_cast<Constant>(I.getOperand(2))) {
4016 NumElements = cast<VectorType>(Cst->getType())->getNumElements();
4017
4018 if (Cst->isNullValue()) {
4019 for (unsigned i = 0; i < NumElements; i++) {
David Neto257c3892018-04-11 13:19:45 -04004020 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04004021 }
4022 } else if (const ConstantDataSequential *CDS =
4023 dyn_cast<ConstantDataSequential>(Cst)) {
4024 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
4025 std::vector<uint32_t> LiteralNum;
David Neto257c3892018-04-11 13:19:45 -04004026 const auto value = CDS->getElementAsInteger(i);
4027 assert(value <= UINT32_MAX);
4028 Ops << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004029 }
4030 } else if (const ConstantVector *CV = dyn_cast<ConstantVector>(Cst)) {
4031 for (unsigned i = 0; i < CV->getNumOperands(); i++) {
4032 auto Op = CV->getOperand(i);
4033
4034 uint32_t literal = 0;
4035
4036 if (auto CI = dyn_cast<ConstantInt>(Op)) {
4037 literal = static_cast<uint32_t>(CI->getZExtValue());
4038 } else if (auto UI = dyn_cast<UndefValue>(Op)) {
4039 literal = 0xFFFFFFFFu;
4040 } else {
4041 Op->print(errs());
4042 llvm_unreachable("Unsupported element in ConstantVector!");
4043 }
4044
David Neto257c3892018-04-11 13:19:45 -04004045 Ops << MkNum(literal);
David Neto22f144c2017-06-12 14:26:21 -04004046 }
4047 } else {
4048 Cst->print(errs());
4049 llvm_unreachable("Unsupported constant mask in ShuffleVector!");
4050 }
4051 }
4052
David Neto87846742018-04-11 17:36:22 -04004053 auto *Inst = new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004054 SPIRVInstList.push_back(Inst);
4055 break;
4056 }
4057 case Instruction::ICmp:
4058 case Instruction::FCmp: {
4059 CmpInst *CmpI = cast<CmpInst>(&I);
4060
David Netod4ca2e62017-07-06 18:47:35 -04004061 // Pointer equality is invalid.
4062 Type* ArgTy = CmpI->getOperand(0)->getType();
4063 if (isa<PointerType>(ArgTy)) {
4064 CmpI->print(errs());
4065 std::string name = I.getParent()->getParent()->getName();
4066 errs()
4067 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4068 << "in function " << name << "\n";
4069 llvm_unreachable("Pointer equality check is invalid");
4070 break;
4071 }
4072
David Neto257c3892018-04-11 13:19:45 -04004073 // Ops[0] = Result Type ID
4074 // Ops[1] = Operand 1 ID
4075 // Ops[2] = Operand 2 ID
4076 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004077
David Neto257c3892018-04-11 13:19:45 -04004078 Ops << MkId(lookupType(CmpI->getType())) << MkId(VMap[CmpI->getOperand(0)])
4079 << MkId(VMap[CmpI->getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004080
4081 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
David Neto87846742018-04-11 17:36:22 -04004082 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004083 SPIRVInstList.push_back(Inst);
4084 break;
4085 }
4086 case Instruction::Br: {
4087 // Branch instrucion is deferred because it needs label's ID. Record slot's
4088 // location on SPIRVInstructionList.
4089 DeferredInsts.push_back(
4090 std::make_tuple(&I, --SPIRVInstList.end(), 0 /* No id */));
4091 break;
4092 }
4093 case Instruction::Switch: {
4094 I.print(errs());
4095 llvm_unreachable("Unsupported instruction???");
4096 break;
4097 }
4098 case Instruction::IndirectBr: {
4099 I.print(errs());
4100 llvm_unreachable("Unsupported instruction???");
4101 break;
4102 }
4103 case Instruction::PHI: {
4104 // Branch instrucion is deferred because it needs label's ID. Record slot's
4105 // location on SPIRVInstructionList.
4106 DeferredInsts.push_back(
4107 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4108 break;
4109 }
4110 case Instruction::Alloca: {
4111 //
4112 // Generate OpVariable.
4113 //
4114 // Ops[0] : Result Type ID
4115 // Ops[1] : Storage Class
4116 SPIRVOperandList Ops;
4117
David Neto257c3892018-04-11 13:19:45 -04004118 Ops << MkId(lookupType(I.getType())) << MkNum(spv::StorageClassFunction);
David Neto22f144c2017-06-12 14:26:21 -04004119
David Neto87846742018-04-11 17:36:22 -04004120 auto *Inst = new SPIRVInstruction(spv::OpVariable, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004121 SPIRVInstList.push_back(Inst);
4122 break;
4123 }
4124 case Instruction::Load: {
4125 LoadInst *LD = cast<LoadInst>(&I);
4126 //
4127 // Generate OpLoad.
4128 //
4129
David Neto0a2f98d2017-09-15 19:38:40 -04004130 uint32_t ResTyID = lookupType(LD->getType());
David Netoa60b00b2017-09-15 16:34:09 -04004131 uint32_t PointerID = VMap[LD->getPointerOperand()];
4132
4133 // This is a hack to work around what looks like a driver bug.
4134 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004135 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4136 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004137 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004138 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004139 // Generate a bitwise-and of the original value with itself.
4140 // We should have been able to get away with just an OpCopyObject,
4141 // but we need something more complex to get past certain driver bugs.
4142 // This is ridiculous, but necessary.
4143 // TODO(dneto): Revisit this once drivers fix their bugs.
4144
4145 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004146 Ops << MkId(ResTyID) << MkId(WorkgroupSizeValueID)
4147 << MkId(WorkgroupSizeValueID);
David Neto0a2f98d2017-09-15 19:38:40 -04004148
David Neto87846742018-04-11 17:36:22 -04004149 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto0a2f98d2017-09-15 19:38:40 -04004150 SPIRVInstList.push_back(Inst);
David Netoa60b00b2017-09-15 16:34:09 -04004151 break;
4152 }
4153
4154 // This is the normal path. Generate a load.
4155
David Neto22f144c2017-06-12 14:26:21 -04004156 // Ops[0] = Result Type ID
4157 // Ops[1] = Pointer ID
4158 // Ops[2] ... Ops[n] = Optional Memory Access
4159 //
4160 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004161
David Neto22f144c2017-06-12 14:26:21 -04004162 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004163 Ops << MkId(ResTyID) << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04004164
David Neto87846742018-04-11 17:36:22 -04004165 auto *Inst = new SPIRVInstruction(spv::OpLoad, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004166 SPIRVInstList.push_back(Inst);
4167 break;
4168 }
4169 case Instruction::Store: {
4170 StoreInst *ST = cast<StoreInst>(&I);
4171 //
4172 // Generate OpStore.
4173 //
4174
4175 // Ops[0] = Pointer ID
4176 // Ops[1] = Object ID
4177 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4178 //
4179 // TODO: Do we need to implement Optional Memory Access???
David Neto257c3892018-04-11 13:19:45 -04004180 SPIRVOperandList Ops;
4181 Ops << MkId(VMap[ST->getPointerOperand()])
4182 << MkId(VMap[ST->getValueOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004183
David Neto87846742018-04-11 17:36:22 -04004184 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004185 SPIRVInstList.push_back(Inst);
4186 break;
4187 }
4188 case Instruction::AtomicCmpXchg: {
4189 I.print(errs());
4190 llvm_unreachable("Unsupported instruction???");
4191 break;
4192 }
4193 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004194 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4195
4196 spv::Op opcode;
4197
4198 switch (AtomicRMW->getOperation()) {
4199 default:
4200 I.print(errs());
4201 llvm_unreachable("Unsupported instruction???");
4202 case llvm::AtomicRMWInst::Add:
4203 opcode = spv::OpAtomicIAdd;
4204 break;
4205 case llvm::AtomicRMWInst::Sub:
4206 opcode = spv::OpAtomicISub;
4207 break;
4208 case llvm::AtomicRMWInst::Xchg:
4209 opcode = spv::OpAtomicExchange;
4210 break;
4211 case llvm::AtomicRMWInst::Min:
4212 opcode = spv::OpAtomicSMin;
4213 break;
4214 case llvm::AtomicRMWInst::Max:
4215 opcode = spv::OpAtomicSMax;
4216 break;
4217 case llvm::AtomicRMWInst::UMin:
4218 opcode = spv::OpAtomicUMin;
4219 break;
4220 case llvm::AtomicRMWInst::UMax:
4221 opcode = spv::OpAtomicUMax;
4222 break;
4223 case llvm::AtomicRMWInst::And:
4224 opcode = spv::OpAtomicAnd;
4225 break;
4226 case llvm::AtomicRMWInst::Or:
4227 opcode = spv::OpAtomicOr;
4228 break;
4229 case llvm::AtomicRMWInst::Xor:
4230 opcode = spv::OpAtomicXor;
4231 break;
4232 }
4233
4234 //
4235 // Generate OpAtomic*.
4236 //
4237 SPIRVOperandList Ops;
4238
David Neto257c3892018-04-11 13:19:45 -04004239 Ops << MkId(lookupType(I.getType()))
4240 << MkId(VMap[AtomicRMW->getPointerOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004241
4242 auto IntTy = Type::getInt32Ty(I.getContext());
Neil Henning39672102017-09-29 14:33:13 +01004243 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
David Neto257c3892018-04-11 13:19:45 -04004244 Ops << MkId(VMap[ConstantScopeDevice]);
Neil Henning39672102017-09-29 14:33:13 +01004245
4246 const auto ConstantMemorySemantics = ConstantInt::get(
4247 IntTy, spv::MemorySemanticsUniformMemoryMask |
4248 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto257c3892018-04-11 13:19:45 -04004249 Ops << MkId(VMap[ConstantMemorySemantics]);
Neil Henning39672102017-09-29 14:33:13 +01004250
David Neto257c3892018-04-11 13:19:45 -04004251 Ops << MkId(VMap[AtomicRMW->getValOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004252
4253 VMap[&I] = nextID;
4254
David Neto87846742018-04-11 17:36:22 -04004255 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
Neil Henning39672102017-09-29 14:33:13 +01004256 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004257 break;
4258 }
4259 case Instruction::Fence: {
4260 I.print(errs());
4261 llvm_unreachable("Unsupported instruction???");
4262 break;
4263 }
4264 case Instruction::Call: {
4265 CallInst *Call = dyn_cast<CallInst>(&I);
4266 Function *Callee = Call->getCalledFunction();
4267
4268 // Sampler initializers become a load of the corresponding sampler.
4269 if (Callee->getName().equals("__translate_sampler_initializer")) {
4270 // Check that the sampler map was definitely used though.
4271 if (0 == getSamplerMap().size()) {
4272 llvm_unreachable("Sampler literal in source without sampler map!");
4273 }
4274
4275 SPIRVOperandList Ops;
4276
David Neto257c3892018-04-11 13:19:45 -04004277 Ops << MkId(lookupType(SamplerTy->getPointerElementType()))
4278 << MkId(VMap[Call]);
David Neto22f144c2017-06-12 14:26:21 -04004279
4280 VMap[Call] = nextID;
David Neto87846742018-04-11 17:36:22 -04004281 auto *Inst = new SPIRVInstruction(spv::OpLoad, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004282 SPIRVInstList.push_back(Inst);
4283
4284 break;
4285 }
4286
4287 if (Callee->getName().startswith("spirv.atomic")) {
4288 spv::Op opcode = StringSwitch<spv::Op>(Callee->getName())
4289 .Case("spirv.atomic_add", spv::OpAtomicIAdd)
4290 .Case("spirv.atomic_sub", spv::OpAtomicISub)
4291 .Case("spirv.atomic_exchange", spv::OpAtomicExchange)
4292 .Case("spirv.atomic_inc", spv::OpAtomicIIncrement)
4293 .Case("spirv.atomic_dec", spv::OpAtomicIDecrement)
4294 .Case("spirv.atomic_compare_exchange",
4295 spv::OpAtomicCompareExchange)
4296 .Case("spirv.atomic_umin", spv::OpAtomicUMin)
4297 .Case("spirv.atomic_smin", spv::OpAtomicSMin)
4298 .Case("spirv.atomic_umax", spv::OpAtomicUMax)
4299 .Case("spirv.atomic_smax", spv::OpAtomicSMax)
4300 .Case("spirv.atomic_and", spv::OpAtomicAnd)
4301 .Case("spirv.atomic_or", spv::OpAtomicOr)
4302 .Case("spirv.atomic_xor", spv::OpAtomicXor)
4303 .Default(spv::OpNop);
4304
4305 //
4306 // Generate OpAtomic*.
4307 //
4308 SPIRVOperandList Ops;
4309
David Neto257c3892018-04-11 13:19:45 -04004310 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004311
4312 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004313 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004314 }
4315
4316 VMap[&I] = nextID;
4317
David Neto87846742018-04-11 17:36:22 -04004318 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004319 SPIRVInstList.push_back(Inst);
4320 break;
4321 }
4322
4323 if (Callee->getName().startswith("_Z3dot")) {
4324 // If the argument is a vector type, generate OpDot
4325 if (Call->getArgOperand(0)->getType()->isVectorTy()) {
4326 //
4327 // Generate OpDot.
4328 //
4329 SPIRVOperandList Ops;
4330
David Neto257c3892018-04-11 13:19:45 -04004331 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004332
4333 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004334 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004335 }
4336
4337 VMap[&I] = nextID;
4338
David Neto87846742018-04-11 17:36:22 -04004339 auto *Inst = new SPIRVInstruction(spv::OpDot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004340 SPIRVInstList.push_back(Inst);
4341 } else {
4342 //
4343 // Generate OpFMul.
4344 //
4345 SPIRVOperandList Ops;
4346
David Neto257c3892018-04-11 13:19:45 -04004347 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004348
4349 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004350 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004351 }
4352
4353 VMap[&I] = nextID;
4354
David Neto87846742018-04-11 17:36:22 -04004355 auto *Inst = new SPIRVInstruction(spv::OpFMul, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004356 SPIRVInstList.push_back(Inst);
4357 }
4358 break;
4359 }
4360
David Neto8505ebf2017-10-13 18:50:50 -04004361 if (Callee->getName().startswith("_Z4fmod")) {
4362 // OpenCL fmod(x,y) is x - y * trunc(x/y)
4363 // The sign for a non-zero result is taken from x.
4364 // (Try an example.)
4365 // So translate to OpFRem
4366
4367 SPIRVOperandList Ops;
4368
David Neto257c3892018-04-11 13:19:45 -04004369 Ops << MkId(lookupType(I.getType()));
David Neto8505ebf2017-10-13 18:50:50 -04004370
4371 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004372 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto8505ebf2017-10-13 18:50:50 -04004373 }
4374
4375 VMap[&I] = nextID;
4376
David Neto87846742018-04-11 17:36:22 -04004377 auto *Inst = new SPIRVInstruction(spv::OpFRem, nextID++, Ops);
David Neto8505ebf2017-10-13 18:50:50 -04004378 SPIRVInstList.push_back(Inst);
4379 break;
4380 }
4381
David Neto22f144c2017-06-12 14:26:21 -04004382 // spirv.store_null.* intrinsics become OpStore's.
4383 if (Callee->getName().startswith("spirv.store_null")) {
4384 //
4385 // Generate OpStore.
4386 //
4387
4388 // Ops[0] = Pointer ID
4389 // Ops[1] = Object ID
4390 // Ops[2] ... Ops[n]
4391 SPIRVOperandList Ops;
4392
4393 uint32_t PointerID = VMap[Call->getArgOperand(0)];
David Neto22f144c2017-06-12 14:26:21 -04004394 uint32_t ObjectID = VMap[Call->getArgOperand(1)];
David Neto257c3892018-04-11 13:19:45 -04004395 Ops << MkId(PointerID) << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04004396
David Neto87846742018-04-11 17:36:22 -04004397 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpStore, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004398
4399 break;
4400 }
4401
4402 // spirv.copy_memory.* intrinsics become OpMemoryMemory's.
4403 if (Callee->getName().startswith("spirv.copy_memory")) {
4404 //
4405 // Generate OpCopyMemory.
4406 //
4407
4408 // Ops[0] = Dst ID
4409 // Ops[1] = Src ID
4410 // Ops[2] = Memory Access
4411 // Ops[3] = Alignment
4412
4413 auto IsVolatile =
4414 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
4415
4416 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
4417 : spv::MemoryAccessMaskNone;
4418
4419 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
4420
4421 auto Alignment =
4422 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4423
David Neto257c3892018-04-11 13:19:45 -04004424 SPIRVOperandList Ops;
4425 Ops << MkId(VMap[Call->getArgOperand(0)])
4426 << MkId(VMap[Call->getArgOperand(1)]) << MkNum(MemoryAccess)
4427 << MkNum(static_cast<uint32_t>(Alignment));
David Neto22f144c2017-06-12 14:26:21 -04004428
David Neto87846742018-04-11 17:36:22 -04004429 auto *Inst = new SPIRVInstruction(spv::OpCopyMemory, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004430
4431 SPIRVInstList.push_back(Inst);
4432
4433 break;
4434 }
4435
4436 // Nothing to do for abs with uint. Map abs's operand ID to VMap for abs
4437 // with unit.
4438 if (Callee->getName().equals("_Z3absj") ||
4439 Callee->getName().equals("_Z3absDv2_j") ||
4440 Callee->getName().equals("_Z3absDv3_j") ||
4441 Callee->getName().equals("_Z3absDv4_j")) {
4442 VMap[&I] = VMap[Call->getOperand(0)];
4443 break;
4444 }
4445
4446 // barrier is converted to OpControlBarrier
4447 if (Callee->getName().equals("__spirv_control_barrier")) {
4448 //
4449 // Generate OpControlBarrier.
4450 //
4451 // Ops[0] = Execution Scope ID
4452 // Ops[1] = Memory Scope ID
4453 // Ops[2] = Memory Semantics ID
4454 //
4455 Value *ExecutionScope = Call->getArgOperand(0);
4456 Value *MemoryScope = Call->getArgOperand(1);
4457 Value *MemorySemantics = Call->getArgOperand(2);
4458
David Neto257c3892018-04-11 13:19:45 -04004459 SPIRVOperandList Ops;
4460 Ops << MkId(VMap[ExecutionScope]) << MkId(VMap[MemoryScope])
4461 << MkId(VMap[MemorySemantics]);
David Neto22f144c2017-06-12 14:26:21 -04004462
David Neto87846742018-04-11 17:36:22 -04004463 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpControlBarrier, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004464 break;
4465 }
4466
4467 // memory barrier is converted to OpMemoryBarrier
4468 if (Callee->getName().equals("__spirv_memory_barrier")) {
4469 //
4470 // Generate OpMemoryBarrier.
4471 //
4472 // Ops[0] = Memory Scope ID
4473 // Ops[1] = Memory Semantics ID
4474 //
4475 SPIRVOperandList Ops;
4476
David Neto257c3892018-04-11 13:19:45 -04004477 uint32_t MemoryScopeID = VMap[Call->getArgOperand(0)];
4478 uint32_t MemorySemanticsID = VMap[Call->getArgOperand(1)];
David Neto22f144c2017-06-12 14:26:21 -04004479
David Neto257c3892018-04-11 13:19:45 -04004480 Ops << MkId(MemoryScopeID) << MkId(MemorySemanticsID);
David Neto22f144c2017-06-12 14:26:21 -04004481
David Neto87846742018-04-11 17:36:22 -04004482 auto *Inst = new SPIRVInstruction(spv::OpMemoryBarrier, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004483 SPIRVInstList.push_back(Inst);
4484 break;
4485 }
4486
4487 // isinf is converted to OpIsInf
4488 if (Callee->getName().equals("__spirv_isinff") ||
4489 Callee->getName().equals("__spirv_isinfDv2_f") ||
4490 Callee->getName().equals("__spirv_isinfDv3_f") ||
4491 Callee->getName().equals("__spirv_isinfDv4_f")) {
4492 //
4493 // Generate OpIsInf.
4494 //
4495 // Ops[0] = Result Type ID
4496 // Ops[1] = X ID
4497 //
4498 SPIRVOperandList Ops;
4499
David Neto257c3892018-04-11 13:19:45 -04004500 Ops << MkId(lookupType(I.getType()))
4501 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004502
4503 VMap[&I] = nextID;
4504
David Neto87846742018-04-11 17:36:22 -04004505 auto *Inst = new SPIRVInstruction(spv::OpIsInf, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004506 SPIRVInstList.push_back(Inst);
4507 break;
4508 }
4509
4510 // isnan is converted to OpIsNan
4511 if (Callee->getName().equals("__spirv_isnanf") ||
4512 Callee->getName().equals("__spirv_isnanDv2_f") ||
4513 Callee->getName().equals("__spirv_isnanDv3_f") ||
4514 Callee->getName().equals("__spirv_isnanDv4_f")) {
4515 //
4516 // Generate OpIsInf.
4517 //
4518 // Ops[0] = Result Type ID
4519 // Ops[1] = X ID
4520 //
4521 SPIRVOperandList Ops;
4522
David Neto257c3892018-04-11 13:19:45 -04004523 Ops << MkId(lookupType(I.getType()))
4524 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004525
4526 VMap[&I] = nextID;
4527
David Neto87846742018-04-11 17:36:22 -04004528 auto *Inst = new SPIRVInstruction(spv::OpIsNan, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004529 SPIRVInstList.push_back(Inst);
4530 break;
4531 }
4532
4533 // all is converted to OpAll
4534 if (Callee->getName().equals("__spirv_allDv2_i") ||
4535 Callee->getName().equals("__spirv_allDv3_i") ||
4536 Callee->getName().equals("__spirv_allDv4_i")) {
4537 //
4538 // Generate OpAll.
4539 //
4540 // Ops[0] = Result Type ID
4541 // Ops[1] = Vector ID
4542 //
4543 SPIRVOperandList Ops;
4544
David Neto257c3892018-04-11 13:19:45 -04004545 Ops << MkId(lookupType(I.getType()))
4546 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004547
4548 VMap[&I] = nextID;
4549
David Neto87846742018-04-11 17:36:22 -04004550 auto *Inst = new SPIRVInstruction(spv::OpAll, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004551 SPIRVInstList.push_back(Inst);
4552 break;
4553 }
4554
4555 // any is converted to OpAny
4556 if (Callee->getName().equals("__spirv_anyDv2_i") ||
4557 Callee->getName().equals("__spirv_anyDv3_i") ||
4558 Callee->getName().equals("__spirv_anyDv4_i")) {
4559 //
4560 // Generate OpAny.
4561 //
4562 // Ops[0] = Result Type ID
4563 // Ops[1] = Vector ID
4564 //
4565 SPIRVOperandList Ops;
4566
David Neto257c3892018-04-11 13:19:45 -04004567 Ops << MkId(lookupType(I.getType()))
4568 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004569
4570 VMap[&I] = nextID;
4571
David Neto87846742018-04-11 17:36:22 -04004572 auto *Inst = new SPIRVInstruction(spv::OpAny, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004573 SPIRVInstList.push_back(Inst);
4574 break;
4575 }
4576
4577 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
4578 // Additionally, OpTypeSampledImage is generated.
4579 if (Callee->getName().equals(
4580 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
4581 Callee->getName().equals(
4582 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
4583 //
4584 // Generate OpSampledImage.
4585 //
4586 // Ops[0] = Result Type ID
4587 // Ops[1] = Image ID
4588 // Ops[2] = Sampler ID
4589 //
4590 SPIRVOperandList Ops;
4591
4592 Value *Image = Call->getArgOperand(0);
4593 Value *Sampler = Call->getArgOperand(1);
4594 Value *Coordinate = Call->getArgOperand(2);
4595
4596 TypeMapType &OpImageTypeMap = getImageTypeMap();
4597 Type *ImageTy = Image->getType()->getPointerElementType();
4598 uint32_t ImageTyID = OpImageTypeMap[ImageTy];
David Neto22f144c2017-06-12 14:26:21 -04004599 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004600 uint32_t SamplerID = VMap[Sampler];
David Neto257c3892018-04-11 13:19:45 -04004601
4602 Ops << MkId(ImageTyID) << MkId(ImageID) << MkId(SamplerID);
David Neto22f144c2017-06-12 14:26:21 -04004603
4604 uint32_t SampledImageID = nextID;
4605
David Neto87846742018-04-11 17:36:22 -04004606 auto *Inst = new SPIRVInstruction(spv::OpSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004607 SPIRVInstList.push_back(Inst);
4608
4609 //
4610 // Generate OpImageSampleExplicitLod.
4611 //
4612 // Ops[0] = Result Type ID
4613 // Ops[1] = Sampled Image ID
4614 // Ops[2] = Coordinate ID
4615 // Ops[3] = Image Operands Type ID
4616 // Ops[4] ... Ops[n] = Operands ID
4617 //
4618 Ops.clear();
4619
David Neto257c3892018-04-11 13:19:45 -04004620 Ops << MkId(lookupType(Call->getType())) << MkId(SampledImageID)
4621 << MkId(VMap[Coordinate]) << MkNum(spv::ImageOperandsLodMask);
David Neto22f144c2017-06-12 14:26:21 -04004622
4623 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
David Neto257c3892018-04-11 13:19:45 -04004624 Ops << MkId(VMap[CstFP0]);
David Neto22f144c2017-06-12 14:26:21 -04004625
4626 VMap[&I] = nextID;
4627
David Neto87846742018-04-11 17:36:22 -04004628 Inst = new SPIRVInstruction(spv::OpImageSampleExplicitLod, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004629 SPIRVInstList.push_back(Inst);
4630 break;
4631 }
4632
4633 // write_imagef is mapped to OpImageWrite.
4634 if (Callee->getName().equals(
4635 "_Z12write_imagef14ocl_image2d_woDv2_iDv4_f") ||
4636 Callee->getName().equals(
4637 "_Z12write_imagef14ocl_image3d_woDv4_iDv4_f")) {
4638 //
4639 // Generate OpImageWrite.
4640 //
4641 // Ops[0] = Image ID
4642 // Ops[1] = Coordinate ID
4643 // Ops[2] = Texel ID
4644 // Ops[3] = (Optional) Image Operands Type (Literal Number)
4645 // Ops[4] ... Ops[n] = (Optional) Operands ID
4646 //
4647 SPIRVOperandList Ops;
4648
4649 Value *Image = Call->getArgOperand(0);
4650 Value *Coordinate = Call->getArgOperand(1);
4651 Value *Texel = Call->getArgOperand(2);
4652
4653 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004654 uint32_t CoordinateID = VMap[Coordinate];
David Neto22f144c2017-06-12 14:26:21 -04004655 uint32_t TexelID = VMap[Texel];
David Neto257c3892018-04-11 13:19:45 -04004656 Ops << MkId(ImageID) << MkId(CoordinateID) << MkId(TexelID);
David Neto22f144c2017-06-12 14:26:21 -04004657
David Neto87846742018-04-11 17:36:22 -04004658 auto *Inst = new SPIRVInstruction(spv::OpImageWrite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004659 SPIRVInstList.push_back(Inst);
4660 break;
4661 }
4662
David Neto5c22a252018-03-15 16:07:41 -04004663 // get_image_width is mapped to OpImageQuerySize
4664 if (Callee->getName().equals("_Z15get_image_width14ocl_image2d_ro") ||
4665 Callee->getName().equals("_Z15get_image_width14ocl_image2d_wo") ||
4666 Callee->getName().equals("_Z16get_image_height14ocl_image2d_ro") ||
4667 Callee->getName().equals("_Z16get_image_height14ocl_image2d_wo")) {
4668 //
4669 // Generate OpImageQuerySize, then pull out the right component.
4670 // Assume 2D image for now.
4671 //
4672 // Ops[0] = Image ID
4673 //
4674 // %sizes = OpImageQuerySizes %uint2 %im
4675 // %result = OpCompositeExtract %uint %sizes 0-or-1
4676 SPIRVOperandList Ops;
4677
4678 // Implement:
4679 // %sizes = OpImageQuerySizes %uint2 %im
4680 uint32_t SizesTypeID =
4681 TypeMap[VectorType::get(Type::getInt32Ty(Context), 2)];
David Neto5c22a252018-03-15 16:07:41 -04004682 Value *Image = Call->getArgOperand(0);
4683 uint32_t ImageID = VMap[Image];
David Neto257c3892018-04-11 13:19:45 -04004684 Ops << MkId(SizesTypeID) << MkId(ImageID);
David Neto5c22a252018-03-15 16:07:41 -04004685
4686 uint32_t SizesID = nextID++;
David Neto87846742018-04-11 17:36:22 -04004687 auto *QueryInst =
4688 new SPIRVInstruction(spv::OpImageQuerySize, SizesID, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004689 SPIRVInstList.push_back(QueryInst);
4690
4691 // Reset value map entry since we generated an intermediate instruction.
4692 VMap[&I] = nextID;
4693
4694 // Implement:
4695 // %result = OpCompositeExtract %uint %sizes 0-or-1
4696 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004697 Ops << MkId(TypeMap[I.getType()]) << MkId(SizesID);
David Neto5c22a252018-03-15 16:07:41 -04004698
4699 uint32_t component = Callee->getName().contains("height") ? 1 : 0;
David Neto257c3892018-04-11 13:19:45 -04004700 Ops << MkNum(component);
David Neto5c22a252018-03-15 16:07:41 -04004701
David Neto87846742018-04-11 17:36:22 -04004702 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004703 SPIRVInstList.push_back(Inst);
4704 break;
4705 }
4706
David Neto22f144c2017-06-12 14:26:21 -04004707 // Call instrucion is deferred because it needs function's ID. Record
4708 // slot's location on SPIRVInstructionList.
4709 DeferredInsts.push_back(
4710 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4711
David Neto3fbb4072017-10-16 11:28:14 -04004712 // Check whether the implementation of this call uses an extended
4713 // instruction plus one more value-producing instruction. If so, then
4714 // reserve the id for the extra value-producing slot.
4715 glsl::ExtInst EInst = getIndirectExtInstEnum(Callee->getName());
4716 if (EInst != kGlslExtInstBad) {
4717 // Reserve a spot for the extra value.
David Neto4d02a532017-09-17 12:57:44 -04004718 // Increase nextID.
David Neto22f144c2017-06-12 14:26:21 -04004719 VMap[&I] = nextID;
4720 nextID++;
4721 }
4722 break;
4723 }
4724 case Instruction::Ret: {
4725 unsigned NumOps = I.getNumOperands();
4726 if (NumOps == 0) {
4727 //
4728 // Generate OpReturn.
4729 //
David Neto87846742018-04-11 17:36:22 -04004730 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpReturn, {}));
David Neto22f144c2017-06-12 14:26:21 -04004731 } else {
4732 //
4733 // Generate OpReturnValue.
4734 //
4735
4736 // Ops[0] = Return Value ID
4737 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004738
4739 Ops << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004740
David Neto87846742018-04-11 17:36:22 -04004741 auto *Inst = new SPIRVInstruction(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004742 SPIRVInstList.push_back(Inst);
4743 break;
4744 }
4745 break;
4746 }
4747 }
4748}
4749
4750void SPIRVProducerPass::GenerateFuncEpilogue() {
4751 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4752
4753 //
4754 // Generate OpFunctionEnd
4755 //
4756
David Neto87846742018-04-11 17:36:22 -04004757 auto *Inst = new SPIRVInstruction(spv::OpFunctionEnd, {});
David Neto22f144c2017-06-12 14:26:21 -04004758 SPIRVInstList.push_back(Inst);
4759}
4760
4761bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
4762 LLVMContext &Context = Ty->getContext();
4763 if (Ty->isVectorTy()) {
4764 if (Ty->getVectorElementType() == Type::getInt8Ty(Context) &&
4765 Ty->getVectorNumElements() == 4) {
4766 return true;
4767 }
4768 }
4769
4770 return false;
4771}
4772
David Neto257c3892018-04-11 13:19:45 -04004773uint32_t SPIRVProducerPass::GetI32Zero() {
4774 if (0 == constant_i32_zero_id_) {
4775 llvm_unreachable("Requesting a 32-bit integer constant but it is not "
4776 "defined in the SPIR-V module");
4777 }
4778 return constant_i32_zero_id_;
4779}
4780
David Neto22f144c2017-06-12 14:26:21 -04004781void SPIRVProducerPass::HandleDeferredInstruction() {
4782 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4783 ValueMapType &VMap = getValueMap();
4784 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4785
4786 for (auto DeferredInst = DeferredInsts.rbegin();
4787 DeferredInst != DeferredInsts.rend(); ++DeferredInst) {
4788 Value *Inst = std::get<0>(*DeferredInst);
4789 SPIRVInstructionList::iterator InsertPoint = ++std::get<1>(*DeferredInst);
4790 if (InsertPoint != SPIRVInstList.end()) {
4791 while ((*InsertPoint)->getOpcode() == spv::OpPhi) {
4792 ++InsertPoint;
4793 }
4794 }
4795
4796 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
4797 // Check whether basic block, which has this branch instruction, is loop
4798 // header or not. If it is loop header, generate OpLoopMerge and
4799 // OpBranchConditional.
4800 Function *Func = Br->getParent()->getParent();
4801 DominatorTree &DT =
4802 getAnalysis<DominatorTreeWrapperPass>(*Func).getDomTree();
4803 const LoopInfo &LI =
4804 getAnalysis<LoopInfoWrapperPass>(*Func).getLoopInfo();
4805
4806 BasicBlock *BrBB = Br->getParent();
4807 if (LI.isLoopHeader(BrBB)) {
4808 Value *ContinueBB = nullptr;
4809 Value *MergeBB = nullptr;
4810
4811 Loop *L = LI.getLoopFor(BrBB);
4812 MergeBB = L->getExitBlock();
4813 if (!MergeBB) {
4814 // StructurizeCFG pass converts CFG into triangle shape and the cfg
4815 // has regions with single entry/exit. As a result, loop should not
4816 // have multiple exits.
4817 llvm_unreachable("Loop has multiple exits???");
4818 }
4819
4820 if (L->isLoopLatch(BrBB)) {
4821 ContinueBB = BrBB;
4822 } else {
4823 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
4824 // block.
4825 BasicBlock *Header = L->getHeader();
4826 BasicBlock *Latch = L->getLoopLatch();
4827 for (BasicBlock *BB : L->blocks()) {
4828 if (BB == Header) {
4829 continue;
4830 }
4831
4832 // Check whether block dominates block with back-edge.
4833 if (DT.dominates(BB, Latch)) {
4834 ContinueBB = BB;
4835 }
4836 }
4837
4838 if (!ContinueBB) {
4839 llvm_unreachable("Wrong continue block from loop");
4840 }
4841 }
4842
4843 //
4844 // Generate OpLoopMerge.
4845 //
4846 // Ops[0] = Merge Block ID
4847 // Ops[1] = Continue Target ID
4848 // Ops[2] = Selection Control
4849 SPIRVOperandList Ops;
4850
4851 // StructurizeCFG pass already manipulated CFG. Just use false block of
4852 // branch instruction as merge block.
4853 uint32_t MergeBBID = VMap[MergeBB];
David Neto22f144c2017-06-12 14:26:21 -04004854 uint32_t ContinueBBID = VMap[ContinueBB];
David Neto257c3892018-04-11 13:19:45 -04004855 Ops << MkId(MergeBBID) << MkId(ContinueBBID)
4856 << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004857
David Neto87846742018-04-11 17:36:22 -04004858 auto *MergeInst = new SPIRVInstruction(spv::OpLoopMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004859 SPIRVInstList.insert(InsertPoint, MergeInst);
4860
4861 } else if (Br->isConditional()) {
4862 bool HasBackEdge = false;
4863
4864 for (unsigned i = 0; i < Br->getNumSuccessors(); i++) {
4865 if (LI.isLoopHeader(Br->getSuccessor(i))) {
4866 HasBackEdge = true;
4867 }
4868 }
4869 if (!HasBackEdge) {
4870 //
4871 // Generate OpSelectionMerge.
4872 //
4873 // Ops[0] = Merge Block ID
4874 // Ops[1] = Selection Control
4875 SPIRVOperandList Ops;
4876
4877 // StructurizeCFG pass already manipulated CFG. Just use false block
4878 // of branch instruction as merge block.
4879 uint32_t MergeBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004880 Ops << MkId(MergeBBID) << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004881
David Neto87846742018-04-11 17:36:22 -04004882 auto *MergeInst = new SPIRVInstruction(spv::OpSelectionMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004883 SPIRVInstList.insert(InsertPoint, MergeInst);
4884 }
4885 }
4886
4887 if (Br->isConditional()) {
4888 //
4889 // Generate OpBranchConditional.
4890 //
4891 // Ops[0] = Condition ID
4892 // Ops[1] = True Label ID
4893 // Ops[2] = False Label ID
4894 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
4895 SPIRVOperandList Ops;
4896
4897 uint32_t CondID = VMap[Br->getCondition()];
David Neto22f144c2017-06-12 14:26:21 -04004898 uint32_t TrueBBID = VMap[Br->getSuccessor(0)];
David Neto22f144c2017-06-12 14:26:21 -04004899 uint32_t FalseBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004900
4901 Ops << MkId(CondID) << MkId(TrueBBID) << MkId(FalseBBID);
David Neto22f144c2017-06-12 14:26:21 -04004902
David Neto87846742018-04-11 17:36:22 -04004903 auto *BrInst = new SPIRVInstruction(spv::OpBranchConditional, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004904 SPIRVInstList.insert(InsertPoint, BrInst);
4905 } else {
4906 //
4907 // Generate OpBranch.
4908 //
4909 // Ops[0] = Target Label ID
4910 SPIRVOperandList Ops;
4911
4912 uint32_t TargetID = VMap[Br->getSuccessor(0)];
David Neto257c3892018-04-11 13:19:45 -04004913 Ops << MkId(TargetID);
David Neto22f144c2017-06-12 14:26:21 -04004914
David Neto87846742018-04-11 17:36:22 -04004915 SPIRVInstList.insert(InsertPoint,
4916 new SPIRVInstruction(spv::OpBranch, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004917 }
4918 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
4919 //
4920 // Generate OpPhi.
4921 //
4922 // Ops[0] = Result Type ID
4923 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
4924 SPIRVOperandList Ops;
4925
David Neto257c3892018-04-11 13:19:45 -04004926 Ops << MkId(lookupType(PHI->getType()));
David Neto22f144c2017-06-12 14:26:21 -04004927
David Neto22f144c2017-06-12 14:26:21 -04004928 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
4929 uint32_t VarID = VMap[PHI->getIncomingValue(i)];
David Neto22f144c2017-06-12 14:26:21 -04004930 uint32_t ParentID = VMap[PHI->getIncomingBlock(i)];
David Neto257c3892018-04-11 13:19:45 -04004931 Ops << MkId(VarID) << MkId(ParentID);
David Neto22f144c2017-06-12 14:26:21 -04004932 }
4933
4934 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04004935 InsertPoint,
4936 new SPIRVInstruction(spv::OpPhi, std::get<2>(*DeferredInst), Ops));
David Neto22f144c2017-06-12 14:26:21 -04004937 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
4938 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04004939 auto callee_name = Callee->getName();
4940 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04004941
4942 if (EInst) {
4943 uint32_t &ExtInstImportID = getOpExtInstImportID();
4944
4945 //
4946 // Generate OpExtInst.
4947 //
4948
4949 // Ops[0] = Result Type ID
4950 // Ops[1] = Set ID (OpExtInstImport ID)
4951 // Ops[2] = Instruction Number (Literal Number)
4952 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
4953 SPIRVOperandList Ops;
4954
David Neto257c3892018-04-11 13:19:45 -04004955 Ops << MkId(lookupType(Call->getType())) << MkId(ExtInstImportID) << MkNum(EInst);
David Neto22f144c2017-06-12 14:26:21 -04004956
David Neto22f144c2017-06-12 14:26:21 -04004957 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
4958 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004959 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004960 }
4961
David Neto87846742018-04-11 17:36:22 -04004962 auto *ExtInst = new SPIRVInstruction(spv::OpExtInst,
4963 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04004964 SPIRVInstList.insert(InsertPoint, ExtInst);
4965
David Neto3fbb4072017-10-16 11:28:14 -04004966 const auto IndirectExtInst = getIndirectExtInstEnum(callee_name);
4967 if (IndirectExtInst != kGlslExtInstBad) {
4968 // Generate one more instruction that uses the result of the extended
4969 // instruction. Its result id is one more than the id of the
4970 // extended instruction.
David Neto22f144c2017-06-12 14:26:21 -04004971 LLVMContext &Context =
4972 Call->getParent()->getParent()->getParent()->getContext();
David Neto22f144c2017-06-12 14:26:21 -04004973
David Neto3fbb4072017-10-16 11:28:14 -04004974 auto generate_extra_inst = [this, &Context, &Call, &DeferredInst,
4975 &VMap, &SPIRVInstList, &InsertPoint](
4976 spv::Op opcode, Constant *constant) {
4977 //
4978 // Generate instruction like:
4979 // result = opcode constant <extinst-result>
4980 //
4981 // Ops[0] = Result Type ID
4982 // Ops[1] = Operand 0 ;; the constant, suitably splatted
4983 // Ops[2] = Operand 1 ;; the result of the extended instruction
4984 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004985
David Neto3fbb4072017-10-16 11:28:14 -04004986 Type *resultTy = Call->getType();
David Neto257c3892018-04-11 13:19:45 -04004987 Ops << MkId(lookupType(resultTy));
David Neto3fbb4072017-10-16 11:28:14 -04004988
4989 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
4990 constant = ConstantVector::getSplat(
4991 static_cast<unsigned>(vectorTy->getNumElements()), constant);
4992 }
David Neto257c3892018-04-11 13:19:45 -04004993 Ops << MkId(VMap[constant]) << MkId(std::get<2>(*DeferredInst));
David Neto3fbb4072017-10-16 11:28:14 -04004994
4995 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04004996 InsertPoint, new SPIRVInstruction(
4997 opcode, std::get<2>(*DeferredInst) + 1, Ops));
David Neto3fbb4072017-10-16 11:28:14 -04004998 };
4999
5000 switch (IndirectExtInst) {
5001 case glsl::ExtInstFindUMsb: // Implementing clz
5002 generate_extra_inst(
5003 spv::OpISub, ConstantInt::get(Type::getInt32Ty(Context), 31));
5004 break;
5005 case glsl::ExtInstAcos: // Implementing acospi
5006 case glsl::ExtInstAsin: // Implementing asinpi
5007 case glsl::ExtInstAtan2: // Implementing atan2pi
5008 generate_extra_inst(
5009 spv::OpFMul,
5010 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
5011 break;
5012
5013 default:
5014 assert(false && "internally inconsistent");
David Neto4d02a532017-09-17 12:57:44 -04005015 }
David Neto22f144c2017-06-12 14:26:21 -04005016 }
David Neto3fbb4072017-10-16 11:28:14 -04005017
David Neto22f144c2017-06-12 14:26:21 -04005018 } else if (Callee->getName().equals("_Z8popcounti") ||
5019 Callee->getName().equals("_Z8popcountj") ||
5020 Callee->getName().equals("_Z8popcountDv2_i") ||
5021 Callee->getName().equals("_Z8popcountDv3_i") ||
5022 Callee->getName().equals("_Z8popcountDv4_i") ||
5023 Callee->getName().equals("_Z8popcountDv2_j") ||
5024 Callee->getName().equals("_Z8popcountDv3_j") ||
5025 Callee->getName().equals("_Z8popcountDv4_j")) {
5026 //
5027 // Generate OpBitCount
5028 //
5029 // Ops[0] = Result Type ID
5030 // Ops[1] = Base ID
David Neto257c3892018-04-11 13:19:45 -04005031 SPIRVOperandList Ops;
5032 Ops << MkId(lookupType(Call->getType()))
5033 << MkId(VMap[Call->getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04005034
5035 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005036 InsertPoint, new SPIRVInstruction(spv::OpBitCount,
David Neto22f144c2017-06-12 14:26:21 -04005037 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005038
5039 } else if (Callee->getName().startswith(kCompositeConstructFunctionPrefix)) {
5040
5041 // Generate an OpCompositeConstruct
5042 SPIRVOperandList Ops;
5043
5044 // The result type.
David Neto257c3892018-04-11 13:19:45 -04005045 Ops << MkId(lookupType(Call->getType()));
David Netoab03f432017-11-03 17:00:44 -04005046
5047 for (Use &use : Call->arg_operands()) {
David Neto257c3892018-04-11 13:19:45 -04005048 Value *val = use.get();
5049 Ops << MkId(VMap[use.get()]);
David Netoab03f432017-11-03 17:00:44 -04005050 }
5051
5052 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005053 InsertPoint, new SPIRVInstruction(spv::OpCompositeConstruct,
5054 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005055
David Neto22f144c2017-06-12 14:26:21 -04005056 } else {
5057 //
5058 // Generate OpFunctionCall.
5059 //
5060
5061 // Ops[0] = Result Type ID
5062 // Ops[1] = Callee Function ID
5063 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
5064 SPIRVOperandList Ops;
5065
David Neto257c3892018-04-11 13:19:45 -04005066 Ops << MkId( lookupType(Call->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005067
5068 uint32_t CalleeID = VMap[Callee];
David Neto43568eb2017-10-13 18:25:25 -04005069 if (CalleeID == 0) {
5070 errs() << "Can't translate function call. Missing builtin? "
5071 << Callee->getName() << " in: " << *Call << "\n";
5072 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
5073 // causes an infinite loop. Instead, go ahead and generate
5074 // the bad function call. A validator will catch the 0-Id.
5075 // llvm_unreachable("Can't translate function call");
5076 }
David Neto22f144c2017-06-12 14:26:21 -04005077
David Neto257c3892018-04-11 13:19:45 -04005078 Ops << MkId(CalleeID);
David Neto22f144c2017-06-12 14:26:21 -04005079
David Neto22f144c2017-06-12 14:26:21 -04005080 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5081 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04005082 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04005083 }
5084
David Neto87846742018-04-11 17:36:22 -04005085 auto *CallInst = new SPIRVInstruction(spv::OpFunctionCall,
5086 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005087 SPIRVInstList.insert(InsertPoint, CallInst);
5088 }
5089 }
5090 }
5091}
5092
David Neto1a1a0582017-07-07 12:01:44 -04005093void SPIRVProducerPass::HandleDeferredDecorations(const DataLayout &DL) {
David Netoc6f3ab22018-04-06 18:02:31 -04005094 if (getTypesNeedingArrayStride().empty() && LocalArgs.empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04005095 return;
David Netoc6f3ab22018-04-06 18:02:31 -04005096 }
David Neto1a1a0582017-07-07 12:01:44 -04005097
5098 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto1a1a0582017-07-07 12:01:44 -04005099
5100 // Find an iterator pointing just past the last decoration.
5101 bool seen_decorations = false;
5102 auto DecoInsertPoint =
5103 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
5104 [&seen_decorations](SPIRVInstruction *Inst) -> bool {
5105 const bool is_decoration =
5106 Inst->getOpcode() == spv::OpDecorate ||
5107 Inst->getOpcode() == spv::OpMemberDecorate;
5108 if (is_decoration) {
5109 seen_decorations = true;
5110 return false;
5111 } else {
5112 return seen_decorations;
5113 }
5114 });
5115
David Netoc6f3ab22018-04-06 18:02:31 -04005116 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
5117 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07005118 for (auto *type : getTypesNeedingArrayStride()) {
5119 Type *elemTy = nullptr;
5120 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
5121 elemTy = ptrTy->getElementType();
5122 } else if (auto* arrayTy = dyn_cast<ArrayType>(type)) {
5123 elemTy = arrayTy->getArrayElementType();
5124 } else if (auto* seqTy = dyn_cast<SequentialType>(type)) {
5125 elemTy = seqTy->getSequentialElementType();
5126 } else {
5127 errs() << "Unhandled strided type " << *type << "\n";
5128 llvm_unreachable("Unhandled strided type");
5129 }
David Neto1a1a0582017-07-07 12:01:44 -04005130
5131 // Ops[0] = Target ID
5132 // Ops[1] = Decoration (ArrayStride)
5133 // Ops[2] = Stride number (Literal Number)
5134 SPIRVOperandList Ops;
5135
David Neto85082642018-03-24 06:55:20 -07005136 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Neil Henning39672102017-09-29 14:33:13 +01005137 const uint32_t stride = static_cast<uint32_t>(DL.getTypeAllocSize(elemTy));
David Neto257c3892018-04-11 13:19:45 -04005138
5139 Ops << MkId(lookupType(type)) << MkNum(spv::DecorationArrayStride)
5140 << MkNum(stride);
David Neto1a1a0582017-07-07 12:01:44 -04005141
David Neto87846742018-04-11 17:36:22 -04005142 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto1a1a0582017-07-07 12:01:44 -04005143 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
5144 }
David Netoc6f3ab22018-04-06 18:02:31 -04005145
5146 // Emit SpecId decorations targeting the array size value.
5147 for (const Argument *arg : LocalArgs) {
5148 const LocalArgInfo &arg_info = LocalArgMap[arg];
5149 SPIRVOperandList Ops;
5150 Ops << MkId(arg_info.array_size_id) << MkNum(spv::DecorationSpecId)
5151 << MkNum(arg_info.spec_id);
5152 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04005153 new SPIRVInstruction(spv::OpDecorate, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04005154 }
David Neto1a1a0582017-07-07 12:01:44 -04005155}
5156
David Neto22f144c2017-06-12 14:26:21 -04005157glsl::ExtInst SPIRVProducerPass::getExtInstEnum(StringRef Name) {
5158 return StringSwitch<glsl::ExtInst>(Name)
5159 .Case("_Z3absi", glsl::ExtInst::ExtInstSAbs)
5160 .Case("_Z3absDv2_i", glsl::ExtInst::ExtInstSAbs)
5161 .Case("_Z3absDv3_i", glsl::ExtInst::ExtInstSAbs)
5162 .Case("_Z3absDv4_i", glsl::ExtInst::ExtInstSAbs)
5163 .Case("_Z5clampiii", glsl::ExtInst::ExtInstSClamp)
5164 .Case("_Z5clampDv2_iS_S_", glsl::ExtInst::ExtInstSClamp)
5165 .Case("_Z5clampDv3_iS_S_", glsl::ExtInst::ExtInstSClamp)
5166 .Case("_Z5clampDv4_iS_S_", glsl::ExtInst::ExtInstSClamp)
5167 .Case("_Z5clampjjj", glsl::ExtInst::ExtInstUClamp)
5168 .Case("_Z5clampDv2_jS_S_", glsl::ExtInst::ExtInstUClamp)
5169 .Case("_Z5clampDv3_jS_S_", glsl::ExtInst::ExtInstUClamp)
5170 .Case("_Z5clampDv4_jS_S_", glsl::ExtInst::ExtInstUClamp)
5171 .Case("_Z5clampfff", glsl::ExtInst::ExtInstFClamp)
5172 .Case("_Z5clampDv2_fS_S_", glsl::ExtInst::ExtInstFClamp)
5173 .Case("_Z5clampDv3_fS_S_", glsl::ExtInst::ExtInstFClamp)
5174 .Case("_Z5clampDv4_fS_S_", glsl::ExtInst::ExtInstFClamp)
David Neto22f144c2017-06-12 14:26:21 -04005175 .Case("_Z3maxii", glsl::ExtInst::ExtInstSMax)
5176 .Case("_Z3maxDv2_iS_", glsl::ExtInst::ExtInstSMax)
5177 .Case("_Z3maxDv3_iS_", glsl::ExtInst::ExtInstSMax)
5178 .Case("_Z3maxDv4_iS_", glsl::ExtInst::ExtInstSMax)
5179 .Case("_Z3maxjj", glsl::ExtInst::ExtInstUMax)
5180 .Case("_Z3maxDv2_jS_", glsl::ExtInst::ExtInstUMax)
5181 .Case("_Z3maxDv3_jS_", glsl::ExtInst::ExtInstUMax)
5182 .Case("_Z3maxDv4_jS_", glsl::ExtInst::ExtInstUMax)
5183 .Case("_Z3maxff", glsl::ExtInst::ExtInstFMax)
5184 .Case("_Z3maxDv2_fS_", glsl::ExtInst::ExtInstFMax)
5185 .Case("_Z3maxDv3_fS_", glsl::ExtInst::ExtInstFMax)
5186 .Case("_Z3maxDv4_fS_", glsl::ExtInst::ExtInstFMax)
5187 .StartsWith("_Z4fmax", glsl::ExtInst::ExtInstFMax)
5188 .Case("_Z3minii", glsl::ExtInst::ExtInstSMin)
5189 .Case("_Z3minDv2_iS_", glsl::ExtInst::ExtInstSMin)
5190 .Case("_Z3minDv3_iS_", glsl::ExtInst::ExtInstSMin)
5191 .Case("_Z3minDv4_iS_", glsl::ExtInst::ExtInstSMin)
5192 .Case("_Z3minjj", glsl::ExtInst::ExtInstUMin)
5193 .Case("_Z3minDv2_jS_", glsl::ExtInst::ExtInstUMin)
5194 .Case("_Z3minDv3_jS_", glsl::ExtInst::ExtInstUMin)
5195 .Case("_Z3minDv4_jS_", glsl::ExtInst::ExtInstUMin)
5196 .Case("_Z3minff", glsl::ExtInst::ExtInstFMin)
5197 .Case("_Z3minDv2_fS_", glsl::ExtInst::ExtInstFMin)
5198 .Case("_Z3minDv3_fS_", glsl::ExtInst::ExtInstFMin)
5199 .Case("_Z3minDv4_fS_", glsl::ExtInst::ExtInstFMin)
5200 .StartsWith("_Z4fmin", glsl::ExtInst::ExtInstFMin)
5201 .StartsWith("_Z7degrees", glsl::ExtInst::ExtInstDegrees)
5202 .StartsWith("_Z7radians", glsl::ExtInst::ExtInstRadians)
5203 .StartsWith("_Z3mix", glsl::ExtInst::ExtInstFMix)
5204 .StartsWith("_Z4acos", glsl::ExtInst::ExtInstAcos)
5205 .StartsWith("_Z5acosh", glsl::ExtInst::ExtInstAcosh)
5206 .StartsWith("_Z4asin", glsl::ExtInst::ExtInstAsin)
5207 .StartsWith("_Z5asinh", glsl::ExtInst::ExtInstAsinh)
5208 .StartsWith("_Z4atan", glsl::ExtInst::ExtInstAtan)
5209 .StartsWith("_Z5atan2", glsl::ExtInst::ExtInstAtan2)
5210 .StartsWith("_Z5atanh", glsl::ExtInst::ExtInstAtanh)
5211 .StartsWith("_Z4ceil", glsl::ExtInst::ExtInstCeil)
5212 .StartsWith("_Z3sin", glsl::ExtInst::ExtInstSin)
5213 .StartsWith("_Z4sinh", glsl::ExtInst::ExtInstSinh)
5214 .StartsWith("_Z8half_sin", glsl::ExtInst::ExtInstSin)
5215 .StartsWith("_Z10native_sin", glsl::ExtInst::ExtInstSin)
5216 .StartsWith("_Z3cos", glsl::ExtInst::ExtInstCos)
5217 .StartsWith("_Z4cosh", glsl::ExtInst::ExtInstCosh)
5218 .StartsWith("_Z8half_cos", glsl::ExtInst::ExtInstCos)
5219 .StartsWith("_Z10native_cos", glsl::ExtInst::ExtInstCos)
5220 .StartsWith("_Z3tan", glsl::ExtInst::ExtInstTan)
5221 .StartsWith("_Z4tanh", glsl::ExtInst::ExtInstTanh)
5222 .StartsWith("_Z8half_tan", glsl::ExtInst::ExtInstTan)
5223 .StartsWith("_Z10native_tan", glsl::ExtInst::ExtInstTan)
5224 .StartsWith("_Z3exp", glsl::ExtInst::ExtInstExp)
5225 .StartsWith("_Z8half_exp", glsl::ExtInst::ExtInstExp)
5226 .StartsWith("_Z10native_exp", glsl::ExtInst::ExtInstExp)
5227 .StartsWith("_Z4exp2", glsl::ExtInst::ExtInstExp2)
5228 .StartsWith("_Z9half_exp2", glsl::ExtInst::ExtInstExp2)
5229 .StartsWith("_Z11native_exp2", glsl::ExtInst::ExtInstExp2)
5230 .StartsWith("_Z3log", glsl::ExtInst::ExtInstLog)
5231 .StartsWith("_Z8half_log", glsl::ExtInst::ExtInstLog)
5232 .StartsWith("_Z10native_log", glsl::ExtInst::ExtInstLog)
5233 .StartsWith("_Z4log2", glsl::ExtInst::ExtInstLog2)
5234 .StartsWith("_Z9half_log2", glsl::ExtInst::ExtInstLog2)
5235 .StartsWith("_Z11native_log2", glsl::ExtInst::ExtInstLog2)
5236 .StartsWith("_Z4fabs", glsl::ExtInst::ExtInstFAbs)
5237 .StartsWith("_Z5floor", glsl::ExtInst::ExtInstFloor)
5238 .StartsWith("_Z5ldexp", glsl::ExtInst::ExtInstLdexp)
5239 .StartsWith("_Z3pow", glsl::ExtInst::ExtInstPow)
5240 .StartsWith("_Z4powr", glsl::ExtInst::ExtInstPow)
5241 .StartsWith("_Z9half_powr", glsl::ExtInst::ExtInstPow)
5242 .StartsWith("_Z11native_powr", glsl::ExtInst::ExtInstPow)
5243 .StartsWith("_Z5round", glsl::ExtInst::ExtInstRound)
5244 .StartsWith("_Z4sqrt", glsl::ExtInst::ExtInstSqrt)
5245 .StartsWith("_Z9half_sqrt", glsl::ExtInst::ExtInstSqrt)
5246 .StartsWith("_Z11native_sqrt", glsl::ExtInst::ExtInstSqrt)
5247 .StartsWith("_Z5rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5248 .StartsWith("_Z10half_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5249 .StartsWith("_Z12native_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5250 .StartsWith("_Z5trunc", glsl::ExtInst::ExtInstTrunc)
5251 .StartsWith("_Z5frexp", glsl::ExtInst::ExtInstFrexp)
5252 .StartsWith("_Z4sign", glsl::ExtInst::ExtInstFSign)
5253 .StartsWith("_Z6length", glsl::ExtInst::ExtInstLength)
5254 .StartsWith("_Z8distance", glsl::ExtInst::ExtInstDistance)
David Netoe9a03512017-10-16 10:08:27 -04005255 .StartsWith("_Z4step", glsl::ExtInst::ExtInstStep)
David Neto22f144c2017-06-12 14:26:21 -04005256 .Case("_Z5crossDv3_fS_", glsl::ExtInst::ExtInstCross)
5257 .StartsWith("_Z9normalize", glsl::ExtInst::ExtInstNormalize)
5258 .StartsWith("llvm.fmuladd.", glsl::ExtInst::ExtInstFma)
5259 .Case("spirv.unpack.v2f16", glsl::ExtInst::ExtInstUnpackHalf2x16)
5260 .Case("spirv.pack.v2f16", glsl::ExtInst::ExtInstPackHalf2x16)
David Neto62653202017-10-16 19:05:18 -04005261 .Case("clspv.fract.f", glsl::ExtInst::ExtInstFract)
5262 .Case("clspv.fract.v2f", glsl::ExtInst::ExtInstFract)
5263 .Case("clspv.fract.v3f", glsl::ExtInst::ExtInstFract)
5264 .Case("clspv.fract.v4f", glsl::ExtInst::ExtInstFract)
David Neto3fbb4072017-10-16 11:28:14 -04005265 .Default(kGlslExtInstBad);
5266}
5267
5268glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(StringRef Name) {
5269 // Check indirect cases.
5270 return StringSwitch<glsl::ExtInst>(Name)
5271 .StartsWith("_Z3clz", glsl::ExtInst::ExtInstFindUMsb)
5272 // Use exact match on float arg because these need a multiply
5273 // of a constant of the right floating point type.
5274 .Case("_Z6acospif", glsl::ExtInst::ExtInstAcos)
5275 .Case("_Z6acospiDv2_f", glsl::ExtInst::ExtInstAcos)
5276 .Case("_Z6acospiDv3_f", glsl::ExtInst::ExtInstAcos)
5277 .Case("_Z6acospiDv4_f", glsl::ExtInst::ExtInstAcos)
5278 .Case("_Z6asinpif", glsl::ExtInst::ExtInstAsin)
5279 .Case("_Z6asinpiDv2_f", glsl::ExtInst::ExtInstAsin)
5280 .Case("_Z6asinpiDv3_f", glsl::ExtInst::ExtInstAsin)
5281 .Case("_Z6asinpiDv4_f", glsl::ExtInst::ExtInstAsin)
5282 .Case("_Z7atan2piff", glsl::ExtInst::ExtInstAtan2)
5283 .Case("_Z7atan2piDv2_fS_", glsl::ExtInst::ExtInstAtan2)
5284 .Case("_Z7atan2piDv3_fS_", glsl::ExtInst::ExtInstAtan2)
5285 .Case("_Z7atan2piDv4_fS_", glsl::ExtInst::ExtInstAtan2)
5286 .Default(kGlslExtInstBad);
5287}
5288
5289glsl::ExtInst SPIRVProducerPass::getDirectOrIndirectExtInstEnum(StringRef Name) {
5290 auto direct = getExtInstEnum(Name);
5291 if (direct != kGlslExtInstBad)
5292 return direct;
5293 return getIndirectExtInstEnum(Name);
David Neto22f144c2017-06-12 14:26:21 -04005294}
5295
5296void SPIRVProducerPass::PrintResID(SPIRVInstruction *Inst) {
5297 out << "%" << Inst->getResultID();
5298}
5299
5300void SPIRVProducerPass::PrintOpcode(SPIRVInstruction *Inst) {
5301 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5302 out << "\t" << spv::getOpName(Opcode);
5303}
5304
5305void SPIRVProducerPass::PrintOperand(SPIRVOperand *Op) {
5306 SPIRVOperandType OpTy = Op->getType();
5307 switch (OpTy) {
5308 default: {
5309 llvm_unreachable("Unsupported SPIRV Operand Type???");
5310 break;
5311 }
5312 case SPIRVOperandType::NUMBERID: {
5313 out << "%" << Op->getNumID();
5314 break;
5315 }
5316 case SPIRVOperandType::LITERAL_STRING: {
5317 out << "\"" << Op->getLiteralStr() << "\"";
5318 break;
5319 }
5320 case SPIRVOperandType::LITERAL_INTEGER: {
5321 // TODO: Handle LiteralNum carefully.
5322 for (auto Word : Op->getLiteralNum()) {
5323 out << Word;
5324 }
5325 break;
5326 }
5327 case SPIRVOperandType::LITERAL_FLOAT: {
5328 // TODO: Handle LiteralNum carefully.
5329 for (auto Word : Op->getLiteralNum()) {
5330 APFloat APF = APFloat(APFloat::IEEEsingle(), APInt(32, Word));
5331 SmallString<8> Str;
5332 APF.toString(Str, 6, 2);
5333 out << Str;
5334 }
5335 break;
5336 }
5337 }
5338}
5339
5340void SPIRVProducerPass::PrintCapability(SPIRVOperand *Op) {
5341 spv::Capability Cap = static_cast<spv::Capability>(Op->getNumID());
5342 out << spv::getCapabilityName(Cap);
5343}
5344
5345void SPIRVProducerPass::PrintExtInst(SPIRVOperand *Op) {
5346 auto LiteralNum = Op->getLiteralNum();
5347 glsl::ExtInst Ext = static_cast<glsl::ExtInst>(LiteralNum[0]);
5348 out << glsl::getExtInstName(Ext);
5349}
5350
5351void SPIRVProducerPass::PrintAddrModel(SPIRVOperand *Op) {
5352 spv::AddressingModel AddrModel =
5353 static_cast<spv::AddressingModel>(Op->getNumID());
5354 out << spv::getAddressingModelName(AddrModel);
5355}
5356
5357void SPIRVProducerPass::PrintMemModel(SPIRVOperand *Op) {
5358 spv::MemoryModel MemModel = static_cast<spv::MemoryModel>(Op->getNumID());
5359 out << spv::getMemoryModelName(MemModel);
5360}
5361
5362void SPIRVProducerPass::PrintExecModel(SPIRVOperand *Op) {
5363 spv::ExecutionModel ExecModel =
5364 static_cast<spv::ExecutionModel>(Op->getNumID());
5365 out << spv::getExecutionModelName(ExecModel);
5366}
5367
5368void SPIRVProducerPass::PrintExecMode(SPIRVOperand *Op) {
5369 spv::ExecutionMode ExecMode = static_cast<spv::ExecutionMode>(Op->getNumID());
5370 out << spv::getExecutionModeName(ExecMode);
5371}
5372
5373void SPIRVProducerPass::PrintSourceLanguage(SPIRVOperand *Op) {
5374 spv::SourceLanguage SourceLang = static_cast<spv::SourceLanguage>(Op->getNumID());
5375 out << spv::getSourceLanguageName(SourceLang);
5376}
5377
5378void SPIRVProducerPass::PrintFuncCtrl(SPIRVOperand *Op) {
5379 spv::FunctionControlMask FuncCtrl =
5380 static_cast<spv::FunctionControlMask>(Op->getNumID());
5381 out << spv::getFunctionControlName(FuncCtrl);
5382}
5383
5384void SPIRVProducerPass::PrintStorageClass(SPIRVOperand *Op) {
5385 spv::StorageClass StClass = static_cast<spv::StorageClass>(Op->getNumID());
5386 out << getStorageClassName(StClass);
5387}
5388
5389void SPIRVProducerPass::PrintDecoration(SPIRVOperand *Op) {
5390 spv::Decoration Deco = static_cast<spv::Decoration>(Op->getNumID());
5391 out << getDecorationName(Deco);
5392}
5393
5394void SPIRVProducerPass::PrintBuiltIn(SPIRVOperand *Op) {
5395 spv::BuiltIn BIn = static_cast<spv::BuiltIn>(Op->getNumID());
5396 out << getBuiltInName(BIn);
5397}
5398
5399void SPIRVProducerPass::PrintSelectionControl(SPIRVOperand *Op) {
5400 spv::SelectionControlMask BIn =
5401 static_cast<spv::SelectionControlMask>(Op->getNumID());
5402 out << getSelectionControlName(BIn);
5403}
5404
5405void SPIRVProducerPass::PrintLoopControl(SPIRVOperand *Op) {
5406 spv::LoopControlMask BIn = static_cast<spv::LoopControlMask>(Op->getNumID());
5407 out << getLoopControlName(BIn);
5408}
5409
5410void SPIRVProducerPass::PrintDimensionality(SPIRVOperand *Op) {
5411 spv::Dim DIM = static_cast<spv::Dim>(Op->getNumID());
5412 out << getDimName(DIM);
5413}
5414
5415void SPIRVProducerPass::PrintImageFormat(SPIRVOperand *Op) {
5416 spv::ImageFormat Format = static_cast<spv::ImageFormat>(Op->getNumID());
5417 out << getImageFormatName(Format);
5418}
5419
5420void SPIRVProducerPass::PrintMemoryAccess(SPIRVOperand *Op) {
5421 out << spv::getMemoryAccessName(
5422 static_cast<spv::MemoryAccessMask>(Op->getNumID()));
5423}
5424
5425void SPIRVProducerPass::PrintImageOperandsType(SPIRVOperand *Op) {
5426 auto LiteralNum = Op->getLiteralNum();
5427 spv::ImageOperandsMask Type =
5428 static_cast<spv::ImageOperandsMask>(LiteralNum[0]);
5429 out << getImageOperandsName(Type);
5430}
5431
5432void SPIRVProducerPass::WriteSPIRVAssembly() {
5433 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5434
5435 for (auto Inst : SPIRVInstList) {
5436 SPIRVOperandList Ops = Inst->getOperands();
5437 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5438
5439 switch (Opcode) {
5440 default: {
5441 llvm_unreachable("Unsupported SPIRV instruction");
5442 break;
5443 }
5444 case spv::OpCapability: {
5445 // Ops[0] = Capability
5446 PrintOpcode(Inst);
5447 out << " ";
5448 PrintCapability(Ops[0]);
5449 out << "\n";
5450 break;
5451 }
5452 case spv::OpMemoryModel: {
5453 // Ops[0] = Addressing Model
5454 // Ops[1] = Memory Model
5455 PrintOpcode(Inst);
5456 out << " ";
5457 PrintAddrModel(Ops[0]);
5458 out << " ";
5459 PrintMemModel(Ops[1]);
5460 out << "\n";
5461 break;
5462 }
5463 case spv::OpEntryPoint: {
5464 // Ops[0] = Execution Model
5465 // Ops[1] = EntryPoint ID
5466 // Ops[2] = Name (Literal String)
5467 // Ops[3] ... Ops[n] = Interface ID
5468 PrintOpcode(Inst);
5469 out << " ";
5470 PrintExecModel(Ops[0]);
5471 for (uint32_t i = 1; i < Ops.size(); i++) {
5472 out << " ";
5473 PrintOperand(Ops[i]);
5474 }
5475 out << "\n";
5476 break;
5477 }
5478 case spv::OpExecutionMode: {
5479 // Ops[0] = Entry Point ID
5480 // Ops[1] = Execution Mode
5481 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
5482 PrintOpcode(Inst);
5483 out << " ";
5484 PrintOperand(Ops[0]);
5485 out << " ";
5486 PrintExecMode(Ops[1]);
5487 for (uint32_t i = 2; i < Ops.size(); i++) {
5488 out << " ";
5489 PrintOperand(Ops[i]);
5490 }
5491 out << "\n";
5492 break;
5493 }
5494 case spv::OpSource: {
5495 // Ops[0] = SourceLanguage ID
5496 // Ops[1] = Version (LiteralNum)
5497 PrintOpcode(Inst);
5498 out << " ";
5499 PrintSourceLanguage(Ops[0]);
5500 out << " ";
5501 PrintOperand(Ops[1]);
5502 out << "\n";
5503 break;
5504 }
5505 case spv::OpDecorate: {
5506 // Ops[0] = Target ID
5507 // Ops[1] = Decoration (Block or BufferBlock)
5508 // Ops[2] ... Ops[n] = Optional literals according to Decoration
5509 PrintOpcode(Inst);
5510 out << " ";
5511 PrintOperand(Ops[0]);
5512 out << " ";
5513 PrintDecoration(Ops[1]);
5514 // Handle BuiltIn OpDecorate specially.
5515 if (Ops[1]->getNumID() == spv::DecorationBuiltIn) {
5516 out << " ";
5517 PrintBuiltIn(Ops[2]);
5518 } else {
5519 for (uint32_t i = 2; i < Ops.size(); i++) {
5520 out << " ";
5521 PrintOperand(Ops[i]);
5522 }
5523 }
5524 out << "\n";
5525 break;
5526 }
5527 case spv::OpMemberDecorate: {
5528 // Ops[0] = Structure Type ID
5529 // Ops[1] = Member Index(Literal Number)
5530 // Ops[2] = Decoration
5531 // Ops[3] ... Ops[n] = Optional literals according to Decoration
5532 PrintOpcode(Inst);
5533 out << " ";
5534 PrintOperand(Ops[0]);
5535 out << " ";
5536 PrintOperand(Ops[1]);
5537 out << " ";
5538 PrintDecoration(Ops[2]);
5539 for (uint32_t i = 3; i < Ops.size(); i++) {
5540 out << " ";
5541 PrintOperand(Ops[i]);
5542 }
5543 out << "\n";
5544 break;
5545 }
5546 case spv::OpTypePointer: {
5547 // Ops[0] = Storage Class
5548 // Ops[1] = Element Type ID
5549 PrintResID(Inst);
5550 out << " = ";
5551 PrintOpcode(Inst);
5552 out << " ";
5553 PrintStorageClass(Ops[0]);
5554 out << " ";
5555 PrintOperand(Ops[1]);
5556 out << "\n";
5557 break;
5558 }
5559 case spv::OpTypeImage: {
5560 // Ops[0] = Sampled Type ID
5561 // Ops[1] = Dim ID
5562 // Ops[2] = Depth (Literal Number)
5563 // Ops[3] = Arrayed (Literal Number)
5564 // Ops[4] = MS (Literal Number)
5565 // Ops[5] = Sampled (Literal Number)
5566 // Ops[6] = Image Format ID
5567 PrintResID(Inst);
5568 out << " = ";
5569 PrintOpcode(Inst);
5570 out << " ";
5571 PrintOperand(Ops[0]);
5572 out << " ";
5573 PrintDimensionality(Ops[1]);
5574 out << " ";
5575 PrintOperand(Ops[2]);
5576 out << " ";
5577 PrintOperand(Ops[3]);
5578 out << " ";
5579 PrintOperand(Ops[4]);
5580 out << " ";
5581 PrintOperand(Ops[5]);
5582 out << " ";
5583 PrintImageFormat(Ops[6]);
5584 out << "\n";
5585 break;
5586 }
5587 case spv::OpFunction: {
5588 // Ops[0] : Result Type ID
5589 // Ops[1] : Function Control
5590 // Ops[2] : Function Type ID
5591 PrintResID(Inst);
5592 out << " = ";
5593 PrintOpcode(Inst);
5594 out << " ";
5595 PrintOperand(Ops[0]);
5596 out << " ";
5597 PrintFuncCtrl(Ops[1]);
5598 out << " ";
5599 PrintOperand(Ops[2]);
5600 out << "\n";
5601 break;
5602 }
5603 case spv::OpSelectionMerge: {
5604 // Ops[0] = Merge Block ID
5605 // Ops[1] = Selection Control
5606 PrintOpcode(Inst);
5607 out << " ";
5608 PrintOperand(Ops[0]);
5609 out << " ";
5610 PrintSelectionControl(Ops[1]);
5611 out << "\n";
5612 break;
5613 }
5614 case spv::OpLoopMerge: {
5615 // Ops[0] = Merge Block ID
5616 // Ops[1] = Continue Target ID
5617 // Ops[2] = Selection Control
5618 PrintOpcode(Inst);
5619 out << " ";
5620 PrintOperand(Ops[0]);
5621 out << " ";
5622 PrintOperand(Ops[1]);
5623 out << " ";
5624 PrintLoopControl(Ops[2]);
5625 out << "\n";
5626 break;
5627 }
5628 case spv::OpImageSampleExplicitLod: {
5629 // Ops[0] = Result Type ID
5630 // Ops[1] = Sampled Image ID
5631 // Ops[2] = Coordinate ID
5632 // Ops[3] = Image Operands Type ID
5633 // Ops[4] ... Ops[n] = Operands ID
5634 PrintResID(Inst);
5635 out << " = ";
5636 PrintOpcode(Inst);
5637 for (uint32_t i = 0; i < 3; i++) {
5638 out << " ";
5639 PrintOperand(Ops[i]);
5640 }
5641 out << " ";
5642 PrintImageOperandsType(Ops[3]);
5643 for (uint32_t i = 4; i < Ops.size(); i++) {
5644 out << " ";
5645 PrintOperand(Ops[i]);
5646 }
5647 out << "\n";
5648 break;
5649 }
5650 case spv::OpVariable: {
5651 // Ops[0] : Result Type ID
5652 // Ops[1] : Storage Class
5653 // Ops[2] ... Ops[n] = Initializer IDs
5654 PrintResID(Inst);
5655 out << " = ";
5656 PrintOpcode(Inst);
5657 out << " ";
5658 PrintOperand(Ops[0]);
5659 out << " ";
5660 PrintStorageClass(Ops[1]);
5661 for (uint32_t i = 2; i < Ops.size(); i++) {
5662 out << " ";
5663 PrintOperand(Ops[i]);
5664 }
5665 out << "\n";
5666 break;
5667 }
5668 case spv::OpExtInst: {
5669 // Ops[0] = Result Type ID
5670 // Ops[1] = Set ID (OpExtInstImport ID)
5671 // Ops[2] = Instruction Number (Literal Number)
5672 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5673 PrintResID(Inst);
5674 out << " = ";
5675 PrintOpcode(Inst);
5676 out << " ";
5677 PrintOperand(Ops[0]);
5678 out << " ";
5679 PrintOperand(Ops[1]);
5680 out << " ";
5681 PrintExtInst(Ops[2]);
5682 for (uint32_t i = 3; i < Ops.size(); i++) {
5683 out << " ";
5684 PrintOperand(Ops[i]);
5685 }
5686 out << "\n";
5687 break;
5688 }
5689 case spv::OpCopyMemory: {
5690 // Ops[0] = Addressing Model
5691 // Ops[1] = Memory Model
5692 PrintOpcode(Inst);
5693 out << " ";
5694 PrintOperand(Ops[0]);
5695 out << " ";
5696 PrintOperand(Ops[1]);
5697 out << " ";
5698 PrintMemoryAccess(Ops[2]);
5699 out << " ";
5700 PrintOperand(Ops[3]);
5701 out << "\n";
5702 break;
5703 }
5704 case spv::OpExtension:
5705 case spv::OpControlBarrier:
5706 case spv::OpMemoryBarrier:
5707 case spv::OpBranch:
5708 case spv::OpBranchConditional:
5709 case spv::OpStore:
5710 case spv::OpImageWrite:
5711 case spv::OpReturnValue:
5712 case spv::OpReturn:
5713 case spv::OpFunctionEnd: {
5714 PrintOpcode(Inst);
5715 for (uint32_t i = 0; i < Ops.size(); i++) {
5716 out << " ";
5717 PrintOperand(Ops[i]);
5718 }
5719 out << "\n";
5720 break;
5721 }
5722 case spv::OpExtInstImport:
5723 case spv::OpTypeRuntimeArray:
5724 case spv::OpTypeStruct:
5725 case spv::OpTypeSampler:
5726 case spv::OpTypeSampledImage:
5727 case spv::OpTypeInt:
5728 case spv::OpTypeFloat:
5729 case spv::OpTypeArray:
5730 case spv::OpTypeVector:
5731 case spv::OpTypeBool:
5732 case spv::OpTypeVoid:
5733 case spv::OpTypeFunction:
5734 case spv::OpFunctionParameter:
5735 case spv::OpLabel:
5736 case spv::OpPhi:
5737 case spv::OpLoad:
5738 case spv::OpSelect:
5739 case spv::OpAccessChain:
5740 case spv::OpPtrAccessChain:
5741 case spv::OpInBoundsAccessChain:
5742 case spv::OpUConvert:
5743 case spv::OpSConvert:
5744 case spv::OpConvertFToU:
5745 case spv::OpConvertFToS:
5746 case spv::OpConvertUToF:
5747 case spv::OpConvertSToF:
5748 case spv::OpFConvert:
5749 case spv::OpConvertPtrToU:
5750 case spv::OpConvertUToPtr:
5751 case spv::OpBitcast:
5752 case spv::OpIAdd:
5753 case spv::OpFAdd:
5754 case spv::OpISub:
5755 case spv::OpFSub:
5756 case spv::OpIMul:
5757 case spv::OpFMul:
5758 case spv::OpUDiv:
5759 case spv::OpSDiv:
5760 case spv::OpFDiv:
5761 case spv::OpUMod:
5762 case spv::OpSRem:
5763 case spv::OpFRem:
5764 case spv::OpBitwiseOr:
5765 case spv::OpBitwiseXor:
5766 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005767 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005768 case spv::OpShiftLeftLogical:
5769 case spv::OpShiftRightLogical:
5770 case spv::OpShiftRightArithmetic:
5771 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04005772 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04005773 case spv::OpCompositeExtract:
5774 case spv::OpVectorExtractDynamic:
5775 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04005776 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04005777 case spv::OpVectorInsertDynamic:
5778 case spv::OpVectorShuffle:
5779 case spv::OpIEqual:
5780 case spv::OpINotEqual:
5781 case spv::OpUGreaterThan:
5782 case spv::OpUGreaterThanEqual:
5783 case spv::OpULessThan:
5784 case spv::OpULessThanEqual:
5785 case spv::OpSGreaterThan:
5786 case spv::OpSGreaterThanEqual:
5787 case spv::OpSLessThan:
5788 case spv::OpSLessThanEqual:
5789 case spv::OpFOrdEqual:
5790 case spv::OpFOrdGreaterThan:
5791 case spv::OpFOrdGreaterThanEqual:
5792 case spv::OpFOrdLessThan:
5793 case spv::OpFOrdLessThanEqual:
5794 case spv::OpFOrdNotEqual:
5795 case spv::OpFUnordEqual:
5796 case spv::OpFUnordGreaterThan:
5797 case spv::OpFUnordGreaterThanEqual:
5798 case spv::OpFUnordLessThan:
5799 case spv::OpFUnordLessThanEqual:
5800 case spv::OpFUnordNotEqual:
5801 case spv::OpSampledImage:
5802 case spv::OpFunctionCall:
5803 case spv::OpConstantTrue:
5804 case spv::OpConstantFalse:
5805 case spv::OpConstant:
5806 case spv::OpSpecConstant:
5807 case spv::OpConstantComposite:
5808 case spv::OpSpecConstantComposite:
5809 case spv::OpConstantNull:
5810 case spv::OpLogicalOr:
5811 case spv::OpLogicalAnd:
5812 case spv::OpLogicalNot:
5813 case spv::OpLogicalNotEqual:
5814 case spv::OpUndef:
5815 case spv::OpIsInf:
5816 case spv::OpIsNan:
5817 case spv::OpAny:
5818 case spv::OpAll:
David Neto5c22a252018-03-15 16:07:41 -04005819 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04005820 case spv::OpAtomicIAdd:
5821 case spv::OpAtomicISub:
5822 case spv::OpAtomicExchange:
5823 case spv::OpAtomicIIncrement:
5824 case spv::OpAtomicIDecrement:
5825 case spv::OpAtomicCompareExchange:
5826 case spv::OpAtomicUMin:
5827 case spv::OpAtomicSMin:
5828 case spv::OpAtomicUMax:
5829 case spv::OpAtomicSMax:
5830 case spv::OpAtomicAnd:
5831 case spv::OpAtomicOr:
5832 case spv::OpAtomicXor:
5833 case spv::OpDot: {
5834 PrintResID(Inst);
5835 out << " = ";
5836 PrintOpcode(Inst);
5837 for (uint32_t i = 0; i < Ops.size(); i++) {
5838 out << " ";
5839 PrintOperand(Ops[i]);
5840 }
5841 out << "\n";
5842 break;
5843 }
5844 }
5845 }
5846}
5847
5848void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04005849 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04005850}
5851
5852void SPIRVProducerPass::WriteResultID(SPIRVInstruction *Inst) {
5853 WriteOneWord(Inst->getResultID());
5854}
5855
5856void SPIRVProducerPass::WriteWordCountAndOpcode(SPIRVInstruction *Inst) {
5857 // High 16 bit : Word Count
5858 // Low 16 bit : Opcode
5859 uint32_t Word = Inst->getOpcode();
5860 Word |= Inst->getWordCount() << 16;
5861 WriteOneWord(Word);
5862}
5863
5864void SPIRVProducerPass::WriteOperand(SPIRVOperand *Op) {
5865 SPIRVOperandType OpTy = Op->getType();
5866 switch (OpTy) {
5867 default: {
5868 llvm_unreachable("Unsupported SPIRV Operand Type???");
5869 break;
5870 }
5871 case SPIRVOperandType::NUMBERID: {
5872 WriteOneWord(Op->getNumID());
5873 break;
5874 }
5875 case SPIRVOperandType::LITERAL_STRING: {
5876 std::string Str = Op->getLiteralStr();
5877 const char *Data = Str.c_str();
5878 size_t WordSize = Str.size() / 4;
5879 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
5880 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
5881 }
5882
5883 uint32_t Remainder = Str.size() % 4;
5884 uint32_t LastWord = 0;
5885 if (Remainder) {
5886 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
5887 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
5888 }
5889 }
5890
5891 WriteOneWord(LastWord);
5892 break;
5893 }
5894 case SPIRVOperandType::LITERAL_INTEGER:
5895 case SPIRVOperandType::LITERAL_FLOAT: {
5896 auto LiteralNum = Op->getLiteralNum();
5897 // TODO: Handle LiteranNum carefully.
5898 for (auto Word : LiteralNum) {
5899 WriteOneWord(Word);
5900 }
5901 break;
5902 }
5903 }
5904}
5905
5906void SPIRVProducerPass::WriteSPIRVBinary() {
5907 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5908
5909 for (auto Inst : SPIRVInstList) {
David Netoc6f3ab22018-04-06 18:02:31 -04005910 SPIRVOperandList Ops{Inst->getOperands()};
David Neto22f144c2017-06-12 14:26:21 -04005911 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5912
5913 switch (Opcode) {
5914 default: {
David Neto5c22a252018-03-15 16:07:41 -04005915 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04005916 llvm_unreachable("Unsupported SPIRV instruction");
5917 break;
5918 }
5919 case spv::OpCapability:
5920 case spv::OpExtension:
5921 case spv::OpMemoryModel:
5922 case spv::OpEntryPoint:
5923 case spv::OpExecutionMode:
5924 case spv::OpSource:
5925 case spv::OpDecorate:
5926 case spv::OpMemberDecorate:
5927 case spv::OpBranch:
5928 case spv::OpBranchConditional:
5929 case spv::OpSelectionMerge:
5930 case spv::OpLoopMerge:
5931 case spv::OpStore:
5932 case spv::OpImageWrite:
5933 case spv::OpReturnValue:
5934 case spv::OpControlBarrier:
5935 case spv::OpMemoryBarrier:
5936 case spv::OpReturn:
5937 case spv::OpFunctionEnd:
5938 case spv::OpCopyMemory: {
5939 WriteWordCountAndOpcode(Inst);
5940 for (uint32_t i = 0; i < Ops.size(); i++) {
5941 WriteOperand(Ops[i]);
5942 }
5943 break;
5944 }
5945 case spv::OpTypeBool:
5946 case spv::OpTypeVoid:
5947 case spv::OpTypeSampler:
5948 case spv::OpLabel:
5949 case spv::OpExtInstImport:
5950 case spv::OpTypePointer:
5951 case spv::OpTypeRuntimeArray:
5952 case spv::OpTypeStruct:
5953 case spv::OpTypeImage:
5954 case spv::OpTypeSampledImage:
5955 case spv::OpTypeInt:
5956 case spv::OpTypeFloat:
5957 case spv::OpTypeArray:
5958 case spv::OpTypeVector:
5959 case spv::OpTypeFunction: {
5960 WriteWordCountAndOpcode(Inst);
5961 WriteResultID(Inst);
5962 for (uint32_t i = 0; i < Ops.size(); i++) {
5963 WriteOperand(Ops[i]);
5964 }
5965 break;
5966 }
5967 case spv::OpFunction:
5968 case spv::OpFunctionParameter:
5969 case spv::OpAccessChain:
5970 case spv::OpPtrAccessChain:
5971 case spv::OpInBoundsAccessChain:
5972 case spv::OpUConvert:
5973 case spv::OpSConvert:
5974 case spv::OpConvertFToU:
5975 case spv::OpConvertFToS:
5976 case spv::OpConvertUToF:
5977 case spv::OpConvertSToF:
5978 case spv::OpFConvert:
5979 case spv::OpConvertPtrToU:
5980 case spv::OpConvertUToPtr:
5981 case spv::OpBitcast:
5982 case spv::OpIAdd:
5983 case spv::OpFAdd:
5984 case spv::OpISub:
5985 case spv::OpFSub:
5986 case spv::OpIMul:
5987 case spv::OpFMul:
5988 case spv::OpUDiv:
5989 case spv::OpSDiv:
5990 case spv::OpFDiv:
5991 case spv::OpUMod:
5992 case spv::OpSRem:
5993 case spv::OpFRem:
5994 case spv::OpBitwiseOr:
5995 case spv::OpBitwiseXor:
5996 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005997 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005998 case spv::OpShiftLeftLogical:
5999 case spv::OpShiftRightLogical:
6000 case spv::OpShiftRightArithmetic:
6001 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04006002 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04006003 case spv::OpCompositeExtract:
6004 case spv::OpVectorExtractDynamic:
6005 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04006006 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04006007 case spv::OpVectorInsertDynamic:
6008 case spv::OpVectorShuffle:
6009 case spv::OpIEqual:
6010 case spv::OpINotEqual:
6011 case spv::OpUGreaterThan:
6012 case spv::OpUGreaterThanEqual:
6013 case spv::OpULessThan:
6014 case spv::OpULessThanEqual:
6015 case spv::OpSGreaterThan:
6016 case spv::OpSGreaterThanEqual:
6017 case spv::OpSLessThan:
6018 case spv::OpSLessThanEqual:
6019 case spv::OpFOrdEqual:
6020 case spv::OpFOrdGreaterThan:
6021 case spv::OpFOrdGreaterThanEqual:
6022 case spv::OpFOrdLessThan:
6023 case spv::OpFOrdLessThanEqual:
6024 case spv::OpFOrdNotEqual:
6025 case spv::OpFUnordEqual:
6026 case spv::OpFUnordGreaterThan:
6027 case spv::OpFUnordGreaterThanEqual:
6028 case spv::OpFUnordLessThan:
6029 case spv::OpFUnordLessThanEqual:
6030 case spv::OpFUnordNotEqual:
6031 case spv::OpExtInst:
6032 case spv::OpIsInf:
6033 case spv::OpIsNan:
6034 case spv::OpAny:
6035 case spv::OpAll:
6036 case spv::OpUndef:
6037 case spv::OpConstantNull:
6038 case spv::OpLogicalOr:
6039 case spv::OpLogicalAnd:
6040 case spv::OpLogicalNot:
6041 case spv::OpLogicalNotEqual:
6042 case spv::OpConstantComposite:
6043 case spv::OpSpecConstantComposite:
6044 case spv::OpConstantTrue:
6045 case spv::OpConstantFalse:
6046 case spv::OpConstant:
6047 case spv::OpSpecConstant:
6048 case spv::OpVariable:
6049 case spv::OpFunctionCall:
6050 case spv::OpSampledImage:
6051 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04006052 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04006053 case spv::OpSelect:
6054 case spv::OpPhi:
6055 case spv::OpLoad:
6056 case spv::OpAtomicIAdd:
6057 case spv::OpAtomicISub:
6058 case spv::OpAtomicExchange:
6059 case spv::OpAtomicIIncrement:
6060 case spv::OpAtomicIDecrement:
6061 case spv::OpAtomicCompareExchange:
6062 case spv::OpAtomicUMin:
6063 case spv::OpAtomicSMin:
6064 case spv::OpAtomicUMax:
6065 case spv::OpAtomicSMax:
6066 case spv::OpAtomicAnd:
6067 case spv::OpAtomicOr:
6068 case spv::OpAtomicXor:
6069 case spv::OpDot: {
6070 WriteWordCountAndOpcode(Inst);
6071 WriteOperand(Ops[0]);
6072 WriteResultID(Inst);
6073 for (uint32_t i = 1; i < Ops.size(); i++) {
6074 WriteOperand(Ops[i]);
6075 }
6076 break;
6077 }
6078 }
6079 }
6080}