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