blob: b155eceba2c02b26d8d1911c3a1ddf01f3a88989 [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 Neto5c22a252018-03-15 16:07:41 -040020#include <unordered_set>
David Neto482550a2018-03-24 05:21:07 -070021#include <clspv/Option.h>
David Neto22f144c2017-06-12 14:26:21 -040022#include <clspv/Passes.h>
23
24#include <llvm/ADT/StringSwitch.h>
25#include <llvm/ADT/UniqueVector.h>
26#include <llvm/Analysis/LoopInfo.h>
27#include <llvm/IR/Constants.h>
28#include <llvm/IR/Dominators.h>
29#include <llvm/IR/Instructions.h>
30#include <llvm/IR/Metadata.h>
31#include <llvm/IR/Module.h>
32#include <llvm/Pass.h>
David Netocd8ca5f2017-10-02 23:34:11 -040033#include <llvm/Support/CommandLine.h>
David Neto22f144c2017-06-12 14:26:21 -040034#include <llvm/Support/raw_ostream.h>
35#include <llvm/Transforms/Utils/Cloning.h>
36
37#include <spirv/1.0/spirv.hpp>
38#include <clspv/AddressSpace.h>
39#include <clspv/spirv_c_strings.hpp>
40#include <clspv/spirv_glsl.hpp>
41
David Neto4feb7a42017-10-06 17:29:42 -040042#include "ArgKind.h"
David Neto48f56a42017-10-06 16:44:25 -040043
David Neto22f144c2017-06-12 14:26:21 -040044#include <list>
David Neto0676e6f2017-07-11 18:47:44 -040045#include <iomanip>
David Neto26aaf622017-10-23 18:11:53 -040046#include <set>
David Neto0676e6f2017-07-11 18:47:44 -040047#include <sstream>
David Neto26aaf622017-10-23 18:11:53 -040048#include <tuple>
David Neto44795152017-07-13 15:45:28 -040049#include <utility>
David Neto22f144c2017-06-12 14:26:21 -040050
51#if defined(_MSC_VER)
52#pragma warning(pop)
53#endif
54
55using namespace llvm;
56using namespace clspv;
David Neto156783e2017-07-05 15:39:41 -040057using namespace mdconst;
David Neto22f144c2017-06-12 14:26:21 -040058
59namespace {
David Netocd8ca5f2017-10-02 23:34:11 -040060
David Neto3fbb4072017-10-16 11:28:14 -040061// The value of 1/pi. This value is from MSDN
62// https://msdn.microsoft.com/en-us/library/4hwaceh6.aspx
63const double kOneOverPi = 0.318309886183790671538;
64const glsl::ExtInst kGlslExtInstBad = static_cast<glsl::ExtInst>(0);
65
David Netoab03f432017-11-03 17:00:44 -040066const char* kCompositeConstructFunctionPrefix = "clspv.composite_construct.";
67
David Neto22f144c2017-06-12 14:26:21 -040068enum SPIRVOperandType {
69 NUMBERID,
70 LITERAL_INTEGER,
71 LITERAL_STRING,
72 LITERAL_FLOAT
73};
74
75struct SPIRVOperand {
76 explicit SPIRVOperand(SPIRVOperandType Ty, uint32_t Num)
77 : Type(Ty), LiteralNum(1, Num) {}
78 explicit SPIRVOperand(SPIRVOperandType Ty, const char *Str)
79 : Type(Ty), LiteralStr(Str) {}
80 explicit SPIRVOperand(SPIRVOperandType Ty, StringRef Str)
81 : Type(Ty), LiteralStr(Str) {}
82 explicit SPIRVOperand(SPIRVOperandType Ty, ArrayRef<uint32_t> NumVec)
83 : Type(Ty), LiteralNum(NumVec.begin(), NumVec.end()) {}
84
85 SPIRVOperandType getType() { return Type; };
86 uint32_t getNumID() { return LiteralNum[0]; };
87 std::string getLiteralStr() { return LiteralStr; };
88 ArrayRef<uint32_t> getLiteralNum() { return LiteralNum; };
89
90private:
91 SPIRVOperandType Type;
92 std::string LiteralStr;
93 SmallVector<uint32_t, 4> LiteralNum;
94};
95
96struct SPIRVInstruction {
97 explicit SPIRVInstruction(uint16_t WCount, spv::Op Opc, uint32_t ResID,
98 ArrayRef<SPIRVOperand *> Ops)
99 : WordCount(WCount), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID),
100 Operands(Ops.begin(), Ops.end()) {}
101
102 uint16_t getWordCount() const { return WordCount; }
103 uint16_t getOpcode() const { return Opcode; }
104 uint32_t getResultID() const { return ResultID; }
105 ArrayRef<SPIRVOperand *> getOperands() const { return Operands; }
106
107private:
108 uint16_t WordCount;
109 uint16_t Opcode;
110 uint32_t ResultID;
111 SmallVector<SPIRVOperand *, 4> Operands;
112};
113
114struct SPIRVProducerPass final : public ModulePass {
115 typedef std::vector<SPIRVOperand *> SPIRVOperandList;
116 typedef DenseMap<Type *, uint32_t> TypeMapType;
117 typedef UniqueVector<Type *> TypeList;
118 typedef DenseMap<Value *, uint32_t> ValueMapType;
David Netofb9a7972017-08-25 17:08:24 -0400119 typedef UniqueVector<Value *> ValueList;
David Neto22f144c2017-06-12 14:26:21 -0400120 typedef std::vector<std::pair<Value *, uint32_t>> EntryPointVecType;
121 typedef std::list<SPIRVInstruction *> SPIRVInstructionList;
122 typedef std::vector<
123 std::tuple<Value *, SPIRVInstructionList::iterator, uint32_t>>
124 DeferredInstVecType;
125 typedef DenseMap<FunctionType *, std::pair<FunctionType *, uint32_t>>
126 GlobalConstFuncMapType;
127
David Neto44795152017-07-13 15:45:28 -0400128 explicit SPIRVProducerPass(
129 raw_pwrite_stream &out, raw_ostream &descriptor_map_out,
130 ArrayRef<std::pair<unsigned, std::string>> samplerMap, bool outputAsm,
131 bool outputCInitList)
David Netoc2c368d2017-06-30 16:50:17 -0400132 : ModulePass(ID), samplerMap(samplerMap), out(out),
David Neto0676e6f2017-07-11 18:47:44 -0400133 binaryTempOut(binaryTempUnderlyingVector), binaryOut(&out),
David Netoc2c368d2017-06-30 16:50:17 -0400134 descriptorMapOut(descriptor_map_out), outputAsm(outputAsm),
David Neto0676e6f2017-07-11 18:47:44 -0400135 outputCInitList(outputCInitList), patchBoundOffset(0), nextID(1),
David Netoa60b00b2017-09-15 16:34:09 -0400136 OpExtInstImportID(0), HasVariablePointers(false), SamplerTy(nullptr),
137 WorkgroupSizeValueID(0), WorkgroupSizeVarID(0) {}
David Neto22f144c2017-06-12 14:26:21 -0400138
139 void getAnalysisUsage(AnalysisUsage &AU) const override {
140 AU.addRequired<DominatorTreeWrapperPass>();
141 AU.addRequired<LoopInfoWrapperPass>();
142 }
143
144 virtual bool runOnModule(Module &module) override;
145
146 // output the SPIR-V header block
147 void outputHeader();
148
149 // patch the SPIR-V header block
150 void patchHeader();
151
152 uint32_t lookupType(Type *Ty) {
153 if (Ty->isPointerTy() &&
154 (Ty->getPointerAddressSpace() != AddressSpace::UniformConstant)) {
155 auto PointeeTy = Ty->getPointerElementType();
156 if (PointeeTy->isStructTy() &&
157 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
158 Ty = PointeeTy;
159 }
160 }
161
162 if (0 == TypeMap.count(Ty)) {
163 Ty->print(errs());
David Netoe439d702018-03-23 13:14:08 -0700164 llvm_unreachable("\nUnhandled type!");
David Neto22f144c2017-06-12 14:26:21 -0400165 }
166
167 return TypeMap[Ty];
168 }
169 TypeMapType &getImageTypeMap() { return ImageTypeMap; }
170 TypeList &getTypeList() { return Types; };
171 ValueList &getConstantList() { return Constants; };
172 ValueMapType &getValueMap() { return ValueMap; }
173 ValueMapType &getAllocatedValueMap() { return AllocatedValueMap; }
174 SPIRVInstructionList &getSPIRVInstList() { return SPIRVInsts; };
175 ValueToValueMapTy &getArgumentGVMap() { return ArgumentGVMap; };
176 ValueMapType &getArgumentGVIDMap() { return ArgumentGVIDMap; };
177 EntryPointVecType &getEntryPointVec() { return EntryPointVec; };
178 DeferredInstVecType &getDeferredInstVec() { return DeferredInstVec; };
179 ValueList &getEntryPointInterfacesVec() { return EntryPointInterfacesVec; };
180 uint32_t &getOpExtInstImportID() { return OpExtInstImportID; };
181 std::vector<uint32_t> &getBuiltinDimVec() { return BuiltinDimensionVec; };
182 bool hasVariablePointers() { return true; /* We use StorageBuffer everywhere */ };
183 void setVariablePointers(bool Val) { HasVariablePointers = Val; };
David Neto44795152017-07-13 15:45:28 -0400184 ArrayRef<std::pair<unsigned, std::string>> &getSamplerMap() { return samplerMap; }
David Neto22f144c2017-06-12 14:26:21 -0400185 GlobalConstFuncMapType &getGlobalConstFuncTypeMap() {
186 return GlobalConstFuncTypeMap;
187 }
188 SmallPtrSet<Value *, 16> &getGlobalConstArgSet() {
189 return GlobalConstArgumentSet;
190 }
David Neto1a1a0582017-07-07 12:01:44 -0400191 TypeList &getPointerTypesNeedingArrayStride() {
192 return PointerTypesNeedingArrayStride;
193 }
David Neto22f144c2017-06-12 14:26:21 -0400194
195 void GenerateLLVMIRInfo(Module &M);
196 bool FindExtInst(Module &M);
197 void FindTypePerGlobalVar(GlobalVariable &GV);
198 void FindTypePerFunc(Function &F);
David Neto19a1bad2017-08-25 15:01:41 -0400199 // Inserts |Ty| and relevant sub-types into the |Types| member, indicating that
200 // |Ty| and its subtypes will need a corresponding SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400201 void FindType(Type *Ty);
202 void FindConstantPerGlobalVar(GlobalVariable &GV);
203 void FindConstantPerFunc(Function &F);
204 void FindConstant(Value *V);
205 void GenerateExtInstImport();
David Neto19a1bad2017-08-25 15:01:41 -0400206 // Generates instructions for SPIR-V types corresponding to the LLVM types
207 // saved in the |Types| member. A type follows its subtypes. IDs are
208 // allocated sequentially starting with the current value of nextID, and
209 // with a type following its subtypes. Also updates nextID to just beyond
210 // the last generated ID.
David Neto22f144c2017-06-12 14:26:21 -0400211 void GenerateSPIRVTypes(const DataLayout &DL);
212 void GenerateSPIRVConstants();
David Neto5c22a252018-03-15 16:07:41 -0400213 void GenerateModuleInfo(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400214 void GenerateGlobalVar(GlobalVariable &GV);
215 void GenerateSamplers(Module &M);
216 void GenerateFuncPrologue(Function &F);
217 void GenerateFuncBody(Function &F);
218 void GenerateInstForArg(Function &F);
219 spv::Op GetSPIRVCmpOpcode(CmpInst *CmpI);
220 spv::Op GetSPIRVCastOpcode(Instruction &I);
221 spv::Op GetSPIRVBinaryOpcode(Instruction &I);
222 void GenerateInstruction(Instruction &I);
223 void GenerateFuncEpilogue();
224 void HandleDeferredInstruction();
David Neto1a1a0582017-07-07 12:01:44 -0400225 void HandleDeferredDecorations(const DataLayout& DL);
David Neto22f144c2017-06-12 14:26:21 -0400226 bool is4xi8vec(Type *Ty) const;
227 spv::StorageClass GetStorageClass(unsigned AddrSpace) const;
228 spv::BuiltIn GetBuiltin(StringRef globalVarName) const;
David Neto3fbb4072017-10-16 11:28:14 -0400229 // Returns the GLSL extended instruction enum that the given function
230 // call maps to. If none, then returns the 0 value, i.e. GLSLstd4580Bad.
David Neto22f144c2017-06-12 14:26:21 -0400231 glsl::ExtInst getExtInstEnum(StringRef Name);
David Neto3fbb4072017-10-16 11:28:14 -0400232 // Returns the GLSL extended instruction enum indirectly used by the given
233 // function. That is, to implement the given function, we use an extended
234 // instruction plus one more instruction. If none, then returns the 0 value,
235 // i.e. GLSLstd4580Bad.
236 glsl::ExtInst getIndirectExtInstEnum(StringRef Name);
237 // Returns the single GLSL extended instruction used directly or
238 // indirectly by the given function call.
239 glsl::ExtInst getDirectOrIndirectExtInstEnum(StringRef Name);
David Neto22f144c2017-06-12 14:26:21 -0400240 void PrintResID(SPIRVInstruction *Inst);
241 void PrintOpcode(SPIRVInstruction *Inst);
242 void PrintOperand(SPIRVOperand *Op);
243 void PrintCapability(SPIRVOperand *Op);
244 void PrintExtInst(SPIRVOperand *Op);
245 void PrintAddrModel(SPIRVOperand *Op);
246 void PrintMemModel(SPIRVOperand *Op);
247 void PrintExecModel(SPIRVOperand *Op);
248 void PrintExecMode(SPIRVOperand *Op);
249 void PrintSourceLanguage(SPIRVOperand *Op);
250 void PrintFuncCtrl(SPIRVOperand *Op);
251 void PrintStorageClass(SPIRVOperand *Op);
252 void PrintDecoration(SPIRVOperand *Op);
253 void PrintBuiltIn(SPIRVOperand *Op);
254 void PrintSelectionControl(SPIRVOperand *Op);
255 void PrintLoopControl(SPIRVOperand *Op);
256 void PrintDimensionality(SPIRVOperand *Op);
257 void PrintImageFormat(SPIRVOperand *Op);
258 void PrintMemoryAccess(SPIRVOperand *Op);
259 void PrintImageOperandsType(SPIRVOperand *Op);
260 void WriteSPIRVAssembly();
261 void WriteOneWord(uint32_t Word);
262 void WriteResultID(SPIRVInstruction *Inst);
263 void WriteWordCountAndOpcode(SPIRVInstruction *Inst);
264 void WriteOperand(SPIRVOperand *Op);
265 void WriteSPIRVBinary();
266
267private:
268 static char ID;
David Neto44795152017-07-13 15:45:28 -0400269 ArrayRef<std::pair<unsigned, std::string>> samplerMap;
David Neto22f144c2017-06-12 14:26:21 -0400270 raw_pwrite_stream &out;
David Neto0676e6f2017-07-11 18:47:44 -0400271
272 // TODO(dneto): Wouldn't it be better to always just emit a binary, and then
273 // convert to other formats on demand?
274
275 // When emitting a C initialization list, the WriteSPIRVBinary method
276 // will actually write its words to this vector via binaryTempOut.
277 SmallVector<char, 100> binaryTempUnderlyingVector;
278 raw_svector_ostream binaryTempOut;
279
280 // Binary output writes to this stream, which might be |out| or
281 // |binaryTempOut|. It's the latter when we really want to write a C
282 // initializer list.
283 raw_pwrite_stream* binaryOut;
David Netoc2c368d2017-06-30 16:50:17 -0400284 raw_ostream &descriptorMapOut;
David Neto22f144c2017-06-12 14:26:21 -0400285 const bool outputAsm;
David Neto0676e6f2017-07-11 18:47:44 -0400286 const bool outputCInitList; // If true, output look like {0x7023, ... , 5}
David Neto22f144c2017-06-12 14:26:21 -0400287 uint64_t patchBoundOffset;
288 uint32_t nextID;
289
David Neto19a1bad2017-08-25 15:01:41 -0400290 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400291 TypeMapType TypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400292 // Maps an LLVM image type to its SPIR-V ID.
David Neto22f144c2017-06-12 14:26:21 -0400293 TypeMapType ImageTypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400294 // A unique-vector of LLVM types that map to a SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400295 TypeList Types;
296 ValueList Constants;
David Neto19a1bad2017-08-25 15:01:41 -0400297 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400298 ValueMapType ValueMap;
299 ValueMapType AllocatedValueMap;
300 SPIRVInstructionList SPIRVInsts;
David Netoe439d702018-03-23 13:14:08 -0700301 // Maps a kernel argument value to a global value. OpenCL kernel arguments
302 // have to map to resources: buffers, samplers, images, or sampled images.
David Neto22f144c2017-06-12 14:26:21 -0400303 ValueToValueMapTy ArgumentGVMap;
304 ValueMapType ArgumentGVIDMap;
305 EntryPointVecType EntryPointVec;
306 DeferredInstVecType DeferredInstVec;
307 ValueList EntryPointInterfacesVec;
308 uint32_t OpExtInstImportID;
309 std::vector<uint32_t> BuiltinDimensionVec;
310 bool HasVariablePointers;
311 Type *SamplerTy;
312 GlobalConstFuncMapType GlobalConstFuncTypeMap;
313 SmallPtrSet<Value *, 16> GlobalConstArgumentSet;
David Neto1a1a0582017-07-07 12:01:44 -0400314 // An ordered set of pointer types of Base arguments to OpPtrAccessChain,
315 // and which point into transparent memory (StorageBuffer storage class).
316 // These will require an ArrayStride decoration.
317 // See SPV_KHR_variable_pointers rev 13.
318 TypeList PointerTypesNeedingArrayStride;
David Netoa60b00b2017-09-15 16:34:09 -0400319
320 // This is truly ugly, but works around what look like driver bugs.
321 // For get_local_size, an earlier part of the flow has created a module-scope
322 // variable in Private address space to hold the value for the workgroup
323 // size. Its intializer is a uint3 value marked as builtin WorkgroupSize.
324 // When this is present, save the IDs of the initializer value and variable
325 // in these two variables. We only ever do a vector load from it, and
326 // when we see one of those, substitute just the value of the intializer.
327 // This mimics what Glslang does, and that's what drivers are used to.
David Neto66cfe642018-03-24 06:13:56 -0700328 // TODO(dneto): Remove this once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -0400329 uint32_t WorkgroupSizeValueID;
330 uint32_t WorkgroupSizeVarID;
David Neto26aaf622017-10-23 18:11:53 -0400331
332 // What module-scope variables already have had their binding information
333 // emitted?
334 DenseSet<Value*> GVarWithEmittedBindingInfo;
David Neto22f144c2017-06-12 14:26:21 -0400335};
336
337char SPIRVProducerPass::ID;
338}
339
340namespace clspv {
David Neto44795152017-07-13 15:45:28 -0400341ModulePass *
342createSPIRVProducerPass(raw_pwrite_stream &out, raw_ostream &descriptor_map_out,
343 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
344 bool outputAsm, bool outputCInitList) {
345 return new SPIRVProducerPass(out, descriptor_map_out, samplerMap, outputAsm,
346 outputCInitList);
David Neto22f144c2017-06-12 14:26:21 -0400347}
David Netoc2c368d2017-06-30 16:50:17 -0400348} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400349
350bool SPIRVProducerPass::runOnModule(Module &module) {
David Neto0676e6f2017-07-11 18:47:44 -0400351 binaryOut = outputCInitList ? &binaryTempOut : &out;
352
David Neto22f144c2017-06-12 14:26:21 -0400353 // SPIR-V always begins with its header information
354 outputHeader();
355
356 // Gather information from the LLVM IR that we require.
357 GenerateLLVMIRInfo(module);
358
359 // If we are using a sampler map, find the type of the sampler.
360 if (0 < getSamplerMap().size()) {
361 auto SamplerStructTy = module.getTypeByName("opencl.sampler_t");
362 if (!SamplerStructTy) {
363 SamplerStructTy =
364 StructType::create(module.getContext(), "opencl.sampler_t");
365 }
366
367 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
368
369 FindType(SamplerTy);
370 }
371
372 // Collect information on global variables too.
373 for (GlobalVariable &GV : module.globals()) {
374 // If the GV is one of our special __spirv_* variables, remove the
375 // initializer as it was only placed there to force LLVM to not throw the
376 // value away.
377 if (GV.getName().startswith("__spirv_")) {
378 GV.setInitializer(nullptr);
379 }
380
381 // Collect types' information from global variable.
382 FindTypePerGlobalVar(GV);
383
384 // Collect constant information from global variable.
385 FindConstantPerGlobalVar(GV);
386
387 // If the variable is an input, entry points need to know about it.
388 if (AddressSpace::Input == GV.getType()->getPointerAddressSpace()) {
David Netofb9a7972017-08-25 17:08:24 -0400389 getEntryPointInterfacesVec().insert(&GV);
David Neto22f144c2017-06-12 14:26:21 -0400390 }
391 }
392
393 // If there are extended instructions, generate OpExtInstImport.
394 if (FindExtInst(module)) {
395 GenerateExtInstImport();
396 }
397
398 // Generate SPIRV instructions for types.
399 const DataLayout &DL = module.getDataLayout();
400 GenerateSPIRVTypes(DL);
401
402 // Generate SPIRV constants.
403 GenerateSPIRVConstants();
404
405 // If we have a sampler map, we might have literal samplers to generate.
406 if (0 < getSamplerMap().size()) {
407 GenerateSamplers(module);
408 }
409
410 // Generate SPIRV variables.
411 for (GlobalVariable &GV : module.globals()) {
412 GenerateGlobalVar(GV);
413 }
414
415 // Generate SPIRV instructions for each function.
416 for (Function &F : module) {
417 if (F.isDeclaration()) {
418 continue;
419 }
420
421 // Generate Function Prologue.
422 GenerateFuncPrologue(F);
423
424 // Generate SPIRV instructions for function body.
425 GenerateFuncBody(F);
426
427 // Generate Function Epilogue.
428 GenerateFuncEpilogue();
429 }
430
431 HandleDeferredInstruction();
David Neto1a1a0582017-07-07 12:01:44 -0400432 HandleDeferredDecorations(DL);
David Neto22f144c2017-06-12 14:26:21 -0400433
434 // Generate SPIRV module information.
David Neto5c22a252018-03-15 16:07:41 -0400435 GenerateModuleInfo(module);
David Neto22f144c2017-06-12 14:26:21 -0400436
437 if (outputAsm) {
438 WriteSPIRVAssembly();
439 } else {
440 WriteSPIRVBinary();
441 }
442
443 // We need to patch the SPIR-V header to set bound correctly.
444 patchHeader();
David Neto0676e6f2017-07-11 18:47:44 -0400445
446 if (outputCInitList) {
447 bool first = true;
David Neto0676e6f2017-07-11 18:47:44 -0400448 std::ostringstream os;
449
David Neto57fb0b92017-08-04 15:35:09 -0400450 auto emit_word = [&os, &first](uint32_t word) {
David Neto0676e6f2017-07-11 18:47:44 -0400451 if (!first)
David Neto57fb0b92017-08-04 15:35:09 -0400452 os << ",\n";
453 os << word;
David Neto0676e6f2017-07-11 18:47:44 -0400454 first = false;
455 };
456
457 os << "{";
David Neto57fb0b92017-08-04 15:35:09 -0400458 const std::string str(binaryTempOut.str());
459 for (unsigned i = 0; i < str.size(); i += 4) {
460 const uint32_t a = static_cast<unsigned char>(str[i]);
461 const uint32_t b = static_cast<unsigned char>(str[i + 1]);
462 const uint32_t c = static_cast<unsigned char>(str[i + 2]);
463 const uint32_t d = static_cast<unsigned char>(str[i + 3]);
464 emit_word(a | (b << 8) | (c << 16) | (d << 24));
David Neto0676e6f2017-07-11 18:47:44 -0400465 }
466 os << "}\n";
467 out << os.str();
468 }
469
David Neto22f144c2017-06-12 14:26:21 -0400470 return false;
471}
472
473void SPIRVProducerPass::outputHeader() {
474 if (outputAsm) {
475 // for ASM output the header goes into 5 comments at the beginning of the
476 // file
477 out << "; SPIR-V\n";
478
479 // the major version number is in the 2nd highest byte
480 const uint32_t major = (spv::Version >> 16) & 0xFF;
481
482 // the minor version number is in the 2nd lowest byte
483 const uint32_t minor = (spv::Version >> 8) & 0xFF;
484 out << "; Version: " << major << "." << minor << "\n";
485
486 // use Codeplay's vendor ID
487 out << "; Generator: Codeplay; 0\n";
488
489 out << "; Bound: ";
490
491 // we record where we need to come back to and patch in the bound value
492 patchBoundOffset = out.tell();
493
494 // output one space per digit for the max size of a 32 bit unsigned integer
495 // (which is the maximum ID we could possibly be using)
496 for (uint32_t i = std::numeric_limits<uint32_t>::max(); 0 != i; i /= 10) {
497 out << " ";
498 }
499
500 out << "\n";
501
502 out << "; Schema: 0\n";
503 } else {
David Neto0676e6f2017-07-11 18:47:44 -0400504 binaryOut->write(reinterpret_cast<const char *>(&spv::MagicNumber),
David Neto22f144c2017-06-12 14:26:21 -0400505 sizeof(spv::MagicNumber));
David Neto0676e6f2017-07-11 18:47:44 -0400506 binaryOut->write(reinterpret_cast<const char *>(&spv::Version),
David Neto22f144c2017-06-12 14:26:21 -0400507 sizeof(spv::Version));
508
509 // use Codeplay's vendor ID
510 const uint32_t vendor = 3 << 16;
David Neto0676e6f2017-07-11 18:47:44 -0400511 binaryOut->write(reinterpret_cast<const char *>(&vendor), sizeof(vendor));
David Neto22f144c2017-06-12 14:26:21 -0400512
513 // we record where we need to come back to and patch in the bound value
David Neto0676e6f2017-07-11 18:47:44 -0400514 patchBoundOffset = binaryOut->tell();
David Neto22f144c2017-06-12 14:26:21 -0400515
516 // output a bad bound for now
David Neto0676e6f2017-07-11 18:47:44 -0400517 binaryOut->write(reinterpret_cast<const char *>(&nextID), sizeof(nextID));
David Neto22f144c2017-06-12 14:26:21 -0400518
519 // output the schema (reserved for use and must be 0)
520 const uint32_t schema = 0;
David Neto0676e6f2017-07-11 18:47:44 -0400521 binaryOut->write(reinterpret_cast<const char *>(&schema), sizeof(schema));
David Neto22f144c2017-06-12 14:26:21 -0400522 }
523}
524
525void SPIRVProducerPass::patchHeader() {
526 if (outputAsm) {
527 // get the string representation of the max bound used (nextID will be the
528 // max ID used)
529 auto asString = std::to_string(nextID);
530 out.pwrite(asString.c_str(), asString.size(), patchBoundOffset);
531 } else {
532 // for a binary we just write the value of nextID over bound
David Neto0676e6f2017-07-11 18:47:44 -0400533 binaryOut->pwrite(reinterpret_cast<char *>(&nextID), sizeof(nextID),
534 patchBoundOffset);
David Neto22f144c2017-06-12 14:26:21 -0400535 }
536}
537
538void SPIRVProducerPass::GenerateLLVMIRInfo(Module &M) {
539 // This function generates LLVM IR for function such as global variable for
540 // argument, constant and pointer type for argument access. These information
541 // is artificial one because we need Vulkan SPIR-V output. This function is
542 // executed ahead of FindType and FindConstant.
543 ValueToValueMapTy &ArgGVMap = getArgumentGVMap();
544 LLVMContext &Context = M.getContext();
545
546 // Map for avoiding to generate struct type with same fields.
547 DenseMap<Type *, Type *> ArgTyMap;
548
David Neto5c22a252018-03-15 16:07:41 -0400549 // These function calls need a <2 x i32> as an intermediate result but not
550 // the final result.
551 std::unordered_set<std::string> NeedsIVec2{
552 "_Z15get_image_width14ocl_image2d_ro",
553 "_Z15get_image_width14ocl_image2d_wo",
554 "_Z16get_image_height14ocl_image2d_ro",
555 "_Z16get_image_height14ocl_image2d_wo",
556 };
557
David Neto22f144c2017-06-12 14:26:21 -0400558 // Collect global constant variables.
559 SmallVector<GlobalVariable *, 8> GVList;
560 for (GlobalVariable &GV : M.globals()) {
561 if (GV.getType()->getAddressSpace() == AddressSpace::Constant) {
562 GVList.push_back(&GV);
563 }
564 }
565
566 // Change global constant variable's address space to ModuleScopePrivate.
567 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
568 for (auto GV : GVList) {
569 // If there is no user of gv, delete gv.
570 if (GV->use_empty()) {
571 GV->eraseFromParent();
572 continue;
573 }
574
575 // Create new gv with ModuleScopePrivate address space.
576 Type *NewGVTy = GV->getType()->getPointerElementType();
577 GlobalVariable *NewGV = new GlobalVariable(
578 M, NewGVTy, false, GV->getLinkage(), GV->getInitializer(), "", nullptr,
579 GV->getThreadLocalMode(), AddressSpace::ModuleScopePrivate);
580 NewGV->takeName(GV);
581
582 const SmallVector<User *, 8> GVUsers(GV->user_begin(), GV->user_end());
583 SmallVector<User*, 8> CandidateUsers;
584
585 for (User *GVU : GVUsers) {
586 if (CallInst *Call = dyn_cast<CallInst>(GVU)) {
587 // Find argument index.
588 unsigned GVCstArgIdx = 0;
589 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
590 if (GV == Call->getOperand(i)) {
591 GVCstArgIdx = i;
592 }
593 }
594
595 // Record function with global constant.
596 GlobalConstFuncTyMap[Call->getFunctionType()] =
597 std::make_pair(Call->getFunctionType(), GVCstArgIdx);
598 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(GVU)) {
599 // Check GEP users.
600 for (User *GEPU : GEP->users()) {
601 if (CallInst *GEPCall = dyn_cast<CallInst>(GEPU)) {
602 // Find argument index.
603 unsigned GVCstArgIdx = 0;
604 for (unsigned i = 0; i < GEPCall->getNumArgOperands(); i++) {
605 if (GEP == GEPCall->getOperand(i)) {
606 GVCstArgIdx = i;
607 }
608 }
609
610 // Record function with global constant.
611 GlobalConstFuncTyMap[GEPCall->getFunctionType()] =
612 std::make_pair(GEPCall->getFunctionType(), GVCstArgIdx);
613 }
614 }
615 }
616
617 CandidateUsers.push_back(GVU);
618 }
619
620 for (User *U : CandidateUsers) {
621 // Update users of gv with new gv.
622 U->replaceUsesOfWith(GV, NewGV);
623 }
624
625 // Delete original gv.
626 GV->eraseFromParent();
627 }
628
629 bool HasWorkGroupBuiltin = false;
630 for (GlobalVariable &GV : M.globals()) {
631 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
632 if (spv::BuiltInWorkgroupSize == BuiltinType) {
633 HasWorkGroupBuiltin = true;
634 }
635 }
636
637
David Neto26aaf622017-10-23 18:11:53 -0400638
639 // Map kernel functions to their ordinal number in the compilation unit.
640 UniqueVector<Function*> KernelOrdinal;
641
642 // Map the global variables created for kernel args to their creation
643 // order.
644 UniqueVector<GlobalVariable*> KernelArgVarOrdinal;
645
646 // For each kernel argument type, record the kernel arg global variables
647 // generated for that type, the function in which that variable was most
648 // recently used, and the binding number it took. For reproducibility,
649 // we track things by ordinal number (rather than pointer), and we use a
650 // std::set rather than DenseSet since std::set maintains an ordering.
651 // Each tuple is the ordinals of the kernel function, the binding number,
652 // and the ordinal of the kernal-arg-var.
653 //
654 // This table lets us reuse module-scope StorageBuffer variables between
655 // different kernels.
656 DenseMap<Type *, std::set<std::tuple<unsigned, unsigned, unsigned>>>
657 GVarsForType;
658
David Neto22f144c2017-06-12 14:26:21 -0400659 for (Function &F : M) {
660 // Handle kernel function first.
661 if (F.isDeclaration() || F.getCallingConv() != CallingConv::SPIR_KERNEL) {
662 continue;
663 }
David Neto26aaf622017-10-23 18:11:53 -0400664 KernelOrdinal.insert(&F);
David Neto22f144c2017-06-12 14:26:21 -0400665
666 for (BasicBlock &BB : F) {
667 for (Instruction &I : BB) {
668 if (I.getOpcode() == Instruction::ZExt ||
669 I.getOpcode() == Instruction::SExt ||
670 I.getOpcode() == Instruction::UIToFP) {
671 // If there is zext with i1 type, it will be changed to OpSelect. The
672 // OpSelect needs constant 0 and 1 so the constants are added here.
673
674 auto OpTy = I.getOperand(0)->getType();
675
676 if (OpTy->isIntegerTy(1) ||
677 (OpTy->isVectorTy() &&
678 OpTy->getVectorElementType()->isIntegerTy(1))) {
679 if (I.getOpcode() == Instruction::ZExt) {
680 APInt One(32, 1);
681 FindConstant(Constant::getNullValue(I.getType()));
682 FindConstant(Constant::getIntegerValue(I.getType(), One));
683 } else if (I.getOpcode() == Instruction::SExt) {
684 APInt MinusOne(32, UINT64_MAX, true);
685 FindConstant(Constant::getNullValue(I.getType()));
686 FindConstant(Constant::getIntegerValue(I.getType(), MinusOne));
687 } else {
688 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
689 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
690 }
691 }
692 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
693 Function *Callee = Call->getCalledFunction();
694
695 // Handle image type specially.
696 if (Callee->getName().equals(
697 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
698 Callee->getName().equals(
699 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
700 TypeMapType &OpImageTypeMap = getImageTypeMap();
701 Type *ImageTy =
702 Call->getArgOperand(0)->getType()->getPointerElementType();
703 OpImageTypeMap[ImageTy] = 0;
704
705 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
706 }
David Neto5c22a252018-03-15 16:07:41 -0400707
708 if (NeedsIVec2.find(Callee->getName()) != NeedsIVec2.end()) {
709 FindType(VectorType::get(Type::getInt32Ty(Context), 2));
710 }
David Neto22f144c2017-06-12 14:26:21 -0400711 }
712 }
713 }
714
715 if (M.getTypeByName("opencl.image2d_ro_t") ||
716 M.getTypeByName("opencl.image2d_wo_t") ||
717 M.getTypeByName("opencl.image3d_ro_t") ||
718 M.getTypeByName("opencl.image3d_wo_t")) {
719 // Assume Image type's sampled type is float type.
720 FindType(Type::getFloatTy(Context));
721 }
722
723 if (const MDNode *MD =
724 dyn_cast<Function>(&F)->getMetadata("reqd_work_group_size")) {
725 // We generate constants if the WorkgroupSize builtin is being used.
726 if (HasWorkGroupBuiltin) {
727 // Collect constant information for work group size.
728 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(0)));
729 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(1)));
730 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(2)));
731 }
732 }
733
734 // Wrap up all argument types with struct type and create global variables
735 // with them.
736 bool HasArgUser = false;
737 unsigned Idx = 0;
738
739 for (const Argument &Arg : F.args()) {
740 Type *ArgTy = Arg.getType();
David Neto22f144c2017-06-12 14:26:21 -0400741
David Netoe439d702018-03-23 13:14:08 -0700742 // The pointee type of the module scope variable we will make.
743 Type *GVTy = nullptr;
David Neto22f144c2017-06-12 14:26:21 -0400744
745 Type *TmpArgTy = ArgTy;
746
747 // sampler_t and image types have pointer type of struct type with
David Netoe439d702018-03-23 13:14:08 -0700748 // opaque type as field. Extract the struct type. It will be used by
749 // global variable for argument.
David Neto22f144c2017-06-12 14:26:21 -0400750 bool IsSamplerType = false;
751 bool IsImageType = false;
752 if (PointerType *TmpArgPTy = dyn_cast<PointerType>(TmpArgTy)) {
753 if (StructType *STy =
754 dyn_cast<StructType>(TmpArgPTy->getElementType())) {
755 if (STy->isOpaque()) {
756 if (STy->getName().equals("opencl.sampler_t")) {
David Neto22f144c2017-06-12 14:26:21 -0400757 IsSamplerType = true;
758 TmpArgTy = STy;
759 } else if (STy->getName().equals("opencl.image2d_ro_t") ||
760 STy->getName().equals("opencl.image2d_wo_t") ||
761 STy->getName().equals("opencl.image3d_ro_t") ||
762 STy->getName().equals("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -0400763 IsImageType = true;
764 TmpArgTy = STy;
765 } else {
766 llvm_unreachable("Argument has opaque type unsupported???");
767 }
768 }
769 }
770 }
771
David Netoe439d702018-03-23 13:14:08 -0700772 // Determine the address space for the module-scope variable.
773 unsigned AddrSpace = AddressSpace::Global;
774 if (IsSamplerType || IsImageType) {
775 AddrSpace = AddressSpace::UniformConstant;
776 } else if (PointerType *ArgPTy = dyn_cast<PointerType>(ArgTy)) {
777 AddrSpace = ArgPTy->getAddressSpace();
David Neto482550a2018-03-24 05:21:07 -0700778 } else if (clspv::Option::PodArgsInUniformBuffer()) {
David Netoe439d702018-03-23 13:14:08 -0700779 // Use a uniform buffer for POD arguments.
780 AddrSpace = AddressSpace::Uniform;
781 }
782
David Neto22f144c2017-06-12 14:26:21 -0400783 // LLVM's pointer type is distinguished by address space but we need to
784 // regard constant and global address space as same here. If pointer
785 // type has constant address space, generate new pointer type
786 // temporarily to check previous struct type for argument.
787 if (PointerType *TmpArgPTy = dyn_cast<PointerType>(TmpArgTy)) {
David Netoe439d702018-03-23 13:14:08 -0700788 if (TmpArgPTy->getAddressSpace() == AddressSpace::Constant) {
David Neto22f144c2017-06-12 14:26:21 -0400789 TmpArgTy = PointerType::get(TmpArgPTy->getElementType(),
790 AddressSpace::Global);
791 }
792 }
793
794 if (IsSamplerType || IsImageType) {
795 GVTy = TmpArgTy;
796 } else if (ArgTyMap.count(TmpArgTy)) {
797 // If there are arguments handled previously, use its type.
798 GVTy = ArgTyMap[TmpArgTy];
799 } else {
800 // Wrap up argument type with struct type.
David Neto83add0a2017-10-23 15:30:59 -0400801 // Reuse struct types where possible.
David Neto7b2abea2017-10-23 20:02:02 -0400802 SmallVector<Type*,1> members{ArgTy};
David Neto83add0a2017-10-23 15:30:59 -0400803 StructType *STy = StructType::get(Context, members);
David Neto22f144c2017-06-12 14:26:21 -0400804
805 GVTy = STy;
806 ArgTyMap[TmpArgTy] = STy;
807 }
808
809 // In order to build type map between llvm type and spirv id, LLVM
810 // global variable is needed. It has llvm type and other instructions
811 // can access it with its type.
David Neto26aaf622017-10-23 18:11:53 -0400812 //
813 // Reuse a global variable if it was created for a different entry point.
814
815 // Returns a new global variable for this kernel argument, and remembers
816 // it in KernelArgVarOrdinal.
817 auto make_gvar = [&]() {
818 auto result = new GlobalVariable(
819 M, GVTy, false, GlobalValue::ExternalLinkage, UndefValue::get(GVTy),
820 F.getName() + ".arg." + std::to_string(Idx), nullptr,
821 GlobalValue::ThreadLocalMode::NotThreadLocal, AddrSpace);
822 KernelArgVarOrdinal.insert(result);
823 return result;
824 };
825
826 // Make a new variable if there was none for this type, or if we can
827 // reuse one created for a different function but not yet reused for
828 // the current function, *and* the binding is the same.
829 // Always make a new variable if we're forcing distinct descriptor sets.
830 GlobalVariable *GV = nullptr;
831 auto which_set = GVarsForType.find(GVTy);
832 if (IsSamplerType || IsImageType || which_set == GVarsForType.end() ||
David Neto482550a2018-03-24 05:21:07 -0700833 clspv::Option::DistinctKernelDescriptorSets()) {
David Neto26aaf622017-10-23 18:11:53 -0400834 GV = make_gvar();
835 } else {
836 auto &set = which_set->second;
837 // Reuse a variable if it was associated with a different function.
838 for (auto iter = set.begin(), end = set.end();
839 iter != end; ++iter) {
840 const unsigned fn_ordinal = std::get<0>(*iter);
841 const unsigned binding = std::get<1>(*iter);
842 if (fn_ordinal != KernelOrdinal.idFor(&F) && binding == Idx) {
843 GV = KernelArgVarOrdinal[std::get<2>(*iter)];
844 // Remove it from the set. We'll add it back later.
845 set.erase(iter);
846 break;
847 }
848 }
849 if (!GV) {
850 GV = make_gvar();
851 }
852 }
853 assert(GV);
854 GVarsForType[GVTy].insert(std::make_tuple(KernelOrdinal.idFor(&F), Idx,
855 KernelArgVarOrdinal.idFor(GV)));
David Neto22f144c2017-06-12 14:26:21 -0400856
857 // Generate type info for argument global variable.
David Neto26aaf622017-10-23 18:11:53 -0400858 FindType(GV->getType());
David Neto22f144c2017-06-12 14:26:21 -0400859
David Neto26aaf622017-10-23 18:11:53 -0400860 ArgGVMap[&Arg] = GV;
861
862 Idx++;
David Neto22f144c2017-06-12 14:26:21 -0400863
864 // Generate pointer type of argument type for OpAccessChain of argument.
865 if (!Arg.use_empty()) {
866 if (!isa<PointerType>(ArgTy)) {
David Netoe439d702018-03-23 13:14:08 -0700867 auto ty = PointerType::get(ArgTy, AddrSpace);
868 FindType(ty);
David Neto22f144c2017-06-12 14:26:21 -0400869 }
870 HasArgUser = true;
871 }
872 }
873
874 if (HasArgUser) {
875 // Generate constant 0 for OpAccessChain of argument.
876 Type *IdxTy = Type::getInt32Ty(Context);
877 FindConstant(ConstantInt::get(IdxTy, 0));
878 FindType(IdxTy);
879 }
880
881 // Collect types' information from function.
882 FindTypePerFunc(F);
883
884 // Collect constant information from function.
885 FindConstantPerFunc(F);
886 }
887
888 for (Function &F : M) {
889 // Handle non-kernel functions.
890 if (F.isDeclaration() || F.getCallingConv() == CallingConv::SPIR_KERNEL) {
891 continue;
892 }
893
894 for (BasicBlock &BB : F) {
895 for (Instruction &I : BB) {
896 if (I.getOpcode() == Instruction::ZExt ||
897 I.getOpcode() == Instruction::SExt ||
898 I.getOpcode() == Instruction::UIToFP) {
899 // If there is zext with i1 type, it will be changed to OpSelect. The
900 // OpSelect needs constant 0 and 1 so the constants are added here.
901
902 auto OpTy = I.getOperand(0)->getType();
903
904 if (OpTy->isIntegerTy(1) ||
905 (OpTy->isVectorTy() &&
906 OpTy->getVectorElementType()->isIntegerTy(1))) {
907 if (I.getOpcode() == Instruction::ZExt) {
908 APInt One(32, 1);
909 FindConstant(Constant::getNullValue(I.getType()));
910 FindConstant(Constant::getIntegerValue(I.getType(), One));
911 } else if (I.getOpcode() == Instruction::SExt) {
912 APInt MinusOne(32, UINT64_MAX, true);
913 FindConstant(Constant::getNullValue(I.getType()));
914 FindConstant(Constant::getIntegerValue(I.getType(), MinusOne));
915 } else {
916 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
917 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
918 }
919 }
920 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
921 Function *Callee = Call->getCalledFunction();
922
923 // Handle image type specially.
924 if (Callee->getName().equals(
925 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
926 Callee->getName().equals(
927 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
928 TypeMapType &OpImageTypeMap = getImageTypeMap();
929 Type *ImageTy =
930 Call->getArgOperand(0)->getType()->getPointerElementType();
931 OpImageTypeMap[ImageTy] = 0;
932
933 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
934 }
935 }
936 }
937 }
938
939 if (M.getTypeByName("opencl.image2d_ro_t") ||
940 M.getTypeByName("opencl.image2d_wo_t") ||
941 M.getTypeByName("opencl.image3d_ro_t") ||
942 M.getTypeByName("opencl.image3d_wo_t")) {
943 // Assume Image type's sampled type is float type.
944 FindType(Type::getFloatTy(Context));
945 }
946
947 // Collect types' information from function.
948 FindTypePerFunc(F);
949
950 // Collect constant information from function.
951 FindConstantPerFunc(F);
952 }
953}
954
955bool SPIRVProducerPass::FindExtInst(Module &M) {
956 LLVMContext &Context = M.getContext();
957 bool HasExtInst = false;
958
959 for (Function &F : M) {
960 for (BasicBlock &BB : F) {
961 for (Instruction &I : BB) {
962 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
963 Function *Callee = Call->getCalledFunction();
964 // Check whether this call is for extend instructions.
David Neto3fbb4072017-10-16 11:28:14 -0400965 auto callee_name = Callee->getName();
966 const glsl::ExtInst EInst = getExtInstEnum(callee_name);
967 const glsl::ExtInst IndirectEInst =
968 getIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -0400969
David Neto3fbb4072017-10-16 11:28:14 -0400970 HasExtInst |=
971 (EInst != kGlslExtInstBad) || (IndirectEInst != kGlslExtInstBad);
972
973 if (IndirectEInst) {
974 // Register extra constants if needed.
975
976 // Registers a type and constant for computing the result of the
977 // given instruction. If the result of the instruction is a vector,
978 // then make a splat vector constant with the same number of
979 // elements.
980 auto register_constant = [this, &I](Constant *constant) {
981 FindType(constant->getType());
982 FindConstant(constant);
983 if (auto *vectorTy = dyn_cast<VectorType>(I.getType())) {
984 // Register the splat vector of the value with the same
985 // width as the result of the instruction.
986 auto *vec_constant = ConstantVector::getSplat(
987 static_cast<unsigned>(vectorTy->getNumElements()),
988 constant);
989 FindConstant(vec_constant);
990 FindType(vec_constant->getType());
991 }
992 };
993 switch (IndirectEInst) {
994 case glsl::ExtInstFindUMsb:
995 // clz needs OpExtInst and OpISub with constant 31, or splat
996 // vector of 31. Add it to the constant list here.
997 register_constant(
998 ConstantInt::get(Type::getInt32Ty(Context), 31));
999 break;
1000 case glsl::ExtInstAcos:
1001 case glsl::ExtInstAsin:
1002 case glsl::ExtInstAtan2:
1003 // We need 1/pi for acospi, asinpi, atan2pi.
1004 register_constant(
1005 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
1006 break;
1007 default:
1008 assert(false && "internally inconsistent");
1009 }
David Neto22f144c2017-06-12 14:26:21 -04001010 }
1011 }
1012 }
1013 }
1014 }
1015
1016 return HasExtInst;
1017}
1018
1019void SPIRVProducerPass::FindTypePerGlobalVar(GlobalVariable &GV) {
1020 // Investigate global variable's type.
1021 FindType(GV.getType());
1022}
1023
1024void SPIRVProducerPass::FindTypePerFunc(Function &F) {
1025 // Investigate function's type.
1026 FunctionType *FTy = F.getFunctionType();
1027
1028 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
1029 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
1030 // Handle function with global constant parameters.
1031 if (GlobalConstFuncTyMap.count(FTy)) {
1032 uint32_t GVCstArgIdx = GlobalConstFuncTypeMap[FTy].second;
1033 SmallVector<Type *, 4> NewFuncParamTys;
1034 for (unsigned i = 0; i < FTy->getNumParams(); i++) {
1035 Type *ParamTy = FTy->getParamType(i);
1036 if (i == GVCstArgIdx) {
1037 Type *EleTy = ParamTy->getPointerElementType();
1038 ParamTy = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1039 }
1040
1041 NewFuncParamTys.push_back(ParamTy);
1042 }
1043
1044 FunctionType *NewFTy =
1045 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1046 GlobalConstFuncTyMap[FTy] = std::make_pair(NewFTy, GVCstArgIdx);
1047 FTy = NewFTy;
1048 }
1049
1050 FindType(FTy);
1051 } else {
1052 // As kernel functions do not have parameters, create new function type and
1053 // add it to type map.
1054 SmallVector<Type *, 4> NewFuncParamTys;
1055 FunctionType *NewFTy =
1056 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1057 FindType(NewFTy);
1058 }
1059
1060 // Investigate instructions' type in function body.
1061 for (BasicBlock &BB : F) {
1062 for (Instruction &I : BB) {
1063 if (isa<ShuffleVectorInst>(I)) {
1064 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1065 // Ignore type for mask of shuffle vector instruction.
1066 if (i == 2) {
1067 continue;
1068 }
1069
1070 Value *Op = I.getOperand(i);
1071 if (!isa<MetadataAsValue>(Op)) {
1072 FindType(Op->getType());
1073 }
1074 }
1075
1076 FindType(I.getType());
1077 continue;
1078 }
1079
1080 // Work through the operands of the instruction.
1081 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1082 Value *const Op = I.getOperand(i);
1083 // If any of the operands is a constant, find the type!
1084 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1085 FindType(Op->getType());
1086 }
1087 }
1088
1089 for (Use &Op : I.operands()) {
1090 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1091 // Avoid to check call instruction's type.
1092 break;
1093 }
1094 if (!isa<MetadataAsValue>(&Op)) {
1095 FindType(Op->getType());
1096 continue;
1097 }
1098 }
1099
1100 CallInst *Call = dyn_cast<CallInst>(&I);
1101
1102 // We don't want to track the type of this call as we are going to replace
1103 // it.
1104 if (Call && ("__translate_sampler_initializer" ==
1105 Call->getCalledFunction()->getName())) {
1106 continue;
1107 }
1108
1109 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1110 // If gep's base operand has ModuleScopePrivate address space, make gep
1111 // return ModuleScopePrivate address space.
1112 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate) {
1113 // Add pointer type with private address space for global constant to
1114 // type list.
1115 Type *EleTy = I.getType()->getPointerElementType();
1116 Type *NewPTy =
1117 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1118
1119 FindType(NewPTy);
1120 continue;
1121 }
1122 }
1123
1124 FindType(I.getType());
1125 }
1126 }
1127}
1128
1129void SPIRVProducerPass::FindType(Type *Ty) {
1130 TypeList &TyList = getTypeList();
1131
1132 if (0 != TyList.idFor(Ty)) {
1133 return;
1134 }
1135
1136 if (Ty->isPointerTy()) {
1137 auto AddrSpace = Ty->getPointerAddressSpace();
1138 if ((AddressSpace::Constant == AddrSpace) ||
1139 (AddressSpace::Global == AddrSpace)) {
1140 auto PointeeTy = Ty->getPointerElementType();
1141
1142 if (PointeeTy->isStructTy() &&
1143 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1144 FindType(PointeeTy);
1145 auto ActualPointerTy =
1146 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1147 FindType(ActualPointerTy);
1148 return;
1149 }
1150 }
1151 }
1152
1153 // OpTypeArray has constant and we need to support type of the constant.
1154 if (isa<ArrayType>(Ty)) {
1155 LLVMContext &Context = Ty->getContext();
1156 FindType(Type::getInt32Ty(Context));
1157 }
1158
1159 for (Type *SubTy : Ty->subtypes()) {
1160 FindType(SubTy);
1161 }
1162
1163 TyList.insert(Ty);
1164}
1165
1166void SPIRVProducerPass::FindConstantPerGlobalVar(GlobalVariable &GV) {
1167 // If the global variable has a (non undef) initializer.
1168 if (GV.hasInitializer() && !isa<UndefValue>(GV.getInitializer())) {
1169 FindConstant(GV.getInitializer());
1170 }
1171}
1172
1173void SPIRVProducerPass::FindConstantPerFunc(Function &F) {
1174 // Investigate constants in function body.
1175 for (BasicBlock &BB : F) {
1176 for (Instruction &I : BB) {
1177 CallInst *Call = dyn_cast<CallInst>(&I);
1178
1179 if (Call && ("__translate_sampler_initializer" ==
1180 Call->getCalledFunction()->getName())) {
1181 // We've handled these constants elsewhere, so skip it.
1182 continue;
1183 }
1184
1185 if (isa<AllocaInst>(I)) {
1186 // Alloca instruction has constant for the number of element. Ignore it.
1187 continue;
1188 } else if (isa<ShuffleVectorInst>(I)) {
1189 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1190 // Ignore constant for mask of shuffle vector instruction.
1191 if (i == 2) {
1192 continue;
1193 }
1194
1195 if (isa<Constant>(I.getOperand(i)) &&
1196 !isa<GlobalValue>(I.getOperand(i))) {
1197 FindConstant(I.getOperand(i));
1198 }
1199 }
1200
1201 continue;
1202 } else if (isa<InsertElementInst>(I)) {
1203 // Handle InsertElement with <4 x i8> specially.
1204 Type *CompositeTy = I.getOperand(0)->getType();
1205 if (is4xi8vec(CompositeTy)) {
1206 LLVMContext &Context = CompositeTy->getContext();
1207 if (isa<Constant>(I.getOperand(0))) {
1208 FindConstant(I.getOperand(0));
1209 }
1210
1211 if (isa<Constant>(I.getOperand(1))) {
1212 FindConstant(I.getOperand(1));
1213 }
1214
1215 // Add mask constant 0xFF.
1216 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1217 FindConstant(CstFF);
1218
1219 // Add shift amount constant.
1220 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
1221 uint64_t Idx = CI->getZExtValue();
1222 Constant *CstShiftAmount =
1223 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1224 FindConstant(CstShiftAmount);
1225 }
1226
1227 continue;
1228 }
1229
1230 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1231 // Ignore constant for index of InsertElement instruction.
1232 if (i == 2) {
1233 continue;
1234 }
1235
1236 if (isa<Constant>(I.getOperand(i)) &&
1237 !isa<GlobalValue>(I.getOperand(i))) {
1238 FindConstant(I.getOperand(i));
1239 }
1240 }
1241
1242 continue;
1243 } else if (isa<ExtractElementInst>(I)) {
1244 // Handle ExtractElement with <4 x i8> specially.
1245 Type *CompositeTy = I.getOperand(0)->getType();
1246 if (is4xi8vec(CompositeTy)) {
1247 LLVMContext &Context = CompositeTy->getContext();
1248 if (isa<Constant>(I.getOperand(0))) {
1249 FindConstant(I.getOperand(0));
1250 }
1251
1252 // Add mask constant 0xFF.
1253 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1254 FindConstant(CstFF);
1255
1256 // Add shift amount constant.
1257 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1258 uint64_t Idx = CI->getZExtValue();
1259 Constant *CstShiftAmount =
1260 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1261 FindConstant(CstShiftAmount);
1262 } else {
1263 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
1264 FindConstant(Cst8);
1265 }
1266
1267 continue;
1268 }
1269
1270 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1271 // Ignore constant for index of ExtractElement instruction.
1272 if (i == 1) {
1273 continue;
1274 }
1275
1276 if (isa<Constant>(I.getOperand(i)) &&
1277 !isa<GlobalValue>(I.getOperand(i))) {
1278 FindConstant(I.getOperand(i));
1279 }
1280 }
1281
1282 continue;
1283 } else if ((Instruction::Xor == I.getOpcode()) && I.getType()->isIntegerTy(1)) {
1284 // 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
1285 bool foundConstantTrue = false;
1286 for (Use &Op : I.operands()) {
1287 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1288 auto CI = cast<ConstantInt>(Op);
1289
1290 if (CI->isZero() || foundConstantTrue) {
1291 // 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.
1292 FindConstant(Op);
1293 } else {
1294 foundConstantTrue = true;
1295 }
1296 }
1297 }
1298
1299 continue;
David Netod2de94a2017-08-28 17:27:47 -04001300 } else if (isa<TruncInst>(I)) {
1301 // For truncation to i8 we mask against 255.
1302 Type *ToTy = I.getType();
1303 if (8u == ToTy->getPrimitiveSizeInBits()) {
1304 LLVMContext &Context = ToTy->getContext();
1305 Constant *Cst255 = ConstantInt::get(Type::getInt32Ty(Context), 0xff);
1306 FindConstant(Cst255);
1307 }
1308 // Fall through.
Neil Henning39672102017-09-29 14:33:13 +01001309 } else if (isa<AtomicRMWInst>(I)) {
1310 LLVMContext &Context = I.getContext();
1311
1312 FindConstant(
1313 ConstantInt::get(Type::getInt32Ty(Context), spv::ScopeDevice));
1314 FindConstant(ConstantInt::get(
1315 Type::getInt32Ty(Context),
1316 spv::MemorySemanticsUniformMemoryMask |
1317 spv::MemorySemanticsSequentiallyConsistentMask));
David Neto22f144c2017-06-12 14:26:21 -04001318 }
1319
1320 for (Use &Op : I.operands()) {
1321 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1322 FindConstant(Op);
1323 }
1324 }
1325 }
1326 }
1327}
1328
1329void SPIRVProducerPass::FindConstant(Value *V) {
David Neto22f144c2017-06-12 14:26:21 -04001330 ValueList &CstList = getConstantList();
1331
David Netofb9a7972017-08-25 17:08:24 -04001332 // If V is already tracked, ignore it.
1333 if (0 != CstList.idFor(V)) {
David Neto22f144c2017-06-12 14:26:21 -04001334 return;
1335 }
1336
1337 Constant *Cst = cast<Constant>(V);
1338
1339 // Handle constant with <4 x i8> type specially.
1340 Type *CstTy = Cst->getType();
1341 if (is4xi8vec(CstTy)) {
1342 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001343 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001344 }
1345 }
1346
1347 if (Cst->getNumOperands()) {
1348 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end(); I != E;
1349 ++I) {
1350 FindConstant(*I);
1351 }
1352
David Netofb9a7972017-08-25 17:08:24 -04001353 CstList.insert(Cst);
David Neto22f144c2017-06-12 14:26:21 -04001354 return;
1355 } else if (const ConstantDataSequential *CDS =
1356 dyn_cast<ConstantDataSequential>(Cst)) {
1357 // Add constants for each element to constant list.
1358 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
1359 Constant *EleCst = CDS->getElementAsConstant(i);
1360 FindConstant(EleCst);
1361 }
1362 }
1363
1364 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001365 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001366 }
1367}
1368
1369spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1370 switch (AddrSpace) {
1371 default:
1372 llvm_unreachable("Unsupported OpenCL address space");
1373 case AddressSpace::Private:
1374 return spv::StorageClassFunction;
1375 case AddressSpace::Global:
1376 case AddressSpace::Constant:
1377 return spv::StorageClassStorageBuffer;
1378 case AddressSpace::Input:
1379 return spv::StorageClassInput;
1380 case AddressSpace::Local:
1381 return spv::StorageClassWorkgroup;
1382 case AddressSpace::UniformConstant:
1383 return spv::StorageClassUniformConstant;
David Netoe439d702018-03-23 13:14:08 -07001384 case AddressSpace::Uniform: // For POD kernel args.
1385 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001386 case AddressSpace::ModuleScopePrivate:
1387 return spv::StorageClassPrivate;
1388 }
1389}
1390
1391spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1392 return StringSwitch<spv::BuiltIn>(Name)
1393 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1394 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1395 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1396 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1397 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
1398 .Default(spv::BuiltInMax);
1399}
1400
1401void SPIRVProducerPass::GenerateExtInstImport() {
1402 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1403 uint32_t &ExtInstImportID = getOpExtInstImportID();
1404
1405 //
1406 // Generate OpExtInstImport.
1407 //
1408 // Ops[0] ... Ops[n] = Name (Literal String)
1409 SPIRVOperandList Ops;
1410
1411 SPIRVOperand *Name =
1412 new SPIRVOperand(SPIRVOperandType::LITERAL_STRING, "GLSL.std.450");
1413 Ops.push_back(Name);
1414
1415 size_t NameWordSize = (Name->getLiteralStr().size() + 1) / 4;
1416 assert(NameWordSize < (UINT16_MAX - 2));
1417 if ((Name->getLiteralStr().size() + 1) % 4) {
1418 NameWordSize += 1;
1419 }
1420
1421 uint16_t WordCount = static_cast<uint16_t>(2 + NameWordSize);
1422 ExtInstImportID = nextID;
1423
1424 SPIRVInstruction *Inst =
1425 new SPIRVInstruction(WordCount, spv::OpExtInstImport, nextID++, Ops);
1426 SPIRVInstList.push_back(Inst);
1427}
1428
1429void SPIRVProducerPass::GenerateSPIRVTypes(const DataLayout &DL) {
1430 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1431 ValueMapType &VMap = getValueMap();
1432 ValueMapType &AllocatedVMap = getAllocatedValueMap();
1433 ValueToValueMapTy &ArgGVMap = getArgumentGVMap();
1434
1435 // Map for OpTypeRuntimeArray. If argument has pointer type, 2 spirv type
1436 // instructions are generated. They are OpTypePointer and OpTypeRuntimeArray.
1437 DenseMap<Type *, uint32_t> OpRuntimeTyMap;
1438
1439 for (Type *Ty : getTypeList()) {
1440 // Update TypeMap with nextID for reference later.
1441 TypeMap[Ty] = nextID;
1442
1443 switch (Ty->getTypeID()) {
1444 default: {
1445 Ty->print(errs());
1446 llvm_unreachable("Unsupported type???");
1447 break;
1448 }
1449 case Type::MetadataTyID:
1450 case Type::LabelTyID: {
1451 // Ignore these types.
1452 break;
1453 }
1454 case Type::PointerTyID: {
1455 PointerType *PTy = cast<PointerType>(Ty);
1456 unsigned AddrSpace = PTy->getAddressSpace();
1457
1458 // For the purposes of our Vulkan SPIR-V type system, constant and global
1459 // are conflated.
1460 bool UseExistingOpTypePointer = false;
1461 if (AddressSpace::Constant == AddrSpace) {
1462 AddrSpace = AddressSpace::Global;
1463
1464 // Check to see if we already created this type (for instance, if we had
1465 // a constant <type>* and a global <type>*, the type would be created by
1466 // one of these types, and shared by both).
1467 auto GlobalTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1468 if (0 < TypeMap.count(GlobalTy)) {
1469 TypeMap[PTy] = TypeMap[GlobalTy];
David Netoe439d702018-03-23 13:14:08 -07001470 UseExistingOpTypePointer = true;
David Neto22f144c2017-06-12 14:26:21 -04001471 break;
1472 }
1473 } else if (AddressSpace::Global == AddrSpace) {
1474 AddrSpace = AddressSpace::Constant;
1475
1476 // Check to see if we already created this type (for instance, if we had
1477 // a constant <type>* and a global <type>*, the type would be created by
1478 // one of these types, and shared by both).
1479 auto ConstantTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1480 if (0 < TypeMap.count(ConstantTy)) {
1481 TypeMap[PTy] = TypeMap[ConstantTy];
1482 UseExistingOpTypePointer = true;
1483 }
1484 }
1485
1486 bool IsOpTypeRuntimeArray = false;
1487 bool HasArgUser = false;
1488
1489 for (auto ArgGV : ArgGVMap) {
1490 auto Arg = ArgGV.first;
1491
1492 Type *ArgTy = Arg->getType();
1493 if (ArgTy == PTy) {
1494 if (AddrSpace != AddressSpace::UniformConstant) {
1495 IsOpTypeRuntimeArray = true;
1496 }
1497
1498 for (auto U : Arg->users()) {
1499 if (!isa<GetElementPtrInst>(U) || (U->getType() == PTy)) {
1500 HasArgUser = true;
1501 break;
1502 }
1503 }
1504 }
1505 }
1506
1507 if ((!IsOpTypeRuntimeArray || HasArgUser) && !UseExistingOpTypePointer) {
1508 //
1509 // Generate OpTypePointer.
1510 //
1511
1512 // OpTypePointer
1513 // Ops[0] = Storage Class
1514 // Ops[1] = Element Type ID
1515 SPIRVOperandList Ops;
1516
1517 spv::StorageClass StorageClass = GetStorageClass(AddrSpace);
1518
1519 SPIRVOperand *StorageClassOp =
1520 new SPIRVOperand(SPIRVOperandType::NUMBERID, StorageClass);
1521 Ops.push_back(StorageClassOp);
1522
1523 uint32_t EleTyID = lookupType(PTy->getElementType());
1524 SPIRVOperand *EleTyOp =
1525 new SPIRVOperand(SPIRVOperandType::NUMBERID, EleTyID);
1526 Ops.push_back(EleTyOp);
1527
1528 spv::Op Opcode = spv::OpTypePointer;
1529 uint16_t WordCount = 4;
1530
1531 SPIRVInstruction *Inst =
1532 new SPIRVInstruction(WordCount, Opcode, nextID++, Ops);
1533 SPIRVInstList.push_back(Inst);
1534 }
1535
1536 if (IsOpTypeRuntimeArray) {
1537 //
1538 // Generate OpTypeRuntimeArray.
1539 //
1540
1541 // OpTypeRuntimeArray
1542 // Ops[0] = Element Type ID
1543 SPIRVOperandList Ops;
1544
1545 uint32_t EleTyID = lookupType(PTy->getElementType());
1546 SPIRVOperand *EleTyOp =
1547 new SPIRVOperand(SPIRVOperandType::NUMBERID, EleTyID);
1548 Ops.push_back(EleTyOp);
1549
1550 spv::Op Opcode = spv::OpTypeRuntimeArray;
1551 uint16_t WordCount = 3;
1552
1553 uint32_t OpTypeRuntimeArrayID = nextID;
1554 assert(0 == OpRuntimeTyMap.count(Ty));
1555 OpRuntimeTyMap[Ty] = nextID;
1556
1557 SPIRVInstruction *Inst =
1558 new SPIRVInstruction(WordCount, Opcode, nextID++, Ops);
1559 SPIRVInstList.push_back(Inst);
1560
1561 // Generate OpDecorate.
1562 auto DecoInsertPoint =
1563 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
1564 [](SPIRVInstruction *Inst) -> bool {
1565 return Inst->getOpcode() != spv::OpDecorate &&
1566 Inst->getOpcode() != spv::OpMemberDecorate &&
1567 Inst->getOpcode() != spv::OpExtInstImport;
1568 });
1569
1570 // Ops[0] = Target ID
1571 // Ops[1] = Decoration (ArrayStride)
1572 // Ops[2] = Stride Number(Literal Number)
1573 Ops.clear();
1574
1575 SPIRVOperand *PTyIDOp =
1576 new SPIRVOperand(SPIRVOperandType::NUMBERID, OpTypeRuntimeArrayID);
1577 Ops.push_back(PTyIDOp);
1578
1579 SPIRVOperand *DecoOp = new SPIRVOperand(SPIRVOperandType::NUMBERID,
1580 spv::DecorationArrayStride);
1581 Ops.push_back(DecoOp);
1582
1583 std::vector<uint32_t> LiteralNum;
1584 Type *EleTy = PTy->getElementType();
Neil Henning39672102017-09-29 14:33:13 +01001585 LiteralNum.push_back(static_cast<uint32_t>(DL.getTypeAllocSize(EleTy)));
David Neto22f144c2017-06-12 14:26:21 -04001586 SPIRVOperand *ArrayStrideOp =
1587 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
1588 Ops.push_back(ArrayStrideOp);
1589
1590 SPIRVInstruction *DecoInst =
1591 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, Ops);
1592 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
1593 }
1594 break;
1595 }
1596 case Type::StructTyID: {
1597 LLVMContext &Context = Ty->getContext();
1598
1599 StructType *STy = cast<StructType>(Ty);
1600
1601 // Handle sampler type.
1602 if (STy->isOpaque()) {
1603 if (STy->getName().equals("opencl.sampler_t")) {
1604 //
1605 // Generate OpTypeSampler
1606 //
1607 // Empty Ops.
1608 SPIRVOperandList Ops;
1609
1610 SPIRVInstruction *Inst =
1611 new SPIRVInstruction(2, spv::OpTypeSampler, nextID++, Ops);
1612 SPIRVInstList.push_back(Inst);
1613 break;
1614 } else if (STy->getName().equals("opencl.image2d_ro_t") ||
1615 STy->getName().equals("opencl.image2d_wo_t") ||
1616 STy->getName().equals("opencl.image3d_ro_t") ||
1617 STy->getName().equals("opencl.image3d_wo_t")) {
1618 //
1619 // Generate OpTypeImage
1620 //
1621 // Ops[0] = Sampled Type ID
1622 // Ops[1] = Dim ID
1623 // Ops[2] = Depth (Literal Number)
1624 // Ops[3] = Arrayed (Literal Number)
1625 // Ops[4] = MS (Literal Number)
1626 // Ops[5] = Sampled (Literal Number)
1627 // Ops[6] = Image Format ID
1628 //
1629 SPIRVOperandList Ops;
1630
1631 // TODO: Changed Sampled Type according to situations.
1632 uint32_t SampledTyID = lookupType(Type::getFloatTy(Context));
1633 SPIRVOperand *SampledTyIDOp =
1634 new SPIRVOperand(SPIRVOperandType::NUMBERID, SampledTyID);
1635 Ops.push_back(SampledTyIDOp);
1636
1637 spv::Dim DimID = spv::Dim2D;
1638 if (STy->getName().equals("opencl.image3d_ro_t") ||
1639 STy->getName().equals("opencl.image3d_wo_t")) {
1640 DimID = spv::Dim3D;
1641 }
1642 SPIRVOperand *DimIDOp =
1643 new SPIRVOperand(SPIRVOperandType::NUMBERID, DimID);
1644 Ops.push_back(DimIDOp);
1645
1646 // TODO: Set up Depth.
1647 std::vector<uint32_t> LiteralNum;
1648 LiteralNum.push_back(0);
1649 SPIRVOperand *DepthOp =
1650 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
1651 Ops.push_back(DepthOp);
1652
1653 // TODO: Set up Arrayed.
1654 LiteralNum.clear();
1655 LiteralNum.push_back(0);
1656 SPIRVOperand *ArrayedOp =
1657 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
1658 Ops.push_back(ArrayedOp);
1659
1660 // TODO: Set up MS.
1661 LiteralNum.clear();
1662 LiteralNum.push_back(0);
1663 SPIRVOperand *MSOp =
1664 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
1665 Ops.push_back(MSOp);
1666
1667 // TODO: Set up Sampled.
1668 //
1669 // From Spec
1670 //
1671 // 0 indicates this is only known at run time, not at compile time
1672 // 1 indicates will be used with sampler
1673 // 2 indicates will be used without a sampler (a storage image)
1674 uint32_t Sampled = 1;
1675 if (STy->getName().equals("opencl.image2d_wo_t") ||
1676 STy->getName().equals("opencl.image3d_wo_t")) {
1677 Sampled = 2;
1678 }
1679 LiteralNum.clear();
1680 LiteralNum.push_back(Sampled);
1681 SPIRVOperand *SampledOp =
1682 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
1683 Ops.push_back(SampledOp);
1684
1685 // TODO: Set up Image Format.
1686 SPIRVOperand *ImageFormatOp = new SPIRVOperand(
1687 SPIRVOperandType::NUMBERID, spv::ImageFormatUnknown);
1688 Ops.push_back(ImageFormatOp);
1689
1690 SPIRVInstruction *Inst =
1691 new SPIRVInstruction(9, spv::OpTypeImage, nextID++, Ops);
1692 SPIRVInstList.push_back(Inst);
1693 break;
1694 }
1695 }
1696
1697 //
1698 // Generate OpTypeStruct
1699 //
1700 // Ops[0] ... Ops[n] = Member IDs
1701 SPIRVOperandList Ops;
1702
1703 for (auto *EleTy : STy->elements()) {
1704 uint32_t EleTyID = lookupType(EleTy);
1705
1706 // Check OpTypeRuntimeArray.
1707 if (isa<PointerType>(EleTy)) {
1708 for (auto ArgGV : ArgGVMap) {
1709 Type *ArgTy = ArgGV.first->getType();
1710 if (ArgTy == EleTy) {
1711 assert(0 != OpRuntimeTyMap.count(EleTy));
1712 EleTyID = OpRuntimeTyMap[EleTy];
1713 }
1714 }
1715 }
1716
1717 SPIRVOperand *EleTyOp =
1718 new SPIRVOperand(SPIRVOperandType::NUMBERID, EleTyID);
1719 Ops.push_back(EleTyOp);
1720 }
1721
1722 uint16_t WordCount = static_cast<uint16_t>(2 + Ops.size());
1723 uint32_t STyID = nextID;
1724
1725 SPIRVInstruction *Inst =
1726 new SPIRVInstruction(WordCount, spv::OpTypeStruct, nextID++, Ops);
1727 SPIRVInstList.push_back(Inst);
1728
1729 // Generate OpMemberDecorate.
1730 auto DecoInsertPoint =
1731 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
1732 [](SPIRVInstruction *Inst) -> bool {
1733 return Inst->getOpcode() != spv::OpDecorate &&
1734 Inst->getOpcode() != spv::OpMemberDecorate &&
1735 Inst->getOpcode() != spv::OpExtInstImport;
1736 });
1737
David Netoc463b372017-08-10 15:32:21 -04001738 const auto StructLayout = DL.getStructLayout(STy);
1739
David Neto22f144c2017-06-12 14:26:21 -04001740 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
1741 MemberIdx++) {
1742 // Ops[0] = Structure Type ID
1743 // Ops[1] = Member Index(Literal Number)
1744 // Ops[2] = Decoration (Offset)
1745 // Ops[3] = Byte Offset (Literal Number)
1746 Ops.clear();
1747
1748 SPIRVOperand *STyIDOp =
1749 new SPIRVOperand(SPIRVOperandType::NUMBERID, STyID);
1750 Ops.push_back(STyIDOp);
1751
1752 std::vector<uint32_t> LiteralNum;
1753 LiteralNum.push_back(MemberIdx);
1754 SPIRVOperand *MemberIdxOp =
1755 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
1756 Ops.push_back(MemberIdxOp);
1757
1758 SPIRVOperand *DecoOp =
1759 new SPIRVOperand(SPIRVOperandType::NUMBERID, spv::DecorationOffset);
1760 Ops.push_back(DecoOp);
1761
1762 LiteralNum.clear();
David Netoc463b372017-08-10 15:32:21 -04001763 const auto ByteOffset =
1764 uint32_t(StructLayout->getElementOffset(MemberIdx));
David Neto22f144c2017-06-12 14:26:21 -04001765 LiteralNum.push_back(ByteOffset);
1766 SPIRVOperand *ByteOffsetOp =
1767 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
1768 Ops.push_back(ByteOffsetOp);
1769
1770 SPIRVInstruction *DecoInst =
1771 new SPIRVInstruction(5, spv::OpMemberDecorate, 0 /* No id */, Ops);
1772 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04001773 }
1774
1775 // Generate OpDecorate.
1776 for (auto ArgGV : ArgGVMap) {
1777 Type *ArgGVTy = ArgGV.second->getType();
1778 PointerType *PTy = cast<PointerType>(ArgGVTy);
1779 Type *ArgTy = PTy->getElementType();
1780
1781 // Struct type from argument is already distinguished with the other
1782 // struct types on llvm types. As a result, if current processing struct
1783 // type is same with argument type, we can generate OpDecorate with
1784 // Block or BufferBlock.
1785 if (ArgTy == STy) {
1786 // Ops[0] = Target ID
1787 // Ops[1] = Decoration (Block or BufferBlock)
1788 Ops.clear();
1789
1790 SPIRVOperand *STyIDOp =
1791 new SPIRVOperand(SPIRVOperandType::NUMBERID, STyID);
1792 Ops.push_back(STyIDOp);
1793
David Neto6e392822017-08-04 14:06:10 -04001794 // Use Block decorations with StorageBuffer storage class.
1795 const spv::Decoration Deco = spv::DecorationBlock;
David Neto22f144c2017-06-12 14:26:21 -04001796
1797 SPIRVOperand *DecoOp =
1798 new SPIRVOperand(SPIRVOperandType::NUMBERID, Deco);
1799 Ops.push_back(DecoOp);
1800
1801 SPIRVInstruction *DecoInst =
1802 new SPIRVInstruction(3, spv::OpDecorate, 0 /* No id */, Ops);
1803 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
1804 break;
1805 }
1806 }
1807 break;
1808 }
1809 case Type::IntegerTyID: {
1810 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
1811
1812 if (BitWidth == 1) {
1813 SPIRVInstruction *Inst =
1814 new SPIRVInstruction(2, spv::OpTypeBool, nextID++, {});
1815 SPIRVInstList.push_back(Inst);
1816 } else {
1817 // i8 is added to TypeMap as i32.
David Neto391aeb12017-08-26 15:51:58 -04001818 // No matter what LLVM type is requested first, always alias the
1819 // second one's SPIR-V type to be the same as the one we generated
1820 // first.
Neil Henning39672102017-09-29 14:33:13 +01001821 unsigned aliasToWidth = 0;
David Neto22f144c2017-06-12 14:26:21 -04001822 if (BitWidth == 8) {
David Neto391aeb12017-08-26 15:51:58 -04001823 aliasToWidth = 32;
David Neto22f144c2017-06-12 14:26:21 -04001824 BitWidth = 32;
David Neto391aeb12017-08-26 15:51:58 -04001825 } else if (BitWidth == 32) {
1826 aliasToWidth = 8;
1827 }
1828 if (aliasToWidth) {
1829 Type* otherType = Type::getIntNTy(Ty->getContext(), aliasToWidth);
1830 auto where = TypeMap.find(otherType);
1831 if (where == TypeMap.end()) {
1832 // Go ahead and make it, but also map the other type to it.
1833 TypeMap[otherType] = nextID;
1834 } else {
1835 // Alias this SPIR-V type the existing type.
1836 TypeMap[Ty] = where->second;
1837 break;
1838 }
David Neto22f144c2017-06-12 14:26:21 -04001839 }
1840
1841 SPIRVOperand *Ops[2] = {
1842 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, BitWidth),
1843 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, 0u)};
1844
1845 SPIRVInstList.push_back(
1846 new SPIRVInstruction(4, spv::OpTypeInt, nextID++, Ops));
1847 }
1848 break;
1849 }
1850 case Type::HalfTyID:
1851 case Type::FloatTyID:
1852 case Type::DoubleTyID: {
1853 SPIRVOperand *WidthOp = new SPIRVOperand(
1854 SPIRVOperandType::LITERAL_INTEGER, Ty->getPrimitiveSizeInBits());
1855
1856 SPIRVInstList.push_back(
1857 new SPIRVInstruction(3, spv::OpTypeFloat, nextID++, WidthOp));
1858 break;
1859 }
1860 case Type::ArrayTyID: {
1861 LLVMContext &Context = Ty->getContext();
1862 ArrayType *ArrTy = cast<ArrayType>(Ty);
1863 //
1864 // Generate OpConstant and OpTypeArray.
1865 //
1866
1867 //
1868 // Generate OpConstant for array length.
1869 //
1870 // Ops[0] = Result Type ID
1871 // Ops[1] .. Ops[n] = Values LiteralNumber
1872 SPIRVOperandList Ops;
1873
1874 Type *LengthTy = Type::getInt32Ty(Context);
1875 uint32_t ResTyID = lookupType(LengthTy);
1876 SPIRVOperand *ResTyOp =
1877 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
1878 Ops.push_back(ResTyOp);
1879
1880 uint64_t Length = ArrTy->getArrayNumElements();
1881 assert(Length < UINT32_MAX);
1882 std::vector<uint32_t> LiteralNum;
1883 LiteralNum.push_back(static_cast<uint32_t>(Length));
1884 SPIRVOperand *ValOp =
1885 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
1886 Ops.push_back(ValOp);
1887
1888 // Add constant for length to constant list.
1889 Constant *CstLength = ConstantInt::get(LengthTy, Length);
1890 AllocatedVMap[CstLength] = nextID;
1891 VMap[CstLength] = nextID;
1892 uint32_t LengthID = nextID;
1893
1894 SPIRVInstruction *CstInst =
1895 new SPIRVInstruction(4, spv::OpConstant, nextID++, Ops);
1896 SPIRVInstList.push_back(CstInst);
1897
1898 //
1899 // Generate OpTypeArray.
1900 //
1901 // Ops[0] = Element Type ID
1902 // Ops[1] = Array Length Constant ID
1903 Ops.clear();
1904
1905 uint32_t EleTyID = lookupType(ArrTy->getElementType());
1906 SPIRVOperand *EleTyOp =
1907 new SPIRVOperand(SPIRVOperandType::NUMBERID, EleTyID);
1908 Ops.push_back(EleTyOp);
1909
1910 SPIRVOperand *LengthOp =
1911 new SPIRVOperand(SPIRVOperandType::NUMBERID, LengthID);
1912 Ops.push_back(LengthOp);
1913
1914 // Update TypeMap with nextID.
1915 TypeMap[Ty] = nextID;
1916
1917 SPIRVInstruction *ArrayInst =
1918 new SPIRVInstruction(4, spv::OpTypeArray, nextID++, Ops);
1919 SPIRVInstList.push_back(ArrayInst);
1920 break;
1921 }
1922 case Type::VectorTyID: {
1923 // <4 x i8> is changed to i32.
1924 LLVMContext &Context = Ty->getContext();
1925 if (Ty->getVectorElementType() == Type::getInt8Ty(Context)) {
1926 if (Ty->getVectorNumElements() == 4) {
1927 TypeMap[Ty] = lookupType(Ty->getVectorElementType());
1928 break;
1929 } else {
1930 Ty->print(errs());
1931 llvm_unreachable("Support above i8 vector type");
1932 }
1933 }
1934
1935 // Ops[0] = Component Type ID
1936 // Ops[1] = Component Count (Literal Number)
1937 SPIRVOperand *Ops[2] = {
1938 new SPIRVOperand(SPIRVOperandType::NUMBERID,
1939 lookupType(Ty->getVectorElementType())),
1940 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER,
1941 Ty->getVectorNumElements())};
1942
1943 SPIRVInstList.push_back(
1944 new SPIRVInstruction(4, spv::OpTypeVector, nextID++, Ops));
1945 break;
1946 }
1947 case Type::VoidTyID: {
1948 SPIRVInstruction *Inst =
1949 new SPIRVInstruction(2, spv::OpTypeVoid, nextID++, {});
1950 SPIRVInstList.push_back(Inst);
1951 break;
1952 }
1953 case Type::FunctionTyID: {
1954 // Generate SPIRV instruction for function type.
1955 FunctionType *FTy = cast<FunctionType>(Ty);
1956
1957 // Ops[0] = Return Type ID
1958 // Ops[1] ... Ops[n] = Parameter Type IDs
1959 SPIRVOperandList Ops;
1960
1961 // Find SPIRV instruction for return type
1962 uint32_t RetTyID = lookupType(FTy->getReturnType());
1963
1964 SPIRVOperand *RetTyOp =
1965 new SPIRVOperand(SPIRVOperandType::NUMBERID, RetTyID);
1966 Ops.push_back(RetTyOp);
1967
1968 // Find SPIRV instructions for parameter types
1969 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
1970 // Find SPIRV instruction for parameter type.
1971 auto ParamTy = FTy->getParamType(k);
1972 if (ParamTy->isPointerTy()) {
1973 auto PointeeTy = ParamTy->getPointerElementType();
1974 if (PointeeTy->isStructTy() &&
1975 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1976 ParamTy = PointeeTy;
1977 }
1978 }
1979
1980 uint32_t ParamTyID = lookupType(ParamTy);
1981 SPIRVOperand *ParamTyOp =
1982 new SPIRVOperand(SPIRVOperandType::NUMBERID, ParamTyID);
1983 Ops.push_back(ParamTyOp);
1984 }
1985
1986 // Return type id is included in operand list.
1987 uint16_t WordCount = static_cast<uint16_t>(2 + Ops.size());
1988
1989 SPIRVInstruction *Inst =
1990 new SPIRVInstruction(WordCount, spv::OpTypeFunction, nextID++, Ops);
1991 SPIRVInstList.push_back(Inst);
1992 break;
1993 }
1994 }
1995 }
1996
1997 // Generate OpTypeSampledImage.
1998 TypeMapType &OpImageTypeMap = getImageTypeMap();
1999 for (auto &ImageType : OpImageTypeMap) {
2000 //
2001 // Generate OpTypeSampledImage.
2002 //
2003 // Ops[0] = Image Type ID
2004 //
2005 SPIRVOperandList Ops;
2006
2007 Type *ImgTy = ImageType.first;
2008 uint32_t ImgTyID = TypeMap[ImgTy];
2009 SPIRVOperand *ImgTyOp =
2010 new SPIRVOperand(SPIRVOperandType::NUMBERID, ImgTyID);
2011 Ops.push_back(ImgTyOp);
2012
2013 // Update OpImageTypeMap.
2014 ImageType.second = nextID;
2015
2016 SPIRVInstruction *Inst =
2017 new SPIRVInstruction(3, spv::OpTypeSampledImage, nextID++, Ops);
2018 SPIRVInstList.push_back(Inst);
2019 }
2020}
2021
2022void SPIRVProducerPass::GenerateSPIRVConstants() {
2023 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2024 ValueMapType &VMap = getValueMap();
2025 ValueMapType &AllocatedVMap = getAllocatedValueMap();
2026 ValueList &CstList = getConstantList();
David Neto482550a2018-03-24 05:21:07 -07002027 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04002028
2029 for (uint32_t i = 0; i < CstList.size(); i++) {
David Netofb9a7972017-08-25 17:08:24 -04002030 // UniqueVector ids are 1-based.
2031 Constant *Cst = cast<Constant>(CstList[i+1]);
David Neto22f144c2017-06-12 14:26:21 -04002032
2033 // OpTypeArray's constant was already generated.
David Netofb9a7972017-08-25 17:08:24 -04002034 if (AllocatedVMap.find_as(Cst) != AllocatedVMap.end()) {
David Neto22f144c2017-06-12 14:26:21 -04002035 continue;
2036 }
2037
David Netofb9a7972017-08-25 17:08:24 -04002038 // Set ValueMap with nextID for reference later.
David Neto22f144c2017-06-12 14:26:21 -04002039 VMap[Cst] = nextID;
2040
2041 //
2042 // Generate OpConstant.
2043 //
2044
2045 // Ops[0] = Result Type ID
2046 // Ops[1] .. Ops[n] = Values LiteralNumber
2047 SPIRVOperandList Ops;
2048
2049 uint32_t ResTyID = lookupType(Cst->getType());
2050 SPIRVOperand *ResTyIDOp =
2051 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
2052 Ops.push_back(ResTyIDOp);
2053
2054 std::vector<uint32_t> LiteralNum;
2055 uint16_t WordCount = 0;
2056 spv::Op Opcode = spv::OpNop;
2057
2058 if (isa<UndefValue>(Cst)) {
2059 // Ops[0] = Result Type ID
David Netoc66b3352017-10-20 14:28:46 -04002060 Opcode = spv::OpUndef;
2061 if (hack_undef) {
2062 Type *type = Cst->getType();
2063 if (type->isFPOrFPVectorTy() || type->isIntOrIntVectorTy()) {
2064 Opcode = spv::OpConstantNull;
2065 }
2066 }
David Neto22f144c2017-06-12 14:26:21 -04002067 WordCount = 3;
2068 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
2069 unsigned BitWidth = CI->getBitWidth();
2070 if (BitWidth == 1) {
2071 // If the bitwidth of constant is 1, generate OpConstantTrue or
2072 // OpConstantFalse.
2073 if (CI->getZExtValue()) {
2074 // Ops[0] = Result Type ID
2075 Opcode = spv::OpConstantTrue;
2076 } else {
2077 // Ops[0] = Result Type ID
2078 Opcode = spv::OpConstantFalse;
2079 }
2080 WordCount = 3;
2081 } else {
2082 auto V = CI->getZExtValue();
2083 LiteralNum.push_back(V & 0xFFFFFFFF);
2084
2085 if (BitWidth > 32) {
2086 LiteralNum.push_back(V >> 32);
2087 }
2088
2089 Opcode = spv::OpConstant;
2090 WordCount = static_cast<uint16_t>(3 + LiteralNum.size());
2091
2092 SPIRVOperand *CstValue =
2093 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
2094 Ops.push_back(CstValue);
2095 }
2096 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2097 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2098 Type *CFPTy = CFP->getType();
2099 if (CFPTy->isFloatTy()) {
2100 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2101 } else {
2102 CFPTy->print(errs());
2103 llvm_unreachable("Implement this ConstantFP Type");
2104 }
2105
2106 Opcode = spv::OpConstant;
2107 WordCount = static_cast<uint16_t>(3 + LiteralNum.size());
2108
2109 SPIRVOperand *CstValue =
2110 new SPIRVOperand(SPIRVOperandType::LITERAL_FLOAT, LiteralNum);
2111 Ops.push_back(CstValue);
2112 } else if (isa<ConstantDataSequential>(Cst) &&
2113 cast<ConstantDataSequential>(Cst)->isString()) {
2114 Cst->print(errs());
2115 llvm_unreachable("Implement this Constant");
2116
2117 } else if (const ConstantDataSequential *CDS =
2118 dyn_cast<ConstantDataSequential>(Cst)) {
David Neto49351ac2017-08-26 17:32:20 -04002119 // Let's convert <4 x i8> constant to int constant specially.
2120 // This case occurs when all the values are specified as constant
2121 // ints.
2122 Type *CstTy = Cst->getType();
2123 if (is4xi8vec(CstTy)) {
2124 LLVMContext &Context = CstTy->getContext();
2125
2126 //
2127 // Generate OpConstant with OpTypeInt 32 0.
2128 //
Neil Henning39672102017-09-29 14:33:13 +01002129 uint32_t IntValue = 0;
2130 for (unsigned k = 0; k < 4; k++) {
2131 const uint64_t Val = CDS->getElementAsInteger(k);
David Neto49351ac2017-08-26 17:32:20 -04002132 IntValue = (IntValue << 8) | (Val & 0xffu);
2133 }
2134
2135 Type *i32 = Type::getInt32Ty(Context);
2136 Constant *CstInt = ConstantInt::get(i32, IntValue);
2137 // If this constant is already registered on VMap, use it.
2138 if (VMap.count(CstInt)) {
2139 uint32_t CstID = VMap[CstInt];
2140 VMap[Cst] = CstID;
2141 continue;
2142 }
2143
2144 LiteralNum.push_back(IntValue);
2145 SPIRVOperand *CstValue =
2146 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
2147 Ops.push_back(CstValue);
2148
2149 SPIRVInstruction *CstInst =
2150 new SPIRVInstruction(4, spv::OpConstant, nextID++, Ops);
2151 SPIRVInstList.push_back(CstInst);
2152
2153 continue;
2154 }
2155
2156 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002157 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
2158 Constant *EleCst = CDS->getElementAsConstant(k);
2159 uint32_t EleCstID = VMap[EleCst];
2160 SPIRVOperand *EleCstIDOp =
2161 new SPIRVOperand(SPIRVOperandType::NUMBERID, EleCstID);
2162 Ops.push_back(EleCstIDOp);
2163 }
2164
2165 Opcode = spv::OpConstantComposite;
2166 WordCount = static_cast<uint16_t>(3 + CDS->getNumElements());
2167 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2168 // Let's convert <4 x i8> constant to int constant specially.
David Neto49351ac2017-08-26 17:32:20 -04002169 // This case occurs when at least one of the values is an undef.
David Neto22f144c2017-06-12 14:26:21 -04002170 Type *CstTy = Cst->getType();
2171 if (is4xi8vec(CstTy)) {
2172 LLVMContext &Context = CstTy->getContext();
2173
2174 //
2175 // Generate OpConstant with OpTypeInt 32 0.
2176 //
Neil Henning39672102017-09-29 14:33:13 +01002177 uint32_t IntValue = 0;
David Neto22f144c2017-06-12 14:26:21 -04002178 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2179 I != E; ++I) {
2180 uint64_t Val = 0;
David Neto49351ac2017-08-26 17:32:20 -04002181 const Value* CV = *I;
Neil Henning39672102017-09-29 14:33:13 +01002182 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2183 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002184 }
David Neto49351ac2017-08-26 17:32:20 -04002185 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002186 }
2187
David Neto49351ac2017-08-26 17:32:20 -04002188 Type *i32 = Type::getInt32Ty(Context);
2189 Constant *CstInt = ConstantInt::get(i32, IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002190 // If this constant is already registered on VMap, use it.
2191 if (VMap.count(CstInt)) {
2192 uint32_t CstID = VMap[CstInt];
2193 VMap[Cst] = CstID;
David Neto19a1bad2017-08-25 15:01:41 -04002194 continue;
David Neto22f144c2017-06-12 14:26:21 -04002195 }
2196
David Neto49351ac2017-08-26 17:32:20 -04002197 LiteralNum.push_back(IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002198 SPIRVOperand *CstValue =
2199 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
2200 Ops.push_back(CstValue);
2201
2202 SPIRVInstruction *CstInst =
2203 new SPIRVInstruction(4, spv::OpConstant, nextID++, Ops);
2204 SPIRVInstList.push_back(CstInst);
2205
David Neto19a1bad2017-08-25 15:01:41 -04002206 continue;
David Neto22f144c2017-06-12 14:26:21 -04002207 }
2208
2209 // We use a constant composite in SPIR-V for our constant aggregate in
2210 // LLVM.
2211 Opcode = spv::OpConstantComposite;
2212 WordCount = static_cast<uint16_t>(3 + CA->getNumOperands());
2213
2214 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
2215 // Look up the ID of the element of this aggregate (which we will
2216 // previously have created a constant for).
2217 uint32_t ElementConstantID = VMap[CA->getAggregateElement(k)];
2218
2219 // And add an operand to the composite we are constructing
2220 Ops.push_back(
2221 new SPIRVOperand(SPIRVOperandType::NUMBERID, ElementConstantID));
2222 }
2223 } else if (Cst->isNullValue()) {
2224 Opcode = spv::OpConstantNull;
2225 WordCount = 3;
2226 } else {
2227 Cst->print(errs());
2228 llvm_unreachable("Unsupported Constant???");
2229 }
2230
2231 SPIRVInstruction *CstInst =
2232 new SPIRVInstruction(WordCount, Opcode, nextID++, Ops);
2233 SPIRVInstList.push_back(CstInst);
2234 }
2235}
2236
2237void SPIRVProducerPass::GenerateSamplers(Module &M) {
2238 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2239 ValueMapType &VMap = getValueMap();
2240
2241 DenseMap<unsigned, unsigned> SamplerLiteralToIDMap;
2242
2243 unsigned BindingIdx = 0;
2244
2245 // Generate the sampler map.
2246 for (auto SamplerLiteral : getSamplerMap()) {
2247 // Generate OpVariable.
2248 //
2249 // GIDOps[0] : Result Type ID
2250 // GIDOps[1] : Storage Class
2251 SPIRVOperandList Ops;
2252
2253 Ops.push_back(
2254 new SPIRVOperand(SPIRVOperandType::NUMBERID, lookupType(SamplerTy)));
2255
2256 spv::StorageClass StorageClass = spv::StorageClassUniformConstant;
2257 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, StorageClass));
2258
2259 SPIRVInstruction *Inst = new SPIRVInstruction(
2260 static_cast<uint16_t>(2 + Ops.size()), spv::OpVariable, nextID, Ops);
2261 SPIRVInstList.push_back(Inst);
2262
David Neto44795152017-07-13 15:45:28 -04002263 SamplerLiteralToIDMap[SamplerLiteral.first] = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04002264
2265 // Find Insert Point for OpDecorate.
2266 auto DecoInsertPoint =
2267 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2268 [](SPIRVInstruction *Inst) -> bool {
2269 return Inst->getOpcode() != spv::OpDecorate &&
2270 Inst->getOpcode() != spv::OpMemberDecorate &&
2271 Inst->getOpcode() != spv::OpExtInstImport;
2272 });
2273
2274 // Ops[0] = Target ID
2275 // Ops[1] = Decoration (DescriptorSet)
2276 // Ops[2] = LiteralNumber according to Decoration
2277 Ops.clear();
2278
David Neto44795152017-07-13 15:45:28 -04002279 SPIRVOperand *ArgIDOp =
2280 new SPIRVOperand(SPIRVOperandType::NUMBERID,
2281 SamplerLiteralToIDMap[SamplerLiteral.first]);
David Neto22f144c2017-06-12 14:26:21 -04002282 Ops.push_back(ArgIDOp);
2283
2284 spv::Decoration Deco = spv::DecorationDescriptorSet;
2285 SPIRVOperand *DecoOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Deco);
2286 Ops.push_back(DecoOp);
2287
David Neto44795152017-07-13 15:45:28 -04002288 descriptorMapOut << "sampler," << SamplerLiteral.first << ",samplerExpr,\""
2289 << SamplerLiteral.second << "\",descriptorSet,0,binding,"
David Netoc2c368d2017-06-30 16:50:17 -04002290 << BindingIdx << "\n";
2291
David Neto22f144c2017-06-12 14:26:21 -04002292 std::vector<uint32_t> LiteralNum;
2293 LiteralNum.push_back(0);
2294 SPIRVOperand *DescSet =
2295 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
2296 Ops.push_back(DescSet);
2297
2298 SPIRVInstruction *DescDecoInst =
2299 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, Ops);
2300 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2301
2302 // Ops[0] = Target ID
2303 // Ops[1] = Decoration (Binding)
2304 // Ops[2] = LiteralNumber according to Decoration
2305 Ops.clear();
2306
2307 Ops.push_back(ArgIDOp);
2308
2309 Deco = spv::DecorationBinding;
2310 DecoOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Deco);
2311 Ops.push_back(DecoOp);
2312
2313 LiteralNum.clear();
2314 LiteralNum.push_back(BindingIdx++);
2315 SPIRVOperand *Binding =
2316 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
2317 Ops.push_back(Binding);
2318
2319 SPIRVInstruction *BindDecoInst =
2320 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, Ops);
2321 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
2322 }
2323
2324 const char *TranslateSamplerFunctionName = "__translate_sampler_initializer";
2325
2326 auto SamplerFunction = M.getFunction(TranslateSamplerFunctionName);
2327
2328 // If there are no uses of the sampler function, no work to do!
2329 if (!SamplerFunction) {
2330 return;
2331 }
2332
2333 // Iterate through the users of the sampler function.
2334 for (auto User : SamplerFunction->users()) {
2335 if (auto CI = dyn_cast<CallInst>(User)) {
2336 // Get the literal used to initialize the sampler.
2337 auto Constant = dyn_cast<ConstantInt>(CI->getArgOperand(0));
2338
2339 if (!Constant) {
2340 CI->getArgOperand(0)->print(errs());
2341 llvm_unreachable("Argument of sampler initializer was non-constant!");
2342 }
2343
2344 auto SamplerLiteral = static_cast<unsigned>(Constant->getZExtValue());
2345
2346 if (0 == SamplerLiteralToIDMap.count(SamplerLiteral)) {
2347 Constant->print(errs());
2348 llvm_unreachable("Sampler literal was not found in sampler map!");
2349 }
2350
2351 // Calls to the sampler literal function to initialize a sampler are
2352 // re-routed to the global variables declared for the sampler.
2353 VMap[CI] = SamplerLiteralToIDMap[SamplerLiteral];
2354 }
2355 }
2356}
2357
2358void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
2359 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2360 ValueMapType &VMap = getValueMap();
2361 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
2362
2363 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2364 Type *Ty = GV.getType();
2365 PointerType *PTy = cast<PointerType>(Ty);
2366
2367 uint32_t InitializerID = 0;
2368
2369 // Workgroup size is handled differently (it goes into a constant)
2370 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2371 std::vector<bool> HasMDVec;
2372 uint32_t PrevXDimCst = 0xFFFFFFFF;
2373 uint32_t PrevYDimCst = 0xFFFFFFFF;
2374 uint32_t PrevZDimCst = 0xFFFFFFFF;
2375 for (Function &Func : *GV.getParent()) {
2376 if (Func.isDeclaration()) {
2377 continue;
2378 }
2379
2380 // We only need to check kernels.
2381 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2382 continue;
2383 }
2384
2385 if (const MDNode *MD =
2386 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2387 uint32_t CurXDimCst = static_cast<uint32_t>(
2388 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2389 uint32_t CurYDimCst = static_cast<uint32_t>(
2390 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2391 uint32_t CurZDimCst = static_cast<uint32_t>(
2392 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2393
2394 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2395 PrevZDimCst == 0xFFFFFFFF) {
2396 PrevXDimCst = CurXDimCst;
2397 PrevYDimCst = CurYDimCst;
2398 PrevZDimCst = CurZDimCst;
2399 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2400 CurZDimCst != PrevZDimCst) {
2401 llvm_unreachable(
2402 "reqd_work_group_size must be the same across all kernels");
2403 } else {
2404 continue;
2405 }
2406
2407 //
2408 // Generate OpConstantComposite.
2409 //
2410 // Ops[0] : Result Type ID
2411 // Ops[1] : Constant size for x dimension.
2412 // Ops[2] : Constant size for y dimension.
2413 // Ops[3] : Constant size for z dimension.
2414 SPIRVOperandList Ops;
2415
2416 uint32_t XDimCstID =
2417 VMap[mdconst::extract<ConstantInt>(MD->getOperand(0))];
2418 uint32_t YDimCstID =
2419 VMap[mdconst::extract<ConstantInt>(MD->getOperand(1))];
2420 uint32_t ZDimCstID =
2421 VMap[mdconst::extract<ConstantInt>(MD->getOperand(2))];
2422
2423 InitializerID = nextID;
2424
2425 Ops.push_back(
2426 new SPIRVOperand(SPIRVOperandType::NUMBERID,
2427 lookupType(Ty->getPointerElementType())));
2428
2429 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, XDimCstID));
2430 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, YDimCstID));
2431 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, ZDimCstID));
2432
2433 SPIRVInstruction *Inst =
2434 new SPIRVInstruction(6, spv::OpConstantComposite, nextID++, Ops);
2435 SPIRVInstList.push_back(Inst);
2436
2437 HasMDVec.push_back(true);
2438 } else {
2439 HasMDVec.push_back(false);
2440 }
2441 }
2442
2443 // Check all kernels have same definitions for work_group_size.
2444 bool HasMD = false;
2445 if (!HasMDVec.empty()) {
2446 HasMD = HasMDVec[0];
2447 for (uint32_t i = 1; i < HasMDVec.size(); i++) {
2448 if (HasMD != HasMDVec[i]) {
2449 llvm_unreachable(
2450 "Kernels should have consistent work group size definition");
2451 }
2452 }
2453 }
2454
2455 // If all kernels do not have metadata for reqd_work_group_size, generate
2456 // OpSpecConstants for x/y/z dimension.
2457 if (!HasMD) {
2458 //
2459 // Generate OpSpecConstants for x/y/z dimension.
2460 //
2461 // Ops[0] : Result Type ID
2462 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
2463 uint32_t XDimCstID = 0;
2464 uint32_t YDimCstID = 0;
2465 uint32_t ZDimCstID = 0;
2466
2467 // X Dimension
2468 SPIRVOperandList Ops;
2469
2470 Ops.push_back(new SPIRVOperand(
2471 SPIRVOperandType::NUMBERID,
2472 lookupType(Ty->getPointerElementType()->getSequentialElementType())));
2473
2474 std::vector<uint32_t> LiteralNum;
2475 LiteralNum.push_back(1);
2476 SPIRVOperand *XDim =
2477 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
2478 Ops.push_back(XDim);
2479
2480 XDimCstID = nextID;
2481 BuiltinDimVec.push_back(XDimCstID);
2482
2483 SPIRVInstruction *XDimCstInst =
2484 new SPIRVInstruction(4, spv::OpSpecConstant, nextID++, Ops);
2485 SPIRVInstList.push_back(XDimCstInst);
2486
2487 // Y Dimension
2488 Ops.clear();
2489
2490 Ops.push_back(new SPIRVOperand(
2491 SPIRVOperandType::NUMBERID,
2492 lookupType(Ty->getPointerElementType()->getSequentialElementType())));
2493
2494 LiteralNum.clear();
2495 LiteralNum.push_back(1);
2496 SPIRVOperand *YDim =
2497 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
2498 Ops.push_back(YDim);
2499
2500 YDimCstID = nextID;
2501 BuiltinDimVec.push_back(YDimCstID);
2502
2503 SPIRVInstruction *YDimCstInst =
2504 new SPIRVInstruction(4, spv::OpSpecConstant, nextID++, Ops);
2505 SPIRVInstList.push_back(YDimCstInst);
2506
2507 // Z Dimension
2508 Ops.clear();
2509
2510 Ops.push_back(new SPIRVOperand(
2511 SPIRVOperandType::NUMBERID,
2512 lookupType(Ty->getPointerElementType()->getSequentialElementType())));
2513
2514 LiteralNum.clear();
2515 LiteralNum.push_back(1);
2516 SPIRVOperand *ZDim =
2517 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
2518 Ops.push_back(ZDim);
2519
2520 ZDimCstID = nextID;
2521 BuiltinDimVec.push_back(ZDimCstID);
2522
2523 SPIRVInstruction *ZDimCstInst =
2524 new SPIRVInstruction(4, spv::OpSpecConstant, nextID++, Ops);
2525 SPIRVInstList.push_back(ZDimCstInst);
2526
2527 //
2528 // Generate OpSpecConstantComposite.
2529 //
2530 // Ops[0] : Result Type ID
2531 // Ops[1] : Constant size for x dimension.
2532 // Ops[2] : Constant size for y dimension.
2533 // Ops[3] : Constant size for z dimension.
2534 InitializerID = nextID;
2535
2536 Ops.clear();
2537
2538 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID,
2539 lookupType(Ty->getPointerElementType())));
2540
2541 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, XDimCstID));
2542 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, YDimCstID));
2543 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, ZDimCstID));
2544
2545 SPIRVInstruction *Inst =
2546 new SPIRVInstruction(6, spv::OpSpecConstantComposite, nextID++, Ops);
2547 SPIRVInstList.push_back(Inst);
2548 }
2549 }
2550
2551 if (GV.hasInitializer()) {
2552 InitializerID = VMap[GV.getInitializer()];
2553 }
2554
2555 VMap[&GV] = nextID;
2556
2557 //
2558 // Generate OpVariable.
2559 //
2560 // GIDOps[0] : Result Type ID
2561 // GIDOps[1] : Storage Class
2562 SPIRVOperandList Ops;
2563
2564 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, lookupType(Ty)));
2565
2566 spv::StorageClass StorageClass = GetStorageClass(PTy->getAddressSpace());
2567 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, StorageClass));
2568
2569 if (0 != InitializerID) {
2570 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, InitializerID));
2571 }
2572
2573 SPIRVInstruction *Inst = new SPIRVInstruction(
2574 static_cast<uint16_t>(2 + Ops.size()), spv::OpVariable, nextID++, Ops);
2575 SPIRVInstList.push_back(Inst);
2576
2577 // If we have a builtin.
2578 if (spv::BuiltInMax != BuiltinType) {
2579 // Find Insert Point for OpDecorate.
2580 auto DecoInsertPoint =
2581 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2582 [](SPIRVInstruction *Inst) -> bool {
2583 return Inst->getOpcode() != spv::OpDecorate &&
2584 Inst->getOpcode() != spv::OpMemberDecorate &&
2585 Inst->getOpcode() != spv::OpExtInstImport;
2586 });
2587 //
2588 // Generate OpDecorate.
2589 //
2590 // DOps[0] = Target ID
2591 // DOps[1] = Decoration (Builtin)
2592 // DOps[2] = BuiltIn ID
2593 uint32_t ResultID;
2594
2595 // WorkgroupSize is different, we decorate the constant composite that has
2596 // its value, rather than the variable that we use to access the value.
2597 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2598 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04002599 // Save both the value and variable IDs for later.
2600 WorkgroupSizeValueID = InitializerID;
2601 WorkgroupSizeVarID = VMap[&GV];
David Neto22f144c2017-06-12 14:26:21 -04002602 } else {
2603 ResultID = VMap[&GV];
2604 }
2605
2606 SPIRVOperandList DOps;
2607 SPIRVOperand *ResultIDOp =
2608 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResultID);
2609 DOps.push_back(ResultIDOp);
2610
2611 spv::Decoration Deco = spv::DecorationBuiltIn;
2612 SPIRVOperand *DecoOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Deco);
2613 DOps.push_back(DecoOp);
2614
2615 SPIRVOperand *Builtin =
2616 new SPIRVOperand(SPIRVOperandType::NUMBERID, BuiltinType);
2617 DOps.push_back(Builtin);
2618
2619 SPIRVInstruction *DescDecoInst =
2620 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, DOps);
2621 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2622 }
2623}
2624
2625void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
2626 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2627 ValueMapType &VMap = getValueMap();
2628 EntryPointVecType &EntryPoints = getEntryPointVec();
2629 ValueToValueMapTy &ArgGVMap = getArgumentGVMap();
2630 ValueMapType &ArgGVIDMap = getArgumentGVIDMap();
2631 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
2632 auto &GlobalConstArgSet = getGlobalConstArgSet();
2633
2634 FunctionType *FTy = F.getFunctionType();
2635
2636 //
2637 // Generate OpVariable and OpDecorate for kernel function with arguments.
2638 //
2639 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
2640
2641 // Find Insert Point for OpDecorate.
2642 auto DecoInsertPoint =
2643 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2644 [](SPIRVInstruction *Inst) -> bool {
2645 return Inst->getOpcode() != spv::OpDecorate &&
2646 Inst->getOpcode() != spv::OpMemberDecorate &&
2647 Inst->getOpcode() != spv::OpExtInstImport;
2648 });
2649
2650 uint32_t DescriptorSetIdx = (0 < getSamplerMap().size()) ? 1u : 0u;
David Neto482550a2018-03-24 05:21:07 -07002651 if (clspv::Option::DistinctKernelDescriptorSets()) {
David Netocd8ca5f2017-10-02 23:34:11 -04002652 for (Function &Func : *F.getParent()) {
2653 if (Func.isDeclaration()) {
2654 continue;
David Neto22f144c2017-06-12 14:26:21 -04002655 }
David Netocd8ca5f2017-10-02 23:34:11 -04002656
2657 if (Func.getCallingConv() == CallingConv::SPIR_KERNEL) {
2658 if (&Func == &F) {
2659 break;
2660 }
2661 DescriptorSetIdx++;
2662 }
David Neto22f144c2017-06-12 14:26:21 -04002663 }
2664 }
2665
David Netoe439d702018-03-23 13:14:08 -07002666 auto remap_arg_kind = [](StringRef argKind) {
David Neto482550a2018-03-24 05:21:07 -07002667 return clspv::Option::PodArgsInUniformBuffer() && argKind.equals("pod")
2668 ? "pod_ubo"
2669 : argKind;
David Netoe439d702018-03-23 13:14:08 -07002670 };
2671
David Neto156783e2017-07-05 15:39:41 -04002672 const auto *ArgMap = F.getMetadata("kernel_arg_map");
2673 // Emit descriptor map entries, if there was explicit metadata
2674 // attached.
2675 if (ArgMap) {
2676 for (const auto &arg : ArgMap->operands()) {
2677 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
David Neto48f56a42017-10-06 16:44:25 -04002678 assert(arg_node->getNumOperands() == 5);
David Neto156783e2017-07-05 15:39:41 -04002679 const auto name =
2680 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
2681 const auto old_index =
2682 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
2683 const auto new_index =
2684 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getZExtValue();
2685 const auto offset =
2686 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
David Neto4feb7a42017-10-06 17:29:42 -04002687 const auto argKind =
David Neto48f56a42017-10-06 16:44:25 -04002688 dyn_cast<MDString>(arg_node->getOperand(4))->getString();
David Neto156783e2017-07-05 15:39:41 -04002689 descriptorMapOut << "kernel," << F.getName() << ",arg," << name
2690 << ",argOrdinal," << old_index << ",descriptorSet,"
2691 << DescriptorSetIdx << ",binding," << new_index
David Netoe439d702018-03-23 13:14:08 -07002692 << ",offset," << offset << ",argKind,"
2693 << remap_arg_kind(argKind) << "\n";
David Neto156783e2017-07-05 15:39:41 -04002694 }
2695 }
2696
David Neto22f144c2017-06-12 14:26:21 -04002697 uint32_t BindingIdx = 0;
2698 for (auto &Arg : F.args()) {
2699 Value *NewGV = ArgGVMap[&Arg];
2700 VMap[&Arg] = VMap[NewGV];
2701 ArgGVIDMap[&Arg] = VMap[&Arg];
2702
David Neto156783e2017-07-05 15:39:41 -04002703 // Emit a descriptor map entry for this arg, in case there was no explicit
2704 // kernel arg mapping metadata.
2705 if (!ArgMap) {
2706 descriptorMapOut << "kernel," << F.getName() << ",arg," << Arg.getName()
2707 << ",argOrdinal," << BindingIdx << ",descriptorSet,"
2708 << DescriptorSetIdx << ",binding," << BindingIdx
David Neto4feb7a42017-10-06 17:29:42 -04002709 << ",offset,0,argKind,"
David Netoe439d702018-03-23 13:14:08 -07002710 << remap_arg_kind(
2711 clspv::GetArgKindForType(Arg.getType()))
2712 << "\n";
David Netoc2c368d2017-06-30 16:50:17 -04002713 }
2714
David Neto26aaf622017-10-23 18:11:53 -04002715 if (GVarWithEmittedBindingInfo.count(NewGV)) {
2716 BindingIdx++;
2717 continue;
2718 }
2719 GVarWithEmittedBindingInfo.insert(NewGV);
2720
David Neto22f144c2017-06-12 14:26:21 -04002721 // Ops[0] = Target ID
2722 // Ops[1] = Decoration (DescriptorSet)
2723 // Ops[2] = LiteralNumber according to Decoration
2724 SPIRVOperandList Ops;
2725
2726 SPIRVOperand *ArgIDOp =
2727 new SPIRVOperand(SPIRVOperandType::NUMBERID, VMap[&Arg]);
2728 Ops.push_back(ArgIDOp);
2729
2730 spv::Decoration Deco = spv::DecorationDescriptorSet;
2731 SPIRVOperand *DecoOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Deco);
2732 Ops.push_back(DecoOp);
2733
2734 std::vector<uint32_t> LiteralNum;
2735 LiteralNum.push_back(DescriptorSetIdx);
2736 SPIRVOperand *DescSet =
2737 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
2738 Ops.push_back(DescSet);
2739
2740 SPIRVInstruction *DescDecoInst =
2741 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, Ops);
2742 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2743
2744 // Ops[0] = Target ID
2745 // Ops[1] = Decoration (Binding)
2746 // Ops[2] = LiteralNumber according to Decoration
2747 Ops.clear();
2748
2749 Ops.push_back(ArgIDOp);
2750
2751 Deco = spv::DecorationBinding;
2752 DecoOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Deco);
2753 Ops.push_back(DecoOp);
2754
2755 LiteralNum.clear();
2756 LiteralNum.push_back(BindingIdx++);
2757 SPIRVOperand *Binding =
2758 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
2759 Ops.push_back(Binding);
2760
2761 SPIRVInstruction *BindDecoInst =
2762 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, Ops);
2763 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
2764
2765 // Handle image type argument.
2766 bool HasReadOnlyImageType = false;
2767 bool HasWriteOnlyImageType = false;
2768 if (PointerType *ArgPTy = dyn_cast<PointerType>(Arg.getType())) {
2769 if (StructType *STy = dyn_cast<StructType>(ArgPTy->getElementType())) {
2770 if (STy->isOpaque()) {
2771 if (STy->getName().equals("opencl.image2d_ro_t") ||
2772 STy->getName().equals("opencl.image3d_ro_t")) {
2773 HasReadOnlyImageType = true;
2774 } else if (STy->getName().equals("opencl.image2d_wo_t") ||
2775 STy->getName().equals("opencl.image3d_wo_t")) {
2776 HasWriteOnlyImageType = true;
2777 }
2778 }
2779 }
2780 }
2781
2782 if (HasReadOnlyImageType || HasWriteOnlyImageType) {
2783 // Ops[0] = Target ID
2784 // Ops[1] = Decoration (NonReadable or NonWritable)
2785 Ops.clear();
2786
2787 ArgIDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, VMap[&Arg]);
2788 Ops.push_back(ArgIDOp);
2789
2790 Deco = spv::DecorationNonReadable;
2791 if (HasReadOnlyImageType) {
2792 Deco = spv::DecorationNonWritable;
2793 }
2794 DecoOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Deco);
2795 Ops.push_back(DecoOp);
2796
2797 DescDecoInst =
2798 new SPIRVInstruction(3, spv::OpDecorate, 0 /* No id */, Ops);
2799 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2800 }
2801
2802 // Handle const address space.
2803 if (NewGV->getType()->getPointerAddressSpace() ==
2804 AddressSpace::Constant) {
2805 // Ops[0] = Target ID
2806 // Ops[1] = Decoration (NonWriteable)
2807 Ops.clear();
2808
2809 Ops.push_back(ArgIDOp);
2810
2811 Deco = spv::DecorationNonWritable;
2812 DecoOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Deco);
2813 Ops.push_back(DecoOp);
2814
2815 BindDecoInst =
2816 new SPIRVInstruction(3, spv::OpDecorate, 0 /* No id */, Ops);
2817 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
2818 }
2819 }
2820 }
2821
2822 //
2823 // Generate OPFunction.
2824 //
2825
2826 // FOps[0] : Result Type ID
2827 // FOps[1] : Function Control
2828 // FOps[2] : Function Type ID
2829 SPIRVOperandList FOps;
2830
2831 // Find SPIRV instruction for return type.
2832 uint32_t RetTyID = lookupType(FTy->getReturnType());
2833 SPIRVOperand *RetTyOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, RetTyID);
2834 FOps.push_back(RetTyOp);
2835
2836 // Check function attributes for SPIRV Function Control.
2837 uint32_t FuncControl = spv::FunctionControlMaskNone;
2838 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
2839 FuncControl |= spv::FunctionControlInlineMask;
2840 }
2841 if (F.hasFnAttribute(Attribute::NoInline)) {
2842 FuncControl |= spv::FunctionControlDontInlineMask;
2843 }
2844 // TODO: Check llvm attribute for Function Control Pure.
2845 if (F.hasFnAttribute(Attribute::ReadOnly)) {
2846 FuncControl |= spv::FunctionControlPureMask;
2847 }
2848 // TODO: Check llvm attribute for Function Control Const.
2849 if (F.hasFnAttribute(Attribute::ReadNone)) {
2850 FuncControl |= spv::FunctionControlConstMask;
2851 }
2852
2853 SPIRVOperand *FunctionControlOp =
2854 new SPIRVOperand(SPIRVOperandType::NUMBERID, FuncControl);
2855 FOps.push_back(FunctionControlOp);
2856
2857 uint32_t FTyID;
2858 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
2859 SmallVector<Type *, 4> NewFuncParamTys;
2860 FunctionType *NewFTy =
2861 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
2862 FTyID = lookupType(NewFTy);
2863 } else {
2864 // Handle function with global constant parameters.
2865 if (GlobalConstFuncTyMap.count(FTy)) {
2866 FTyID = lookupType(GlobalConstFuncTyMap[FTy].first);
2867 } else {
2868 FTyID = lookupType(FTy);
2869 }
2870 }
2871
2872 SPIRVOperand *FTyOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, FTyID);
2873 FOps.push_back(FTyOp);
2874
2875 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
2876 EntryPoints.push_back(std::make_pair(&F, nextID));
2877 }
2878
2879 VMap[&F] = nextID;
2880
David Neto482550a2018-03-24 05:21:07 -07002881 if (clspv::Option::ShowIDs()) {
David Netob05675d2018-02-16 12:37:49 -05002882 errs() << "Function " << F.getName() << " is " << nextID << "\n";
2883 }
David Neto22f144c2017-06-12 14:26:21 -04002884 // Generate SPIRV instruction for function.
2885 SPIRVInstruction *FuncInst =
2886 new SPIRVInstruction(5, spv::OpFunction, nextID++, FOps);
2887 SPIRVInstList.push_back(FuncInst);
2888
2889 //
2890 // Generate OpFunctionParameter for Normal function.
2891 //
2892
2893 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2894 // Iterate Argument for name instead of param type from function type.
2895 unsigned ArgIdx = 0;
2896 for (Argument &Arg : F.args()) {
2897 VMap[&Arg] = nextID;
2898
2899 // ParamOps[0] : Result Type ID
2900 SPIRVOperandList ParamOps;
2901
2902 // Find SPIRV instruction for parameter type.
2903 uint32_t ParamTyID = lookupType(Arg.getType());
2904 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
2905 if (GlobalConstFuncTyMap.count(FTy)) {
2906 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
2907 Type *EleTy = PTy->getPointerElementType();
2908 Type *ArgTy =
2909 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
2910 ParamTyID = lookupType(ArgTy);
2911 GlobalConstArgSet.insert(&Arg);
2912 }
2913 }
2914 }
2915 SPIRVOperand *ParamTyOp =
2916 new SPIRVOperand(SPIRVOperandType::NUMBERID, ParamTyID);
2917 ParamOps.push_back(ParamTyOp);
2918
2919 // Generate SPIRV instruction for parameter.
2920 SPIRVInstruction *ParamInst =
2921 new SPIRVInstruction(3, spv::OpFunctionParameter, nextID++, ParamOps);
2922 SPIRVInstList.push_back(ParamInst);
2923
2924 ArgIdx++;
2925 }
2926 }
2927}
2928
David Neto5c22a252018-03-15 16:07:41 -04002929void SPIRVProducerPass::GenerateModuleInfo(Module& module) {
David Neto22f144c2017-06-12 14:26:21 -04002930 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2931 EntryPointVecType &EntryPoints = getEntryPointVec();
2932 ValueMapType &VMap = getValueMap();
2933 ValueList &EntryPointInterfaces = getEntryPointInterfacesVec();
2934 uint32_t &ExtInstImportID = getOpExtInstImportID();
2935 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
2936
2937 // Set up insert point.
2938 auto InsertPoint = SPIRVInstList.begin();
2939
2940 //
2941 // Generate OpCapability
2942 //
2943 // TODO: Which llvm information is mapped to SPIRV Capapbility?
2944
2945 // Ops[0] = Capability
2946 SPIRVOperandList Ops;
2947
2948 SPIRVInstruction *CapInst = new SPIRVInstruction(
2949 2, spv::OpCapability, 0 /* No id */,
2950 new SPIRVOperand(SPIRVOperandType::NUMBERID, spv::CapabilityShader));
2951 SPIRVInstList.insert(InsertPoint, CapInst);
2952
2953 for (Type *Ty : getTypeList()) {
2954 // Find the i16 type.
2955 if (Ty->isIntegerTy(16)) {
2956 // Generate OpCapability for i16 type.
2957 SPIRVInstList.insert(
2958 InsertPoint,
2959 new SPIRVInstruction(2, spv::OpCapability, 0 /* No id */,
2960 new SPIRVOperand(SPIRVOperandType::NUMBERID,
2961 spv::CapabilityInt16)));
2962 } else if (Ty->isIntegerTy(64)) {
2963 // Generate OpCapability for i64 type.
2964 SPIRVInstList.insert(
2965 InsertPoint,
2966 new SPIRVInstruction(2, spv::OpCapability, 0 /* No id */,
2967 new SPIRVOperand(SPIRVOperandType::NUMBERID,
2968 spv::CapabilityInt64)));
2969 } else if (Ty->isHalfTy()) {
2970 // Generate OpCapability for half type.
2971 SPIRVInstList.insert(
2972 InsertPoint,
2973 new SPIRVInstruction(2, spv::OpCapability, 0 /* No id */,
2974 new SPIRVOperand(SPIRVOperandType::NUMBERID,
2975 spv::CapabilityFloat16)));
2976 } else if (Ty->isDoubleTy()) {
2977 // Generate OpCapability for double type.
2978 SPIRVInstList.insert(
2979 InsertPoint,
2980 new SPIRVInstruction(2, spv::OpCapability, 0 /* No id */,
2981 new SPIRVOperand(SPIRVOperandType::NUMBERID,
2982 spv::CapabilityFloat64)));
2983 } else if (auto *STy = dyn_cast<StructType>(Ty)) {
2984 if (STy->isOpaque()) {
David Neto565571c2017-08-21 12:00:05 -04002985 if (STy->getName().equals("opencl.image2d_wo_t") ||
2986 STy->getName().equals("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04002987 // Generate OpCapability for write only image type.
2988 SPIRVInstList.insert(
2989 InsertPoint,
2990 new SPIRVInstruction(
2991 2, spv::OpCapability, 0 /* No id */,
2992 new SPIRVOperand(
2993 SPIRVOperandType::NUMBERID,
2994 spv::CapabilityStorageImageWriteWithoutFormat)));
2995 }
2996 }
2997 }
2998 }
2999
David Neto5c22a252018-03-15 16:07:41 -04003000 { // OpCapability ImageQuery
3001 bool hasImageQuery = false;
3002 for (const char *imageQuery : {
3003 "_Z15get_image_width14ocl_image2d_ro",
3004 "_Z15get_image_width14ocl_image2d_wo",
3005 "_Z16get_image_height14ocl_image2d_ro",
3006 "_Z16get_image_height14ocl_image2d_wo",
3007 }) {
3008 if (module.getFunction(imageQuery)) {
3009 hasImageQuery = true;
3010 break;
3011 }
3012 }
3013 if (hasImageQuery) {
3014
3015 SPIRVInstruction *ImageQueryCapInst =
3016 new SPIRVInstruction(2, spv::OpCapability, 0 /* No id */,
3017 new SPIRVOperand(SPIRVOperandType::NUMBERID,
3018 spv::CapabilityImageQuery));
3019 SPIRVInstList.insert(InsertPoint, ImageQueryCapInst);
3020 }
3021 }
3022
David Neto22f144c2017-06-12 14:26:21 -04003023 if (hasVariablePointers()) {
3024 //
3025 // Generate OpCapability and OpExtension
3026 //
3027
3028 //
3029 // Generate OpCapability.
3030 //
3031 // Ops[0] = Capability
3032 //
3033 Ops.clear();
3034
3035 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID,
3036 spv::CapabilityVariablePointers));
3037
3038 SPIRVInstList.insert(InsertPoint, new SPIRVInstruction(2, spv::OpCapability,
3039 0 /* No id */, Ops));
3040
3041 //
3042 // Generate OpExtension.
3043 //
3044 // Ops[0] = Name (Literal String)
3045 //
David Netoa772fd12017-08-04 14:17:33 -04003046 for (auto extension : {"SPV_KHR_storage_buffer_storage_class",
3047 "SPV_KHR_variable_pointers"}) {
3048 Ops.clear();
David Neto22f144c2017-06-12 14:26:21 -04003049
David Netoa772fd12017-08-04 14:17:33 -04003050 SPIRVOperand *Name =
3051 new SPIRVOperand(SPIRVOperandType::LITERAL_STRING, extension);
3052 Ops.push_back(Name);
David Neto22f144c2017-06-12 14:26:21 -04003053
David Netoa772fd12017-08-04 14:17:33 -04003054 size_t NameWordSize = (Name->getLiteralStr().size() + 1) / 4;
3055 if ((Name->getLiteralStr().size() + 1) % 4) {
3056 NameWordSize += 1;
3057 }
3058
3059 assert((NameWordSize + 1) < UINT16_MAX);
3060 uint16_t WordCount = static_cast<uint16_t>(1 + NameWordSize);
3061
3062 SPIRVInstruction *ExtensionInst =
3063 new SPIRVInstruction(WordCount, spv::OpExtension, 0 /* No id */, Ops);
3064 SPIRVInstList.insert(InsertPoint, ExtensionInst);
David Neto22f144c2017-06-12 14:26:21 -04003065 }
David Neto22f144c2017-06-12 14:26:21 -04003066 }
3067
3068 if (ExtInstImportID) {
3069 ++InsertPoint;
3070 }
3071
3072 //
3073 // Generate OpMemoryModel
3074 //
3075 // Memory model for Vulkan will always be GLSL450.
3076
3077 // Ops[0] = Addressing Model
3078 // Ops[1] = Memory Model
3079 Ops.clear();
3080 SPIRVOperand *AddrModel =
3081 new SPIRVOperand(SPIRVOperandType::NUMBERID, spv::AddressingModelLogical);
3082 Ops.push_back(AddrModel);
3083
3084 SPIRVOperand *MemModel =
3085 new SPIRVOperand(SPIRVOperandType::NUMBERID, spv::MemoryModelGLSL450);
3086 Ops.push_back(MemModel);
3087
3088 SPIRVInstruction *MemModelInst =
3089 new SPIRVInstruction(3, spv::OpMemoryModel, 0 /* No id */, Ops);
3090 SPIRVInstList.insert(InsertPoint, MemModelInst);
3091
3092 //
3093 // Generate OpEntryPoint
3094 //
3095 for (auto EntryPoint : EntryPoints) {
3096 // Ops[0] = Execution Model
3097 // Ops[1] = EntryPoint ID
3098 // Ops[2] = Name (Literal String)
3099 // ...
3100 //
3101 // TODO: Do we need to consider Interface ID for forward references???
3102 Ops.clear();
3103 SPIRVOperand *ExecModel = new SPIRVOperand(SPIRVOperandType::NUMBERID,
3104 spv::ExecutionModelGLCompute);
3105 Ops.push_back(ExecModel);
3106
3107 SPIRVOperand *EntryPointID =
3108 new SPIRVOperand(SPIRVOperandType::NUMBERID, EntryPoint.second);
3109 Ops.push_back(EntryPointID);
3110
3111 SPIRVOperand *Name = new SPIRVOperand(SPIRVOperandType::LITERAL_STRING,
3112 EntryPoint.first->getName());
3113 Ops.push_back(Name);
3114
3115 size_t NameWordSize = (Name->getLiteralStr().size() + 1) / 4;
3116 if ((Name->getLiteralStr().size() + 1) % 4) {
3117 NameWordSize += 1;
3118 }
3119
3120 assert((3 + NameWordSize) < UINT16_MAX);
3121 uint16_t WordCount = static_cast<uint16_t>(3 + NameWordSize);
3122
3123 for (Value *Interface : EntryPointInterfaces) {
3124 SPIRVOperand *GIDOp =
3125 new SPIRVOperand(SPIRVOperandType::NUMBERID, VMap[Interface]);
3126 Ops.push_back(GIDOp);
3127 WordCount++;
3128 }
3129
3130 SPIRVInstruction *EntryPointInst =
3131 new SPIRVInstruction(WordCount, spv::OpEntryPoint, 0 /* No id */, Ops);
3132 SPIRVInstList.insert(InsertPoint, EntryPointInst);
3133 }
3134
3135 for (auto EntryPoint : EntryPoints) {
3136 if (const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
3137 ->getMetadata("reqd_work_group_size")) {
3138
3139 if (!BuiltinDimVec.empty()) {
3140 llvm_unreachable(
3141 "Kernels should have consistent work group size definition");
3142 }
3143
3144 //
3145 // Generate OpExecutionMode
3146 //
3147
3148 // Ops[0] = Entry Point ID
3149 // Ops[1] = Execution Mode
3150 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
3151 Ops.clear();
3152 SPIRVOperand *EntryPointID =
3153 new SPIRVOperand(SPIRVOperandType::NUMBERID, EntryPoint.second);
3154 Ops.push_back(EntryPointID);
3155
3156 SPIRVOperand *ExecMode = new SPIRVOperand(SPIRVOperandType::NUMBERID,
3157 spv::ExecutionModeLocalSize);
3158 Ops.push_back(ExecMode);
3159
3160 uint32_t XDim = static_cast<uint32_t>(
3161 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3162 uint32_t YDim = static_cast<uint32_t>(
3163 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3164 uint32_t ZDim = static_cast<uint32_t>(
3165 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3166
3167 std::vector<uint32_t> LiteralNum;
3168 LiteralNum.push_back(XDim);
3169 SPIRVOperand *XDimOp =
3170 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
3171 Ops.push_back(XDimOp);
3172
3173 LiteralNum.clear();
3174 LiteralNum.push_back(YDim);
3175 SPIRVOperand *YDimOp =
3176 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
3177 Ops.push_back(YDimOp);
3178
3179 LiteralNum.clear();
3180 LiteralNum.push_back(ZDim);
3181 SPIRVOperand *ZDimOp =
3182 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
3183 Ops.push_back(ZDimOp);
3184
3185 SPIRVInstruction *ExecModeInst =
3186 new SPIRVInstruction(static_cast<uint16_t>(1 + Ops.size()),
3187 spv::OpExecutionMode, 0 /* No id */, Ops);
3188 SPIRVInstList.insert(InsertPoint, ExecModeInst);
3189 }
3190 }
3191
3192 //
3193 // Generate OpSource.
3194 //
3195 // Ops[0] = SourceLanguage ID
3196 // Ops[1] = Version (LiteralNum)
3197 //
3198 Ops.clear();
3199 SPIRVOperand *SourceLanguage =
3200 new SPIRVOperand(SPIRVOperandType::NUMBERID, spv::SourceLanguageOpenCL_C);
3201 Ops.push_back(SourceLanguage);
3202
3203 std::vector<uint32_t> LiteralNum;
3204 LiteralNum.push_back(120);
3205 SPIRVOperand *Version =
3206 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
3207 Ops.push_back(Version);
3208
3209 SPIRVInstruction *OpenSourceInst =
3210 new SPIRVInstruction(3, spv::OpSource, 0 /* No id */, Ops);
3211 SPIRVInstList.insert(InsertPoint, OpenSourceInst);
3212
3213 if (!BuiltinDimVec.empty()) {
3214 //
3215 // Generate OpDecorates for x/y/z dimension.
3216 //
3217 // Ops[0] = Target ID
3218 // Ops[1] = Decoration (SpecId)
3219 // Ops[2] = Specialization Cosntant ID (Literal Number)
3220
3221 // X Dimension
3222 Ops.clear();
3223
3224 SPIRVOperand *TargetID =
3225 new SPIRVOperand(SPIRVOperandType::NUMBERID, BuiltinDimVec[0]);
3226 Ops.push_back(TargetID);
3227
3228 SPIRVOperand *DecoOp =
3229 new SPIRVOperand(SPIRVOperandType::NUMBERID, spv::DecorationSpecId);
3230 Ops.push_back(DecoOp);
3231
3232 LiteralNum.clear();
3233 LiteralNum.push_back(0);
3234 SPIRVOperand *XDim =
3235 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
3236 Ops.push_back(XDim);
3237
3238 SPIRVInstruction *XDimDecoInst =
3239 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, Ops);
3240 SPIRVInstList.insert(InsertPoint, XDimDecoInst);
3241
3242 // Y Dimension
3243 Ops.clear();
3244
3245 TargetID = new SPIRVOperand(SPIRVOperandType::NUMBERID, BuiltinDimVec[1]);
3246 Ops.push_back(TargetID);
3247
3248 DecoOp =
3249 new SPIRVOperand(SPIRVOperandType::NUMBERID, spv::DecorationSpecId);
3250 Ops.push_back(DecoOp);
3251
3252 LiteralNum.clear();
3253 LiteralNum.push_back(1);
3254 SPIRVOperand *YDim =
3255 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
3256 Ops.push_back(YDim);
3257
3258 SPIRVInstruction *YDimDecoInst =
3259 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, Ops);
3260 SPIRVInstList.insert(InsertPoint, YDimDecoInst);
3261
3262 // Z Dimension
3263 Ops.clear();
3264
3265 TargetID = new SPIRVOperand(SPIRVOperandType::NUMBERID, BuiltinDimVec[2]);
3266 Ops.push_back(TargetID);
3267
3268 DecoOp =
3269 new SPIRVOperand(SPIRVOperandType::NUMBERID, spv::DecorationSpecId);
3270 Ops.push_back(DecoOp);
3271
3272 LiteralNum.clear();
3273 LiteralNum.push_back(2);
3274 SPIRVOperand *ZDim =
3275 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
3276 Ops.push_back(ZDim);
3277
3278 SPIRVInstruction *ZDimDecoInst =
3279 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, Ops);
3280 SPIRVInstList.insert(InsertPoint, ZDimDecoInst);
3281 }
3282}
3283
3284void SPIRVProducerPass::GenerateInstForArg(Function &F) {
3285 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3286 ValueMapType &VMap = getValueMap();
3287 Module *Module = F.getParent();
3288 LLVMContext &Context = Module->getContext();
3289 ValueToValueMapTy &ArgGVMap = getArgumentGVMap();
3290
3291 for (Argument &Arg : F.args()) {
3292 if (Arg.use_empty()) {
3293 continue;
3294 }
3295
3296 // Check the type of users of arguments.
3297 bool HasOnlyGEPUse = true;
3298 for (auto *U : Arg.users()) {
3299 if (!isa<GetElementPtrInst>(U) && isa<Instruction>(U)) {
3300 HasOnlyGEPUse = false;
3301 break;
3302 }
3303 }
3304
3305 Type *ArgTy = Arg.getType();
3306
3307 if (PointerType *PTy = dyn_cast<PointerType>(ArgTy)) {
3308 if (StructType *STy = dyn_cast<StructType>(PTy->getElementType())) {
3309 if (STy->isOpaque()) {
3310 // Generate OpLoad for sampler and image types.
3311 if (STy->getName().equals("opencl.sampler_t") ||
3312 STy->getName().equals("opencl.image2d_ro_t") ||
3313 STy->getName().equals("opencl.image2d_wo_t") ||
3314 STy->getName().equals("opencl.image3d_ro_t") ||
3315 STy->getName().equals("opencl.image3d_wo_t")) {
3316 //
3317 // Generate OpLoad.
3318 //
3319 // Ops[0] = Result Type ID
3320 // Ops[1] = Pointer ID
3321 // Ops[2] ... Ops[n] = Optional Memory Access
3322 //
3323 // TODO: Do we need to implement Optional Memory Access???
3324 SPIRVOperandList Ops;
3325
3326 // Use type with address space modified.
3327 ArgTy = ArgGVMap[&Arg]->getType()->getPointerElementType();
3328
3329 uint32_t ResTyID = lookupType(ArgTy);
3330 SPIRVOperand *ResTyIDOp =
3331 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3332 Ops.push_back(ResTyIDOp);
3333
3334 uint32_t PointerID = VMap[&Arg];
3335 SPIRVOperand *PointerIDOp =
3336 new SPIRVOperand(SPIRVOperandType::NUMBERID, PointerID);
3337 Ops.push_back(PointerIDOp);
3338
3339 VMap[&Arg] = nextID;
3340 SPIRVInstruction *Inst =
3341 new SPIRVInstruction(4, spv::OpLoad, nextID++, Ops);
3342 SPIRVInstList.push_back(Inst);
3343 continue;
3344 }
3345 }
3346 }
3347
3348 if (!HasOnlyGEPUse) {
3349 //
3350 // Generate OpAccessChain.
3351 //
3352 // Ops[0] = Result Type ID
3353 // Ops[1] = Base ID
3354 // Ops[2] ... Ops[n] = Indexes ID
3355 SPIRVOperandList Ops;
3356
3357 uint32_t ResTyID = lookupType(ArgTy);
3358 if (!isa<PointerType>(ArgTy)) {
3359 ResTyID = lookupType(PointerType::get(ArgTy, AddressSpace::Global));
3360 }
3361 SPIRVOperand *ResTyOp =
3362 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3363 Ops.push_back(ResTyOp);
3364
3365 uint32_t BaseID = VMap[&Arg];
3366 SPIRVOperand *BaseOp =
3367 new SPIRVOperand(SPIRVOperandType::NUMBERID, BaseID);
3368 Ops.push_back(BaseOp);
3369
3370 Type *IdxTy = Type::getInt32Ty(Context);
3371 uint32_t IndexID = VMap[ConstantInt::get(IdxTy, 0)];
3372 SPIRVOperand *IndexIDOp =
3373 new SPIRVOperand(SPIRVOperandType::NUMBERID, IndexID);
3374 Ops.push_back(IndexIDOp);
3375 Ops.push_back(IndexIDOp);
3376
3377 // Generate SPIRV instruction for argument.
3378 VMap[&Arg] = nextID;
3379 SPIRVInstruction *ArgInst =
3380 new SPIRVInstruction(6, spv::OpAccessChain, nextID++, Ops);
3381 SPIRVInstList.push_back(ArgInst);
3382 } else {
3383 // For GEP uses, generate OpAccessChain with folding GEP ahead of GEP.
3384 // Nothing to do here.
3385 }
3386 } else {
3387 //
3388 // Generate OpAccessChain and OpLoad for non-pointer type argument.
3389 //
3390
3391 //
3392 // Generate OpAccessChain.
3393 //
3394 // Ops[0] = Result Type ID
3395 // Ops[1] = Base ID
3396 // Ops[2] ... Ops[n] = Indexes ID
3397 SPIRVOperandList Ops;
3398
3399 uint32_t ResTyID = lookupType(ArgTy);
3400 if (!isa<PointerType>(ArgTy)) {
David Neto482550a2018-03-24 05:21:07 -07003401 auto AS = clspv::Option::PodArgsInUniformBuffer()
3402 ? AddressSpace::Uniform
3403 : AddressSpace::Global;
David Netoe439d702018-03-23 13:14:08 -07003404 ResTyID = lookupType(PointerType::get(ArgTy, AS));
David Neto22f144c2017-06-12 14:26:21 -04003405 }
3406 SPIRVOperand *ResTyIDOp =
3407 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3408 Ops.push_back(ResTyIDOp);
3409
3410 uint32_t BaseID = VMap[&Arg];
3411 SPIRVOperand *BaseOp =
3412 new SPIRVOperand(SPIRVOperandType::NUMBERID, BaseID);
3413 Ops.push_back(BaseOp);
3414
3415 Type *IdxTy = Type::getInt32Ty(Context);
3416 uint32_t IndexID = VMap[ConstantInt::get(IdxTy, 0)];
3417 SPIRVOperand *IndexIDOp =
3418 new SPIRVOperand(SPIRVOperandType::NUMBERID, IndexID);
3419 Ops.push_back(IndexIDOp);
3420
3421 // Generate SPIRV instruction for argument.
3422 uint32_t PointerID = nextID;
3423 VMap[&Arg] = nextID;
3424 SPIRVInstruction *ArgInst =
3425 new SPIRVInstruction(5, spv::OpAccessChain, nextID++, Ops);
3426 SPIRVInstList.push_back(ArgInst);
3427
3428 //
3429 // Generate OpLoad.
3430 //
3431
3432 // Ops[0] = Result Type ID
3433 // Ops[1] = Pointer ID
3434 // Ops[2] ... Ops[n] = Optional Memory Access
3435 //
3436 // TODO: Do we need to implement Optional Memory Access???
3437 Ops.clear();
3438
3439 ResTyID = lookupType(ArgTy);
3440 ResTyIDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3441 Ops.push_back(ResTyIDOp);
3442
3443 SPIRVOperand *PointerIDOp =
3444 new SPIRVOperand(SPIRVOperandType::NUMBERID, PointerID);
3445 Ops.push_back(PointerIDOp);
3446
3447 VMap[&Arg] = nextID;
3448 SPIRVInstruction *Inst =
3449 new SPIRVInstruction(4, spv::OpLoad, nextID++, Ops);
3450 SPIRVInstList.push_back(Inst);
3451 }
3452 }
3453}
3454
3455void SPIRVProducerPass::GenerateFuncBody(Function &F) {
3456 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3457 ValueMapType &VMap = getValueMap();
3458
3459 bool IsKernel = false;
3460 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3461 IsKernel = true;
3462 }
3463
3464 for (BasicBlock &BB : F) {
3465 // Register BasicBlock to ValueMap.
3466 VMap[&BB] = nextID;
3467
3468 //
3469 // Generate OpLabel for Basic Block.
3470 //
3471 SPIRVOperandList Ops;
3472 SPIRVInstruction *Inst =
3473 new SPIRVInstruction(2, spv::OpLabel, nextID++, Ops);
3474 SPIRVInstList.push_back(Inst);
3475
David Neto6dcd4712017-06-23 11:06:47 -04003476 // OpVariable instructions must come first.
3477 for (Instruction &I : BB) {
3478 if (isa<AllocaInst>(I)) {
3479 GenerateInstruction(I);
3480 }
3481 }
3482
David Neto22f144c2017-06-12 14:26:21 -04003483 if (&BB == &F.getEntryBlock() && IsKernel) {
3484 GenerateInstForArg(F);
3485 }
3486
3487 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003488 if (!isa<AllocaInst>(I)) {
3489 GenerateInstruction(I);
3490 }
David Neto22f144c2017-06-12 14:26:21 -04003491 }
3492 }
3493}
3494
3495spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3496 const std::map<CmpInst::Predicate, spv::Op> Map = {
3497 {CmpInst::ICMP_EQ, spv::OpIEqual},
3498 {CmpInst::ICMP_NE, spv::OpINotEqual},
3499 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3500 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3501 {CmpInst::ICMP_ULT, spv::OpULessThan},
3502 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3503 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3504 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3505 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3506 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3507 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3508 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3509 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3510 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3511 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3512 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3513 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3514 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3515 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3516 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3517 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3518 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3519
3520 assert(0 != Map.count(I->getPredicate()));
3521
3522 return Map.at(I->getPredicate());
3523}
3524
3525spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3526 const std::map<unsigned, spv::Op> Map{
3527 {Instruction::Trunc, spv::OpUConvert},
3528 {Instruction::ZExt, spv::OpUConvert},
3529 {Instruction::SExt, spv::OpSConvert},
3530 {Instruction::FPToUI, spv::OpConvertFToU},
3531 {Instruction::FPToSI, spv::OpConvertFToS},
3532 {Instruction::UIToFP, spv::OpConvertUToF},
3533 {Instruction::SIToFP, spv::OpConvertSToF},
3534 {Instruction::FPTrunc, spv::OpFConvert},
3535 {Instruction::FPExt, spv::OpFConvert},
3536 {Instruction::BitCast, spv::OpBitcast}};
3537
3538 assert(0 != Map.count(I.getOpcode()));
3539
3540 return Map.at(I.getOpcode());
3541}
3542
3543spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
3544 if (I.getType()->isIntegerTy(1)) {
3545 switch (I.getOpcode()) {
3546 default:
3547 break;
3548 case Instruction::Or:
3549 return spv::OpLogicalOr;
3550 case Instruction::And:
3551 return spv::OpLogicalAnd;
3552 case Instruction::Xor:
3553 return spv::OpLogicalNotEqual;
3554 }
3555 }
3556
3557 const std::map<unsigned, spv::Op> Map {
3558 {Instruction::Add, spv::OpIAdd},
3559 {Instruction::FAdd, spv::OpFAdd},
3560 {Instruction::Sub, spv::OpISub},
3561 {Instruction::FSub, spv::OpFSub},
3562 {Instruction::Mul, spv::OpIMul},
3563 {Instruction::FMul, spv::OpFMul},
3564 {Instruction::UDiv, spv::OpUDiv},
3565 {Instruction::SDiv, spv::OpSDiv},
3566 {Instruction::FDiv, spv::OpFDiv},
3567 {Instruction::URem, spv::OpUMod},
3568 {Instruction::SRem, spv::OpSRem},
3569 {Instruction::FRem, spv::OpFRem},
3570 {Instruction::Or, spv::OpBitwiseOr},
3571 {Instruction::Xor, spv::OpBitwiseXor},
3572 {Instruction::And, spv::OpBitwiseAnd},
3573 {Instruction::Shl, spv::OpShiftLeftLogical},
3574 {Instruction::LShr, spv::OpShiftRightLogical},
3575 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3576
3577 assert(0 != Map.count(I.getOpcode()));
3578
3579 return Map.at(I.getOpcode());
3580}
3581
3582void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
3583 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3584 ValueMapType &VMap = getValueMap();
3585 ValueToValueMapTy &ArgGVMap = getArgumentGVMap();
3586 ValueMapType &ArgGVIDMap = getArgumentGVIDMap();
3587 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
3588 LLVMContext &Context = I.getParent()->getParent()->getParent()->getContext();
3589
3590 // Register Instruction to ValueMap.
3591 if (0 == VMap[&I]) {
3592 VMap[&I] = nextID;
3593 }
3594
3595 switch (I.getOpcode()) {
3596 default: {
3597 if (Instruction::isCast(I.getOpcode())) {
3598 //
3599 // Generate SPIRV instructions for cast operators.
3600 //
3601
David Netod2de94a2017-08-28 17:27:47 -04003602
3603 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003604 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003605 auto toI8 = Ty == Type::getInt8Ty(Context);
3606 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003607 // Handle zext, sext and uitofp with i1 type specially.
3608 if ((I.getOpcode() == Instruction::ZExt ||
3609 I.getOpcode() == Instruction::SExt ||
3610 I.getOpcode() == Instruction::UIToFP) &&
3611 (OpTy->isIntegerTy(1) ||
3612 (OpTy->isVectorTy() &&
3613 OpTy->getVectorElementType()->isIntegerTy(1)))) {
3614 //
3615 // Generate OpSelect.
3616 //
3617
3618 // Ops[0] = Result Type ID
3619 // Ops[1] = Condition ID
3620 // Ops[2] = True Constant ID
3621 // Ops[3] = False Constant ID
3622 SPIRVOperandList Ops;
3623
3624 uint32_t ResTyID = lookupType(I.getType());
3625 SPIRVOperand *ResTyIDOp =
3626 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3627 Ops.push_back(ResTyIDOp);
3628
3629 // TODO: zext's first operand should be compare instructions???
3630 uint32_t CondID = VMap[I.getOperand(0)];
3631 SPIRVOperand *CondIDOp =
3632 new SPIRVOperand(SPIRVOperandType::NUMBERID, CondID);
3633 Ops.push_back(CondIDOp);
3634
3635 uint32_t TrueID = 0;
3636 if (I.getOpcode() == Instruction::ZExt) {
3637 APInt One(32, 1);
3638 TrueID = VMap[Constant::getIntegerValue(I.getType(), One)];
3639 } else if (I.getOpcode() == Instruction::SExt) {
3640 APInt MinusOne(32, UINT64_MAX, true);
3641 TrueID = VMap[Constant::getIntegerValue(I.getType(), MinusOne)];
3642 } else {
3643 TrueID = VMap[ConstantFP::get(Context, APFloat(1.0f))];
3644 }
3645 SPIRVOperand *TrueIDOp =
3646 new SPIRVOperand(SPIRVOperandType::NUMBERID, TrueID);
3647 Ops.push_back(TrueIDOp);
3648
3649 uint32_t FalseID = 0;
3650 if (I.getOpcode() == Instruction::ZExt) {
3651 FalseID = VMap[Constant::getNullValue(I.getType())];
3652 } else if (I.getOpcode() == Instruction::SExt) {
3653 FalseID = VMap[Constant::getNullValue(I.getType())];
3654 } else {
3655 FalseID = VMap[ConstantFP::get(Context, APFloat(0.0f))];
3656 }
3657 SPIRVOperand *FalseIDOp =
3658 new SPIRVOperand(SPIRVOperandType::NUMBERID, FalseID);
3659 Ops.push_back(FalseIDOp);
3660
3661 SPIRVInstruction *Inst =
3662 new SPIRVInstruction(6, spv::OpSelect, nextID++, Ops);
3663 SPIRVInstList.push_back(Inst);
David Netod2de94a2017-08-28 17:27:47 -04003664 } else if (I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
3665 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3666 // 8 bits.
3667 // Before:
3668 // %result = trunc i32 %a to i8
3669 // After
3670 // %result = OpBitwiseAnd %uint %a %uint_255
3671
3672 SPIRVOperandList Ops;
3673
3674 uint32_t ResTyID = lookupType(OpTy);
3675 SPIRVOperand *ResTyIDOp =
3676 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3677 Ops.push_back(ResTyIDOp);
3678
3679 uint32_t Op0ID = VMap[I.getOperand(0)];
3680 SPIRVOperand *Op0IDOp =
3681 new SPIRVOperand(SPIRVOperandType::NUMBERID, Op0ID);
3682 Ops.push_back(Op0IDOp);
3683
3684 Type *UintTy = Type::getInt32Ty(Context);
3685 uint32_t MaskID = VMap[ConstantInt::get(UintTy, 255)];
3686 SPIRVOperand *MaskOp =
3687 new SPIRVOperand(SPIRVOperandType::NUMBERID, MaskID);
3688 Ops.push_back(MaskOp);
3689
3690 SPIRVInstruction *Inst =
3691 new SPIRVInstruction(5, spv::OpBitwiseAnd, nextID++, Ops);
3692 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003693 } else {
3694 // Ops[0] = Result Type ID
3695 // Ops[1] = Source Value ID
3696 SPIRVOperandList Ops;
3697
3698 uint32_t ResTyID = lookupType(I.getType());
3699 SPIRVOperand *ResTyIDOp =
3700 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3701 Ops.push_back(ResTyIDOp);
3702
3703 uint32_t SrcID = VMap[I.getOperand(0)];
3704 SPIRVOperand *SrcIDOp =
3705 new SPIRVOperand(SPIRVOperandType::NUMBERID, SrcID);
3706 Ops.push_back(SrcIDOp);
3707
3708 SPIRVInstruction *Inst =
3709 new SPIRVInstruction(4, GetSPIRVCastOpcode(I), nextID++, Ops);
3710 SPIRVInstList.push_back(Inst);
3711 }
3712 } else if (isa<BinaryOperator>(I)) {
3713 //
3714 // Generate SPIRV instructions for binary operators.
3715 //
3716
3717 // Handle xor with i1 type specially.
3718 if (I.getOpcode() == Instruction::Xor &&
3719 I.getType() == Type::getInt1Ty(Context) &&
3720 (isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
3721 //
3722 // Generate OpLogicalNot.
3723 //
3724 // Ops[0] = Result Type ID
3725 // Ops[1] = Operand
3726 SPIRVOperandList Ops;
3727
3728 uint32_t ResTyID = lookupType(I.getType());
3729 SPIRVOperand *ResTyIDOp =
3730 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3731 Ops.push_back(ResTyIDOp);
3732
3733 Value *CondV = I.getOperand(0);
3734 if (isa<Constant>(I.getOperand(0))) {
3735 CondV = I.getOperand(1);
3736 }
3737 uint32_t CondID = VMap[CondV];
3738 SPIRVOperand *CondIDOp =
3739 new SPIRVOperand(SPIRVOperandType::NUMBERID, CondID);
3740 Ops.push_back(CondIDOp);
3741
3742 SPIRVInstruction *Inst =
3743 new SPIRVInstruction(4, spv::OpLogicalNot, nextID++, Ops);
3744 SPIRVInstList.push_back(Inst);
3745 } else {
3746 // Ops[0] = Result Type ID
3747 // Ops[1] = Operand 0
3748 // Ops[2] = Operand 1
3749 SPIRVOperandList Ops;
3750
3751 uint32_t ResTyID = lookupType(I.getType());
3752 SPIRVOperand *ResTyIDOp =
3753 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3754 Ops.push_back(ResTyIDOp);
3755
3756 uint32_t Op0ID = VMap[I.getOperand(0)];
3757 SPIRVOperand *Op0IDOp =
3758 new SPIRVOperand(SPIRVOperandType::NUMBERID, Op0ID);
3759 Ops.push_back(Op0IDOp);
3760
3761 uint32_t Op1ID = VMap[I.getOperand(1)];
3762 SPIRVOperand *Op1IDOp =
3763 new SPIRVOperand(SPIRVOperandType::NUMBERID, Op1ID);
3764 Ops.push_back(Op1IDOp);
3765
3766 SPIRVInstruction *Inst =
3767 new SPIRVInstruction(5, GetSPIRVBinaryOpcode(I), nextID++, Ops);
3768 SPIRVInstList.push_back(Inst);
3769 }
3770 } else {
3771 I.print(errs());
3772 llvm_unreachable("Unsupported instruction???");
3773 }
3774 break;
3775 }
3776 case Instruction::GetElementPtr: {
3777 auto &GlobalConstArgSet = getGlobalConstArgSet();
3778
3779 //
3780 // Generate OpAccessChain.
3781 //
3782 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
3783
3784 //
3785 // Generate OpAccessChain.
3786 //
3787
3788 // Ops[0] = Result Type ID
3789 // Ops[1] = Base ID
3790 // Ops[2] ... Ops[n] = Indexes ID
3791 SPIRVOperandList Ops;
3792
David Neto1a1a0582017-07-07 12:01:44 -04003793 PointerType* ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04003794 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
3795 GlobalConstArgSet.count(GEP->getPointerOperand())) {
3796 // Use pointer type with private address space for global constant.
3797 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04003798 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04003799 }
David Neto1a1a0582017-07-07 12:01:44 -04003800 const uint32_t ResTyID = lookupType(ResultType);
David Neto22f144c2017-06-12 14:26:21 -04003801 SPIRVOperand *ResTyIDOp =
3802 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3803 Ops.push_back(ResTyIDOp);
3804
3805 // Check whether GEP's pointer operand is pointer argument.
3806 bool HasArgBasePointer = false;
3807 for (auto ArgGV : ArgGVMap) {
3808 if (ArgGV.first == GEP->getPointerOperand()) {
3809 if (isa<PointerType>(ArgGV.first->getType())) {
3810 HasArgBasePointer = true;
3811 } else {
3812 llvm_unreachable(
3813 "GEP's pointer operand is argument of non-poninter type???");
3814 }
3815 }
3816 }
3817
3818 uint32_t BaseID;
3819 if (HasArgBasePointer) {
3820 // Point to global variable for argument directly.
3821 BaseID = ArgGVIDMap[GEP->getPointerOperand()];
3822 } else {
3823 BaseID = VMap[GEP->getPointerOperand()];
3824 }
3825
3826 SPIRVOperand *BaseIDOp =
3827 new SPIRVOperand(SPIRVOperandType::NUMBERID, BaseID);
3828 Ops.push_back(BaseIDOp);
3829
3830 uint16_t WordCount = 4;
3831
3832 if (HasArgBasePointer) {
3833 // If GEP's pointer operand is argument, add one more index for struct
3834 // type to wrap up argument type.
3835 Type *IdxTy = Type::getInt32Ty(Context);
3836 uint32_t IndexID = VMap[ConstantInt::get(IdxTy, 0)];
3837 SPIRVOperand *IndexIDOp =
3838 new SPIRVOperand(SPIRVOperandType::NUMBERID, IndexID);
3839 Ops.push_back(IndexIDOp);
3840
3841 WordCount++;
3842 }
3843
3844 //
3845 // Follows below rules for gep.
3846 //
3847 // 1. If gep's first index is 0 and gep's base is not kernel function's
3848 // argument, generate OpAccessChain and ignore gep's first index.
3849 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
3850 // first index.
3851 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
3852 // use gep's first index.
3853 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
3854 // gep's first index.
3855 //
3856 spv::Op Opcode = spv::OpAccessChain;
3857 unsigned offset = 0;
3858 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
3859 if (CstInt->getZExtValue() == 0 && !HasArgBasePointer) {
3860 offset = 1;
3861 } else if (CstInt->getZExtValue() != 0 && !HasArgBasePointer) {
3862 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04003863 }
3864 } else if (!HasArgBasePointer) {
3865 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04003866 }
3867
3868 if (Opcode == spv::OpPtrAccessChain) {
David Neto22f144c2017-06-12 14:26:21 -04003869 setVariablePointers(true);
David Neto1a1a0582017-07-07 12:01:44 -04003870 // Do we need to generate ArrayStride? Check against the GEP result type
3871 // rather than the pointer type of the base because when indexing into
3872 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
3873 // for something else in the SPIR-V.
3874 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
3875 if (GetStorageClass(ResultType->getAddressSpace()) ==
3876 spv::StorageClassStorageBuffer) {
3877 // Save the need to generate an ArrayStride decoration. But defer
3878 // generation until later, so we only make one decoration.
3879 getPointerTypesNeedingArrayStride().insert(ResultType);
3880 }
David Neto22f144c2017-06-12 14:26:21 -04003881 }
3882
3883 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
3884 uint32_t IndexID = VMap[*II];
3885 SPIRVOperand *IndexIDOp =
3886 new SPIRVOperand(SPIRVOperandType::NUMBERID, IndexID);
3887 Ops.push_back(IndexIDOp);
3888
3889 WordCount++;
3890 }
3891
3892 SPIRVInstruction *Inst =
3893 new SPIRVInstruction(WordCount, Opcode, nextID++, Ops);
3894 SPIRVInstList.push_back(Inst);
3895 break;
3896 }
3897 case Instruction::ExtractValue: {
3898 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3899 // Ops[0] = Result Type ID
3900 // Ops[1] = Composite ID
3901 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3902 SPIRVOperandList Ops;
3903
3904 uint32_t ResTyID = lookupType(I.getType());
3905 SPIRVOperand *ResTyIDOp =
3906 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3907 Ops.push_back(ResTyIDOp);
3908
3909 uint32_t CompositeID = VMap[EVI->getAggregateOperand()];
3910 SPIRVOperand *CompositeIDOp =
3911 new SPIRVOperand(SPIRVOperandType::NUMBERID, CompositeID);
3912 Ops.push_back(CompositeIDOp);
3913
3914 for (auto &Index : EVI->indices()) {
3915 Ops.push_back(new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, Index));
3916 }
3917
3918 uint16_t WordCount = static_cast<uint16_t>(2 + Ops.size());
3919 SPIRVInstruction *Inst =
3920 new SPIRVInstruction(WordCount, spv::OpCompositeExtract, nextID++, Ops);
3921 SPIRVInstList.push_back(Inst);
3922 break;
3923 }
3924 case Instruction::InsertValue: {
3925 InsertValueInst *IVI = cast<InsertValueInst>(&I);
3926 // Ops[0] = Result Type ID
3927 // Ops[1] = Object ID
3928 // Ops[2] = Composite ID
3929 // Ops[3] ... Ops[n] = Indexes (Literal Number)
3930 SPIRVOperandList Ops;
3931
3932 uint32_t ResTyID = lookupType(I.getType());
3933 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID));
3934
3935 uint32_t ObjectID = VMap[IVI->getInsertedValueOperand()];
3936 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, ObjectID));
3937
3938 uint32_t CompositeID = VMap[IVI->getAggregateOperand()];
3939 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, CompositeID));
3940
3941 for (auto &Index : IVI->indices()) {
3942 Ops.push_back(new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, Index));
3943 }
3944
3945 uint16_t WordCount = static_cast<uint16_t>(2 + Ops.size());
3946 SPIRVInstruction *Inst =
3947 new SPIRVInstruction(WordCount, spv::OpCompositeInsert, nextID++, Ops);
3948 SPIRVInstList.push_back(Inst);
3949 break;
3950 }
3951 case Instruction::Select: {
3952 //
3953 // Generate OpSelect.
3954 //
3955
3956 // Ops[0] = Result Type ID
3957 // Ops[1] = Condition ID
3958 // Ops[2] = True Constant ID
3959 // Ops[3] = False Constant ID
3960 SPIRVOperandList Ops;
3961
3962 // Find SPIRV instruction for parameter type.
3963 auto Ty = I.getType();
3964 if (Ty->isPointerTy()) {
3965 auto PointeeTy = Ty->getPointerElementType();
3966 if (PointeeTy->isStructTy() &&
3967 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
3968 Ty = PointeeTy;
3969 }
3970 }
3971
3972 uint32_t ResTyID = lookupType(Ty);
3973 SPIRVOperand *ResTyIDOp =
3974 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3975 Ops.push_back(ResTyIDOp);
3976
3977 uint32_t CondID = VMap[I.getOperand(0)];
3978 SPIRVOperand *CondIDOp =
3979 new SPIRVOperand(SPIRVOperandType::NUMBERID, CondID);
3980 Ops.push_back(CondIDOp);
3981
3982 uint32_t TrueID = VMap[I.getOperand(1)];
3983 SPIRVOperand *TrueIDOp =
3984 new SPIRVOperand(SPIRVOperandType::NUMBERID, TrueID);
3985 Ops.push_back(TrueIDOp);
3986
3987 uint32_t FalseID = VMap[I.getOperand(2)];
3988 SPIRVOperand *FalseIDOp =
3989 new SPIRVOperand(SPIRVOperandType::NUMBERID, FalseID);
3990 Ops.push_back(FalseIDOp);
3991
3992 SPIRVInstruction *Inst =
3993 new SPIRVInstruction(6, spv::OpSelect, nextID++, Ops);
3994 SPIRVInstList.push_back(Inst);
3995 break;
3996 }
3997 case Instruction::ExtractElement: {
3998 // Handle <4 x i8> type manually.
3999 Type *CompositeTy = I.getOperand(0)->getType();
4000 if (is4xi8vec(CompositeTy)) {
4001 //
4002 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
4003 // <4 x i8>.
4004 //
4005
4006 //
4007 // Generate OpShiftRightLogical
4008 //
4009 // Ops[0] = Result Type ID
4010 // Ops[1] = Operand 0
4011 // Ops[2] = Operand 1
4012 //
4013 SPIRVOperandList Ops;
4014
4015 uint32_t ResTyID = lookupType(CompositeTy);
4016 SPIRVOperand *ResTyIDOp =
4017 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
4018 Ops.push_back(ResTyIDOp);
4019
4020 uint32_t Op0ID = VMap[I.getOperand(0)];
4021 SPIRVOperand *Op0IDOp =
4022 new SPIRVOperand(SPIRVOperandType::NUMBERID, Op0ID);
4023 Ops.push_back(Op0IDOp);
4024
4025 uint32_t Op1ID = 0;
4026 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
4027 // Handle constant index.
4028 uint64_t Idx = CI->getZExtValue();
4029 Value *ShiftAmount =
4030 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
4031 Op1ID = VMap[ShiftAmount];
4032 } else {
4033 // Handle variable index.
4034 SPIRVOperandList TmpOps;
4035
4036 uint32_t TmpResTyID = lookupType(Type::getInt32Ty(Context));
4037 SPIRVOperand *TmpResTyIDOp =
4038 new SPIRVOperand(SPIRVOperandType::NUMBERID, TmpResTyID);
4039 TmpOps.push_back(TmpResTyIDOp);
4040
4041 uint32_t IdxID = VMap[I.getOperand(1)];
4042 SPIRVOperand *TmpOp0IDOp =
4043 new SPIRVOperand(SPIRVOperandType::NUMBERID, IdxID);
4044 TmpOps.push_back(TmpOp0IDOp);
4045
4046 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
4047 uint32_t Cst8ID = VMap[Cst8];
4048 SPIRVOperand *TmpOp1IDOp =
4049 new SPIRVOperand(SPIRVOperandType::NUMBERID, Cst8ID);
4050 TmpOps.push_back(TmpOp1IDOp);
4051
4052 Op1ID = nextID;
4053
4054 SPIRVInstruction *TmpInst =
4055 new SPIRVInstruction(5, spv::OpIMul, nextID++, TmpOps);
4056 SPIRVInstList.push_back(TmpInst);
4057 }
4058 SPIRVOperand *Op1IDOp =
4059 new SPIRVOperand(SPIRVOperandType::NUMBERID, Op1ID);
4060 Ops.push_back(Op1IDOp);
4061
4062 uint32_t ShiftID = nextID;
4063
4064 SPIRVInstruction *Inst =
4065 new SPIRVInstruction(5, spv::OpShiftRightLogical, nextID++, Ops);
4066 SPIRVInstList.push_back(Inst);
4067
4068 //
4069 // Generate OpBitwiseAnd
4070 //
4071 // Ops[0] = Result Type ID
4072 // Ops[1] = Operand 0
4073 // Ops[2] = Operand 1
4074 //
4075 Ops.clear();
4076
4077 ResTyID = lookupType(CompositeTy);
4078 ResTyIDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
4079 Ops.push_back(ResTyIDOp);
4080
4081 Op0ID = ShiftID;
4082 Op0IDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Op0ID);
4083 Ops.push_back(Op0IDOp);
4084
4085 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
4086 Op1ID = VMap[CstFF];
4087 Op1IDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Op1ID);
4088 Ops.push_back(Op1IDOp);
4089
David Neto9b2d6252017-09-06 15:47:37 -04004090 // Reset mapping for this value to the result of the bitwise and.
4091 VMap[&I] = nextID;
4092
David Neto22f144c2017-06-12 14:26:21 -04004093 Inst = new SPIRVInstruction(5, spv::OpBitwiseAnd, nextID++, Ops);
4094 SPIRVInstList.push_back(Inst);
4095 break;
4096 }
4097
4098 // Ops[0] = Result Type ID
4099 // Ops[1] = Composite ID
4100 // Ops[2] ... Ops[n] = Indexes (Literal Number)
4101 SPIRVOperandList Ops;
4102
4103 uint32_t ResTyID = lookupType(I.getType());
4104 SPIRVOperand *ResTyIDOp =
4105 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
4106 Ops.push_back(ResTyIDOp);
4107
4108 uint32_t CompositeID = VMap[I.getOperand(0)];
4109 SPIRVOperand *CompositeIDOp =
4110 new SPIRVOperand(SPIRVOperandType::NUMBERID, CompositeID);
4111 Ops.push_back(CompositeIDOp);
4112
4113 spv::Op Opcode = spv::OpCompositeExtract;
4114 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
4115 std::vector<uint32_t> LiteralNum;
4116 assert(CI->getZExtValue() < UINT32_MAX);
4117 LiteralNum.push_back(static_cast<uint32_t>(CI->getZExtValue()));
4118 SPIRVOperand *Indexes =
4119 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
4120 Ops.push_back(Indexes);
4121 } else {
4122 uint32_t IndexID = VMap[I.getOperand(1)];
4123 SPIRVOperand *IndexIDOp =
4124 new SPIRVOperand(SPIRVOperandType::NUMBERID, IndexID);
4125 Ops.push_back(IndexIDOp);
4126 Opcode = spv::OpVectorExtractDynamic;
4127 }
4128
4129 uint16_t WordCount = 5;
4130 SPIRVInstruction *Inst =
4131 new SPIRVInstruction(WordCount, Opcode, nextID++, Ops);
4132 SPIRVInstList.push_back(Inst);
4133 break;
4134 }
4135 case Instruction::InsertElement: {
4136 // Handle <4 x i8> type manually.
4137 Type *CompositeTy = I.getOperand(0)->getType();
4138 if (is4xi8vec(CompositeTy)) {
4139 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
4140 uint32_t CstFFID = VMap[CstFF];
4141
4142 uint32_t ShiftAmountID = 0;
4143 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
4144 // Handle constant index.
4145 uint64_t Idx = CI->getZExtValue();
4146 Value *ShiftAmount =
4147 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
4148 ShiftAmountID = VMap[ShiftAmount];
4149 } else {
4150 // Handle variable index.
4151 SPIRVOperandList TmpOps;
4152
4153 uint32_t TmpResTyID = lookupType(Type::getInt32Ty(Context));
4154 SPIRVOperand *TmpResTyIDOp =
4155 new SPIRVOperand(SPIRVOperandType::NUMBERID, TmpResTyID);
4156 TmpOps.push_back(TmpResTyIDOp);
4157
4158 uint32_t IdxID = VMap[I.getOperand(2)];
4159 SPIRVOperand *TmpOp0IDOp =
4160 new SPIRVOperand(SPIRVOperandType::NUMBERID, IdxID);
4161 TmpOps.push_back(TmpOp0IDOp);
4162
4163 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
4164 uint32_t Cst8ID = VMap[Cst8];
4165 SPIRVOperand *TmpOp1IDOp =
4166 new SPIRVOperand(SPIRVOperandType::NUMBERID, Cst8ID);
4167 TmpOps.push_back(TmpOp1IDOp);
4168
4169 ShiftAmountID = nextID;
4170
4171 SPIRVInstruction *TmpInst =
4172 new SPIRVInstruction(5, spv::OpIMul, nextID++, TmpOps);
4173 SPIRVInstList.push_back(TmpInst);
4174 }
4175
4176 //
4177 // Generate mask operations.
4178 //
4179
4180 // ShiftLeft mask according to index of insertelement.
4181 SPIRVOperandList Ops;
4182
4183 uint32_t ResTyID = lookupType(CompositeTy);
4184 SPIRVOperand *ResTyIDOp =
4185 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
4186 Ops.push_back(ResTyIDOp);
4187
4188 uint32_t Op0ID = CstFFID;
4189 SPIRVOperand *Op0IDOp =
4190 new SPIRVOperand(SPIRVOperandType::NUMBERID, Op0ID);
4191 Ops.push_back(Op0IDOp);
4192
4193 uint32_t Op1ID = ShiftAmountID;
4194 SPIRVOperand *Op1IDOp =
4195 new SPIRVOperand(SPIRVOperandType::NUMBERID, Op1ID);
4196 Ops.push_back(Op1IDOp);
4197
4198 uint32_t MaskID = nextID;
4199
4200 SPIRVInstruction *Inst =
4201 new SPIRVInstruction(5, spv::OpShiftLeftLogical, nextID++, Ops);
4202 SPIRVInstList.push_back(Inst);
4203
4204 // Inverse mask.
4205 Ops.clear();
4206
4207 Ops.push_back(ResTyIDOp);
4208
4209 Op0ID = MaskID;
4210 Op0IDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Op0ID);
4211 Ops.push_back(Op0IDOp);
4212
4213 uint32_t InvMaskID = nextID;
4214
David Netoa394f392017-08-26 20:45:29 -04004215 Inst = new SPIRVInstruction(4, spv::OpNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004216 SPIRVInstList.push_back(Inst);
4217
4218 // Apply mask.
4219 Ops.clear();
4220
4221 Ops.push_back(ResTyIDOp);
4222
4223 Op0ID = VMap[I.getOperand(0)];
4224 Op0IDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Op0ID);
4225 Ops.push_back(Op0IDOp);
4226
4227 Op1ID = InvMaskID;
4228 Op1IDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Op1ID);
4229 Ops.push_back(Op1IDOp);
4230
4231 uint32_t OrgValID = nextID;
4232
4233 Inst = new SPIRVInstruction(5, spv::OpBitwiseAnd, nextID++, Ops);
4234 SPIRVInstList.push_back(Inst);
4235
4236 // Create correct value according to index of insertelement.
4237 Ops.clear();
4238
4239 Ops.push_back(ResTyIDOp);
4240
4241 Op0ID = VMap[I.getOperand(1)];
4242 Op0IDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Op0ID);
4243 Ops.push_back(Op0IDOp);
4244
4245 Op1ID = ShiftAmountID;
4246 Op1IDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Op1ID);
4247 Ops.push_back(Op1IDOp);
4248
4249 uint32_t InsertValID = nextID;
4250
4251 Inst = new SPIRVInstruction(5, spv::OpShiftLeftLogical, nextID++, Ops);
4252 SPIRVInstList.push_back(Inst);
4253
4254 // Insert value to original value.
4255 Ops.clear();
4256
4257 Ops.push_back(ResTyIDOp);
4258
4259 Op0ID = OrgValID;
4260 Op0IDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Op0ID);
4261 Ops.push_back(Op0IDOp);
4262
4263 Op1ID = InsertValID;
4264 Op1IDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Op1ID);
4265 Ops.push_back(Op1IDOp);
4266
David Netoa394f392017-08-26 20:45:29 -04004267 VMap[&I] = nextID;
4268
David Neto22f144c2017-06-12 14:26:21 -04004269 Inst = new SPIRVInstruction(5, spv::OpBitwiseOr, nextID++, Ops);
4270 SPIRVInstList.push_back(Inst);
4271
4272 break;
4273 }
4274
4275 // Ops[0] = Result Type ID
4276 // Ops[1] = Object ID
4277 // Ops[2] = Composite ID
4278 // Ops[3] ... Ops[n] = Indexes (Literal Number)
4279 SPIRVOperandList Ops;
4280
4281 uint32_t ResTyID = lookupType(I.getType());
4282 SPIRVOperand *ResTyIDOp =
4283 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
4284 Ops.push_back(ResTyIDOp);
4285
4286 uint32_t ObjectID = VMap[I.getOperand(1)];
4287 SPIRVOperand *ObjectIDOp =
4288 new SPIRVOperand(SPIRVOperandType::NUMBERID, ObjectID);
4289 Ops.push_back(ObjectIDOp);
4290
4291 uint32_t CompositeID = VMap[I.getOperand(0)];
4292 SPIRVOperand *CompositeIDOp =
4293 new SPIRVOperand(SPIRVOperandType::NUMBERID, CompositeID);
4294 Ops.push_back(CompositeIDOp);
4295
4296 spv::Op Opcode = spv::OpCompositeInsert;
4297 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
4298 std::vector<uint32_t> LiteralNum;
4299 assert(CI->getZExtValue() < UINT32_MAX);
4300 LiteralNum.push_back(static_cast<uint32_t>(CI->getZExtValue()));
4301 SPIRVOperand *Indexes =
4302 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
4303 Ops.push_back(Indexes);
4304 } else {
4305 uint32_t IndexID = VMap[I.getOperand(1)];
4306 SPIRVOperand *IndexIDOp =
4307 new SPIRVOperand(SPIRVOperandType::NUMBERID, IndexID);
4308 Ops.push_back(IndexIDOp);
4309 Opcode = spv::OpVectorInsertDynamic;
4310 }
4311
4312 uint16_t WordCount = 6;
4313 SPIRVInstruction *Inst =
4314 new SPIRVInstruction(WordCount, Opcode, nextID++, Ops);
4315 SPIRVInstList.push_back(Inst);
4316 break;
4317 }
4318 case Instruction::ShuffleVector: {
4319 // Ops[0] = Result Type ID
4320 // Ops[1] = Vector 1 ID
4321 // Ops[2] = Vector 2 ID
4322 // Ops[3] ... Ops[n] = Components (Literal Number)
4323 SPIRVOperandList Ops;
4324
4325 uint32_t ResTyID = lookupType(I.getType());
4326 SPIRVOperand *ResTyIDOp =
4327 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
4328 Ops.push_back(ResTyIDOp);
4329
4330 uint32_t Vec1ID = VMap[I.getOperand(0)];
4331 SPIRVOperand *Vec1IDOp =
4332 new SPIRVOperand(SPIRVOperandType::NUMBERID, Vec1ID);
4333 Ops.push_back(Vec1IDOp);
4334
4335 uint32_t Vec2ID = VMap[I.getOperand(1)];
4336 SPIRVOperand *Vec2IDOp =
4337 new SPIRVOperand(SPIRVOperandType::NUMBERID, Vec2ID);
4338 Ops.push_back(Vec2IDOp);
4339
4340 uint64_t NumElements = 0;
4341 if (Constant *Cst = dyn_cast<Constant>(I.getOperand(2))) {
4342 NumElements = cast<VectorType>(Cst->getType())->getNumElements();
4343
4344 if (Cst->isNullValue()) {
4345 for (unsigned i = 0; i < NumElements; i++) {
4346 std::vector<uint32_t> LiteralNum;
4347 LiteralNum.push_back(0);
4348 SPIRVOperand *Component =
4349 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
4350 Ops.push_back(Component);
4351 }
4352 } else if (const ConstantDataSequential *CDS =
4353 dyn_cast<ConstantDataSequential>(Cst)) {
4354 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
4355 std::vector<uint32_t> LiteralNum;
4356 assert(CDS->getElementAsInteger(i) < UINT32_MAX);
4357 LiteralNum.push_back(
4358 static_cast<uint32_t>(CDS->getElementAsInteger(i)));
4359 SPIRVOperand *Component =
4360 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
4361 Ops.push_back(Component);
4362 }
4363 } else if (const ConstantVector *CV = dyn_cast<ConstantVector>(Cst)) {
4364 for (unsigned i = 0; i < CV->getNumOperands(); i++) {
4365 auto Op = CV->getOperand(i);
4366
4367 uint32_t literal = 0;
4368
4369 if (auto CI = dyn_cast<ConstantInt>(Op)) {
4370 literal = static_cast<uint32_t>(CI->getZExtValue());
4371 } else if (auto UI = dyn_cast<UndefValue>(Op)) {
4372 literal = 0xFFFFFFFFu;
4373 } else {
4374 Op->print(errs());
4375 llvm_unreachable("Unsupported element in ConstantVector!");
4376 }
4377
4378 std::vector<uint32_t> LiteralNum;
4379 LiteralNum.push_back(literal);
4380 SPIRVOperand *Component =
4381 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
4382 Ops.push_back(Component);
4383 }
4384 } else {
4385 Cst->print(errs());
4386 llvm_unreachable("Unsupported constant mask in ShuffleVector!");
4387 }
4388 }
4389
4390 uint16_t WordCount = static_cast<uint16_t>(5 + NumElements);
4391 SPIRVInstruction *Inst =
4392 new SPIRVInstruction(WordCount, spv::OpVectorShuffle, nextID++, Ops);
4393 SPIRVInstList.push_back(Inst);
4394 break;
4395 }
4396 case Instruction::ICmp:
4397 case Instruction::FCmp: {
4398 CmpInst *CmpI = cast<CmpInst>(&I);
4399
4400 // Ops[0] = Result Type ID
4401 // Ops[1] = Operand 1 ID
4402 // Ops[2] = Operand 2 ID
4403 SPIRVOperandList Ops;
4404
4405 uint32_t ResTyID = lookupType(CmpI->getType());
4406 SPIRVOperand *ResTyIDOp =
4407 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
4408 Ops.push_back(ResTyIDOp);
4409
David Netod4ca2e62017-07-06 18:47:35 -04004410 // Pointer equality is invalid.
4411 Type* ArgTy = CmpI->getOperand(0)->getType();
4412 if (isa<PointerType>(ArgTy)) {
4413 CmpI->print(errs());
4414 std::string name = I.getParent()->getParent()->getName();
4415 errs()
4416 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4417 << "in function " << name << "\n";
4418 llvm_unreachable("Pointer equality check is invalid");
4419 break;
4420 }
4421
David Neto22f144c2017-06-12 14:26:21 -04004422 uint32_t Op1ID = VMap[CmpI->getOperand(0)];
4423 SPIRVOperand *Op1IDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Op1ID);
4424 Ops.push_back(Op1IDOp);
4425
4426 uint32_t Op2ID = VMap[CmpI->getOperand(1)];
4427 SPIRVOperand *Op2IDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Op2ID);
4428 Ops.push_back(Op2IDOp);
4429
4430 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
4431 SPIRVInstruction *Inst = new SPIRVInstruction(5, Opcode, nextID++, Ops);
4432 SPIRVInstList.push_back(Inst);
4433 break;
4434 }
4435 case Instruction::Br: {
4436 // Branch instrucion is deferred because it needs label's ID. Record slot's
4437 // location on SPIRVInstructionList.
4438 DeferredInsts.push_back(
4439 std::make_tuple(&I, --SPIRVInstList.end(), 0 /* No id */));
4440 break;
4441 }
4442 case Instruction::Switch: {
4443 I.print(errs());
4444 llvm_unreachable("Unsupported instruction???");
4445 break;
4446 }
4447 case Instruction::IndirectBr: {
4448 I.print(errs());
4449 llvm_unreachable("Unsupported instruction???");
4450 break;
4451 }
4452 case Instruction::PHI: {
4453 // Branch instrucion is deferred because it needs label's ID. Record slot's
4454 // location on SPIRVInstructionList.
4455 DeferredInsts.push_back(
4456 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4457 break;
4458 }
4459 case Instruction::Alloca: {
4460 //
4461 // Generate OpVariable.
4462 //
4463 // Ops[0] : Result Type ID
4464 // Ops[1] : Storage Class
4465 SPIRVOperandList Ops;
4466
4467 Type *ResTy = I.getType();
4468 uint32_t ResTyID = lookupType(ResTy);
4469 SPIRVOperand *ResTyOp =
4470 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
4471 Ops.push_back(ResTyOp);
4472
4473 spv::StorageClass StorageClass = spv::StorageClassFunction;
4474 SPIRVOperand *StorageClassOp =
4475 new SPIRVOperand(SPIRVOperandType::NUMBERID, StorageClass);
4476 Ops.push_back(StorageClassOp);
4477
4478 SPIRVInstruction *Inst =
4479 new SPIRVInstruction(4, spv::OpVariable, nextID++, Ops);
4480 SPIRVInstList.push_back(Inst);
4481 break;
4482 }
4483 case Instruction::Load: {
4484 LoadInst *LD = cast<LoadInst>(&I);
4485 //
4486 // Generate OpLoad.
4487 //
4488
David Neto0a2f98d2017-09-15 19:38:40 -04004489 uint32_t ResTyID = lookupType(LD->getType());
David Netoa60b00b2017-09-15 16:34:09 -04004490 uint32_t PointerID = VMap[LD->getPointerOperand()];
4491
4492 // This is a hack to work around what looks like a driver bug.
4493 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004494 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4495 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004496 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004497 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004498 // Generate a bitwise-and of the original value with itself.
4499 // We should have been able to get away with just an OpCopyObject,
4500 // but we need something more complex to get past certain driver bugs.
4501 // This is ridiculous, but necessary.
4502 // TODO(dneto): Revisit this once drivers fix their bugs.
4503
4504 SPIRVOperandList Ops;
4505
4506 SPIRVOperand *ResTyIDOp =
4507 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
4508 Ops.push_back(ResTyIDOp);
4509
4510 SPIRVOperand *ValueIDOp0 =
4511 new SPIRVOperand(SPIRVOperandType::NUMBERID, WorkgroupSizeValueID);
4512 Ops.push_back(ValueIDOp0);
4513
4514 SPIRVOperand *ValueIDOp1 =
4515 new SPIRVOperand(SPIRVOperandType::NUMBERID, WorkgroupSizeValueID);
4516 Ops.push_back(ValueIDOp1);
4517
4518 SPIRVInstruction *Inst =
4519 new SPIRVInstruction(5, spv::OpBitwiseAnd, nextID++, Ops);
4520 SPIRVInstList.push_back(Inst);
David Netoa60b00b2017-09-15 16:34:09 -04004521 break;
4522 }
4523
4524 // This is the normal path. Generate a load.
4525
David Neto22f144c2017-06-12 14:26:21 -04004526 // Ops[0] = Result Type ID
4527 // Ops[1] = Pointer ID
4528 // Ops[2] ... Ops[n] = Optional Memory Access
4529 //
4530 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004531
David Neto22f144c2017-06-12 14:26:21 -04004532 SPIRVOperandList Ops;
4533
David Neto22f144c2017-06-12 14:26:21 -04004534 SPIRVOperand *ResTyIDOp =
4535 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
4536 Ops.push_back(ResTyIDOp);
4537
David Neto22f144c2017-06-12 14:26:21 -04004538 SPIRVOperand *PointerIDOp =
4539 new SPIRVOperand(SPIRVOperandType::NUMBERID, PointerID);
4540 Ops.push_back(PointerIDOp);
4541
4542 SPIRVInstruction *Inst =
4543 new SPIRVInstruction(4, spv::OpLoad, nextID++, Ops);
4544 SPIRVInstList.push_back(Inst);
4545 break;
4546 }
4547 case Instruction::Store: {
4548 StoreInst *ST = cast<StoreInst>(&I);
4549 //
4550 // Generate OpStore.
4551 //
4552
4553 // Ops[0] = Pointer ID
4554 // Ops[1] = Object ID
4555 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4556 //
4557 // TODO: Do we need to implement Optional Memory Access???
4558 SPIRVOperand *Ops[2] = {new SPIRVOperand(SPIRVOperandType::NUMBERID,
4559 VMap[ST->getPointerOperand()]),
4560 new SPIRVOperand(SPIRVOperandType::NUMBERID,
4561 VMap[ST->getValueOperand()])};
4562
4563 SPIRVInstruction *Inst =
4564 new SPIRVInstruction(3, spv::OpStore, 0 /* No id */, Ops);
4565 SPIRVInstList.push_back(Inst);
4566 break;
4567 }
4568 case Instruction::AtomicCmpXchg: {
4569 I.print(errs());
4570 llvm_unreachable("Unsupported instruction???");
4571 break;
4572 }
4573 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004574 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4575
4576 spv::Op opcode;
4577
4578 switch (AtomicRMW->getOperation()) {
4579 default:
4580 I.print(errs());
4581 llvm_unreachable("Unsupported instruction???");
4582 case llvm::AtomicRMWInst::Add:
4583 opcode = spv::OpAtomicIAdd;
4584 break;
4585 case llvm::AtomicRMWInst::Sub:
4586 opcode = spv::OpAtomicISub;
4587 break;
4588 case llvm::AtomicRMWInst::Xchg:
4589 opcode = spv::OpAtomicExchange;
4590 break;
4591 case llvm::AtomicRMWInst::Min:
4592 opcode = spv::OpAtomicSMin;
4593 break;
4594 case llvm::AtomicRMWInst::Max:
4595 opcode = spv::OpAtomicSMax;
4596 break;
4597 case llvm::AtomicRMWInst::UMin:
4598 opcode = spv::OpAtomicUMin;
4599 break;
4600 case llvm::AtomicRMWInst::UMax:
4601 opcode = spv::OpAtomicUMax;
4602 break;
4603 case llvm::AtomicRMWInst::And:
4604 opcode = spv::OpAtomicAnd;
4605 break;
4606 case llvm::AtomicRMWInst::Or:
4607 opcode = spv::OpAtomicOr;
4608 break;
4609 case llvm::AtomicRMWInst::Xor:
4610 opcode = spv::OpAtomicXor;
4611 break;
4612 }
4613
4614 //
4615 // Generate OpAtomic*.
4616 //
4617 SPIRVOperandList Ops;
4618
4619 uint32_t TyID = lookupType(I.getType());
4620 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, TyID));
4621
4622 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID,
4623 VMap[AtomicRMW->getPointerOperand()]));
4624
4625 auto IntTy = Type::getInt32Ty(I.getContext());
4626
4627 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
4628
4629 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID,
4630 VMap[ConstantScopeDevice]));
4631
4632 const auto ConstantMemorySemantics = ConstantInt::get(
4633 IntTy, spv::MemorySemanticsUniformMemoryMask |
4634 spv::MemorySemanticsSequentiallyConsistentMask);
4635
4636 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID,
4637 VMap[ConstantMemorySemantics]));
4638
4639 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID,
4640 VMap[AtomicRMW->getValOperand()]));
4641
4642 VMap[&I] = nextID;
4643
4644 SPIRVInstruction *Inst = new SPIRVInstruction(
4645 static_cast<uint16_t>(2 + Ops.size()), opcode, nextID++, Ops);
4646 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004647 break;
4648 }
4649 case Instruction::Fence: {
4650 I.print(errs());
4651 llvm_unreachable("Unsupported instruction???");
4652 break;
4653 }
4654 case Instruction::Call: {
4655 CallInst *Call = dyn_cast<CallInst>(&I);
4656 Function *Callee = Call->getCalledFunction();
4657
4658 // Sampler initializers become a load of the corresponding sampler.
4659 if (Callee->getName().equals("__translate_sampler_initializer")) {
4660 // Check that the sampler map was definitely used though.
4661 if (0 == getSamplerMap().size()) {
4662 llvm_unreachable("Sampler literal in source without sampler map!");
4663 }
4664
4665 SPIRVOperandList Ops;
4666
4667 uint32_t ResTyID = lookupType(SamplerTy->getPointerElementType());
4668 SPIRVOperand *ResTyIDOp =
4669 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
4670 Ops.push_back(ResTyIDOp);
4671
4672 uint32_t PointerID = VMap[Call];
4673 SPIRVOperand *PointerIDOp =
4674 new SPIRVOperand(SPIRVOperandType::NUMBERID, PointerID);
4675 Ops.push_back(PointerIDOp);
4676
4677 VMap[Call] = nextID;
4678 SPIRVInstruction *Inst =
4679 new SPIRVInstruction(4, spv::OpLoad, nextID++, Ops);
4680 SPIRVInstList.push_back(Inst);
4681
4682 break;
4683 }
4684
4685 if (Callee->getName().startswith("spirv.atomic")) {
4686 spv::Op opcode = StringSwitch<spv::Op>(Callee->getName())
4687 .Case("spirv.atomic_add", spv::OpAtomicIAdd)
4688 .Case("spirv.atomic_sub", spv::OpAtomicISub)
4689 .Case("spirv.atomic_exchange", spv::OpAtomicExchange)
4690 .Case("spirv.atomic_inc", spv::OpAtomicIIncrement)
4691 .Case("spirv.atomic_dec", spv::OpAtomicIDecrement)
4692 .Case("spirv.atomic_compare_exchange",
4693 spv::OpAtomicCompareExchange)
4694 .Case("spirv.atomic_umin", spv::OpAtomicUMin)
4695 .Case("spirv.atomic_smin", spv::OpAtomicSMin)
4696 .Case("spirv.atomic_umax", spv::OpAtomicUMax)
4697 .Case("spirv.atomic_smax", spv::OpAtomicSMax)
4698 .Case("spirv.atomic_and", spv::OpAtomicAnd)
4699 .Case("spirv.atomic_or", spv::OpAtomicOr)
4700 .Case("spirv.atomic_xor", spv::OpAtomicXor)
4701 .Default(spv::OpNop);
4702
4703 //
4704 // Generate OpAtomic*.
4705 //
4706 SPIRVOperandList Ops;
4707
4708 uint32_t TyID = lookupType(I.getType());
4709 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, TyID));
4710
4711 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
4712 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID,
4713 VMap[Call->getArgOperand(i)]));
4714 }
4715
4716 VMap[&I] = nextID;
4717
4718 SPIRVInstruction *Inst = new SPIRVInstruction(
4719 static_cast<uint16_t>(2 + Ops.size()), opcode, nextID++, Ops);
4720 SPIRVInstList.push_back(Inst);
4721 break;
4722 }
4723
4724 if (Callee->getName().startswith("_Z3dot")) {
4725 // If the argument is a vector type, generate OpDot
4726 if (Call->getArgOperand(0)->getType()->isVectorTy()) {
4727 //
4728 // Generate OpDot.
4729 //
4730 SPIRVOperandList Ops;
4731
4732 uint32_t TyID = lookupType(I.getType());
4733 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, TyID));
4734
4735 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
4736 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID,
4737 VMap[Call->getArgOperand(i)]));
4738 }
4739
4740 VMap[&I] = nextID;
4741
4742 SPIRVInstruction *Inst = new SPIRVInstruction(
4743 static_cast<uint16_t>(2 + Ops.size()), spv::OpDot, nextID++, Ops);
4744 SPIRVInstList.push_back(Inst);
4745 } else {
4746 //
4747 // Generate OpFMul.
4748 //
4749 SPIRVOperandList Ops;
4750
4751 uint32_t TyID = lookupType(I.getType());
4752 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, TyID));
4753
4754 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
4755 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID,
4756 VMap[Call->getArgOperand(i)]));
4757 }
4758
4759 VMap[&I] = nextID;
4760
4761 SPIRVInstruction *Inst = new SPIRVInstruction(
4762 static_cast<uint16_t>(2 + Ops.size()), spv::OpFMul, nextID++, Ops);
4763 SPIRVInstList.push_back(Inst);
4764 }
4765 break;
4766 }
4767
David Neto8505ebf2017-10-13 18:50:50 -04004768 if (Callee->getName().startswith("_Z4fmod")) {
4769 // OpenCL fmod(x,y) is x - y * trunc(x/y)
4770 // The sign for a non-zero result is taken from x.
4771 // (Try an example.)
4772 // So translate to OpFRem
4773
4774 SPIRVOperandList Ops;
4775
4776 uint32_t TyID = lookupType(I.getType());
4777 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, TyID));
4778
4779 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
4780 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID,
4781 VMap[Call->getArgOperand(i)]));
4782 }
4783
4784 VMap[&I] = nextID;
4785
4786 SPIRVInstruction *Inst = new SPIRVInstruction(
4787 static_cast<uint16_t>(2 + Ops.size()), spv::OpFRem, nextID++, Ops);
4788 SPIRVInstList.push_back(Inst);
4789 break;
4790 }
4791
David Neto22f144c2017-06-12 14:26:21 -04004792 // spirv.store_null.* intrinsics become OpStore's.
4793 if (Callee->getName().startswith("spirv.store_null")) {
4794 //
4795 // Generate OpStore.
4796 //
4797
4798 // Ops[0] = Pointer ID
4799 // Ops[1] = Object ID
4800 // Ops[2] ... Ops[n]
4801 SPIRVOperandList Ops;
4802
4803 uint32_t PointerID = VMap[Call->getArgOperand(0)];
4804 SPIRVOperand *PointerIDOp =
4805 new SPIRVOperand(SPIRVOperandType::NUMBERID, PointerID);
4806 Ops.push_back(PointerIDOp);
4807
4808 uint32_t ObjectID = VMap[Call->getArgOperand(1)];
4809 SPIRVOperand *ObjectIDOp =
4810 new SPIRVOperand(SPIRVOperandType::NUMBERID, ObjectID);
4811 Ops.push_back(ObjectIDOp);
4812
4813 SPIRVInstruction *Inst =
4814 new SPIRVInstruction(3, spv::OpStore, 0 /* No id */, Ops);
4815 SPIRVInstList.push_back(Inst);
4816
4817 break;
4818 }
4819
4820 // spirv.copy_memory.* intrinsics become OpMemoryMemory's.
4821 if (Callee->getName().startswith("spirv.copy_memory")) {
4822 //
4823 // Generate OpCopyMemory.
4824 //
4825
4826 // Ops[0] = Dst ID
4827 // Ops[1] = Src ID
4828 // Ops[2] = Memory Access
4829 // Ops[3] = Alignment
4830
4831 auto IsVolatile =
4832 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
4833
4834 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
4835 : spv::MemoryAccessMaskNone;
4836
4837 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
4838
4839 auto Alignment =
4840 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4841
4842 SPIRVOperand *Ops[4] = {
4843 new SPIRVOperand(SPIRVOperandType::NUMBERID,
4844 VMap[Call->getArgOperand(0)]),
4845 new SPIRVOperand(SPIRVOperandType::NUMBERID,
4846 VMap[Call->getArgOperand(1)]),
4847 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, MemoryAccess),
4848 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER,
4849 static_cast<uint32_t>(Alignment))};
4850
4851 SPIRVInstruction *Inst =
4852 new SPIRVInstruction(5, spv::OpCopyMemory, 0 /* No id */, Ops);
4853
4854 SPIRVInstList.push_back(Inst);
4855
4856 break;
4857 }
4858
4859 // Nothing to do for abs with uint. Map abs's operand ID to VMap for abs
4860 // with unit.
4861 if (Callee->getName().equals("_Z3absj") ||
4862 Callee->getName().equals("_Z3absDv2_j") ||
4863 Callee->getName().equals("_Z3absDv3_j") ||
4864 Callee->getName().equals("_Z3absDv4_j")) {
4865 VMap[&I] = VMap[Call->getOperand(0)];
4866 break;
4867 }
4868
4869 // barrier is converted to OpControlBarrier
4870 if (Callee->getName().equals("__spirv_control_barrier")) {
4871 //
4872 // Generate OpControlBarrier.
4873 //
4874 // Ops[0] = Execution Scope ID
4875 // Ops[1] = Memory Scope ID
4876 // Ops[2] = Memory Semantics ID
4877 //
4878 Value *ExecutionScope = Call->getArgOperand(0);
4879 Value *MemoryScope = Call->getArgOperand(1);
4880 Value *MemorySemantics = Call->getArgOperand(2);
4881
4882 SPIRVOperand *Ops[3] = {
4883 new SPIRVOperand(SPIRVOperandType::NUMBERID, VMap[ExecutionScope]),
4884 new SPIRVOperand(SPIRVOperandType::NUMBERID, VMap[MemoryScope]),
4885 new SPIRVOperand(SPIRVOperandType::NUMBERID, VMap[MemorySemantics])};
4886
4887 SPIRVInstList.push_back(
4888 new SPIRVInstruction(4, spv::OpControlBarrier, 0 /* No id */, Ops));
4889 break;
4890 }
4891
4892 // memory barrier is converted to OpMemoryBarrier
4893 if (Callee->getName().equals("__spirv_memory_barrier")) {
4894 //
4895 // Generate OpMemoryBarrier.
4896 //
4897 // Ops[0] = Memory Scope ID
4898 // Ops[1] = Memory Semantics ID
4899 //
4900 SPIRVOperandList Ops;
4901
4902 Value *MemoryScope = Call->getArgOperand(0);
4903 Value *MemorySemantics = Call->getArgOperand(1);
4904
4905 uint32_t MemoryScopeID = VMap[MemoryScope];
4906 Ops.push_back(
4907 new SPIRVOperand(SPIRVOperandType::NUMBERID, MemoryScopeID));
4908
4909 uint32_t MemorySemanticsID = VMap[MemorySemantics];
4910 Ops.push_back(
4911 new SPIRVOperand(SPIRVOperandType::NUMBERID, MemorySemanticsID));
4912
4913 SPIRVInstruction *Inst =
4914 new SPIRVInstruction(3, spv::OpMemoryBarrier, 0 /* No id */, Ops);
4915 SPIRVInstList.push_back(Inst);
4916 break;
4917 }
4918
4919 // isinf is converted to OpIsInf
4920 if (Callee->getName().equals("__spirv_isinff") ||
4921 Callee->getName().equals("__spirv_isinfDv2_f") ||
4922 Callee->getName().equals("__spirv_isinfDv3_f") ||
4923 Callee->getName().equals("__spirv_isinfDv4_f")) {
4924 //
4925 // Generate OpIsInf.
4926 //
4927 // Ops[0] = Result Type ID
4928 // Ops[1] = X ID
4929 //
4930 SPIRVOperandList Ops;
4931
4932 uint32_t TyID = lookupType(I.getType());
4933 SPIRVOperand *ResTyIDOp =
4934 new SPIRVOperand(SPIRVOperandType::NUMBERID, TyID);
4935 Ops.push_back(ResTyIDOp);
4936
4937 uint32_t XID = VMap[Call->getArgOperand(0)];
4938 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, XID));
4939
4940 VMap[&I] = nextID;
4941
4942 SPIRVInstruction *Inst =
4943 new SPIRVInstruction(4, spv::OpIsInf, nextID++, Ops);
4944 SPIRVInstList.push_back(Inst);
4945 break;
4946 }
4947
4948 // isnan is converted to OpIsNan
4949 if (Callee->getName().equals("__spirv_isnanf") ||
4950 Callee->getName().equals("__spirv_isnanDv2_f") ||
4951 Callee->getName().equals("__spirv_isnanDv3_f") ||
4952 Callee->getName().equals("__spirv_isnanDv4_f")) {
4953 //
4954 // Generate OpIsInf.
4955 //
4956 // Ops[0] = Result Type ID
4957 // Ops[1] = X ID
4958 //
4959 SPIRVOperandList Ops;
4960
4961 uint32_t TyID = lookupType(I.getType());
4962 SPIRVOperand *ResTyIDOp =
4963 new SPIRVOperand(SPIRVOperandType::NUMBERID, TyID);
4964 Ops.push_back(ResTyIDOp);
4965
4966 uint32_t XID = VMap[Call->getArgOperand(0)];
4967 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, XID));
4968
4969 VMap[&I] = nextID;
4970
4971 SPIRVInstruction *Inst =
4972 new SPIRVInstruction(4, spv::OpIsNan, nextID++, Ops);
4973 SPIRVInstList.push_back(Inst);
4974 break;
4975 }
4976
4977 // all is converted to OpAll
4978 if (Callee->getName().equals("__spirv_allDv2_i") ||
4979 Callee->getName().equals("__spirv_allDv3_i") ||
4980 Callee->getName().equals("__spirv_allDv4_i")) {
4981 //
4982 // Generate OpAll.
4983 //
4984 // Ops[0] = Result Type ID
4985 // Ops[1] = Vector ID
4986 //
4987 SPIRVOperandList Ops;
4988
4989 uint32_t TyID = lookupType(I.getType());
4990 SPIRVOperand *ResTyIDOp =
4991 new SPIRVOperand(SPIRVOperandType::NUMBERID, TyID);
4992 Ops.push_back(ResTyIDOp);
4993
4994 uint32_t VectorID = VMap[Call->getArgOperand(0)];
4995 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, VectorID));
4996
4997 VMap[&I] = nextID;
4998
4999 SPIRVInstruction *Inst =
5000 new SPIRVInstruction(4, spv::OpAll, nextID++, Ops);
5001 SPIRVInstList.push_back(Inst);
5002 break;
5003 }
5004
5005 // any is converted to OpAny
5006 if (Callee->getName().equals("__spirv_anyDv2_i") ||
5007 Callee->getName().equals("__spirv_anyDv3_i") ||
5008 Callee->getName().equals("__spirv_anyDv4_i")) {
5009 //
5010 // Generate OpAny.
5011 //
5012 // Ops[0] = Result Type ID
5013 // Ops[1] = Vector ID
5014 //
5015 SPIRVOperandList Ops;
5016
5017 uint32_t TyID = lookupType(I.getType());
5018 SPIRVOperand *ResTyIDOp =
5019 new SPIRVOperand(SPIRVOperandType::NUMBERID, TyID);
5020 Ops.push_back(ResTyIDOp);
5021
5022 uint32_t VectorID = VMap[Call->getArgOperand(0)];
5023 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, VectorID));
5024
5025 VMap[&I] = nextID;
5026
5027 SPIRVInstruction *Inst =
5028 new SPIRVInstruction(4, spv::OpAny, nextID++, Ops);
5029 SPIRVInstList.push_back(Inst);
5030 break;
5031 }
5032
5033 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
5034 // Additionally, OpTypeSampledImage is generated.
5035 if (Callee->getName().equals(
5036 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
5037 Callee->getName().equals(
5038 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
5039 //
5040 // Generate OpSampledImage.
5041 //
5042 // Ops[0] = Result Type ID
5043 // Ops[1] = Image ID
5044 // Ops[2] = Sampler ID
5045 //
5046 SPIRVOperandList Ops;
5047
5048 Value *Image = Call->getArgOperand(0);
5049 Value *Sampler = Call->getArgOperand(1);
5050 Value *Coordinate = Call->getArgOperand(2);
5051
5052 TypeMapType &OpImageTypeMap = getImageTypeMap();
5053 Type *ImageTy = Image->getType()->getPointerElementType();
5054 uint32_t ImageTyID = OpImageTypeMap[ImageTy];
5055 SPIRVOperand *ResTyIDOp =
5056 new SPIRVOperand(SPIRVOperandType::NUMBERID, ImageTyID);
5057 Ops.push_back(ResTyIDOp);
5058
5059 uint32_t ImageID = VMap[Image];
5060 SPIRVOperand *ImageIDOp =
5061 new SPIRVOperand(SPIRVOperandType::NUMBERID, ImageID);
5062 Ops.push_back(ImageIDOp);
5063
5064 uint32_t SamplerID = VMap[Sampler];
5065 SPIRVOperand *SamplerIDOp =
5066 new SPIRVOperand(SPIRVOperandType::NUMBERID, SamplerID);
5067 Ops.push_back(SamplerIDOp);
5068
5069 uint32_t SampledImageID = nextID;
5070
5071 SPIRVInstruction *Inst =
5072 new SPIRVInstruction(5, spv::OpSampledImage, nextID++, Ops);
5073 SPIRVInstList.push_back(Inst);
5074
5075 //
5076 // Generate OpImageSampleExplicitLod.
5077 //
5078 // Ops[0] = Result Type ID
5079 // Ops[1] = Sampled Image ID
5080 // Ops[2] = Coordinate ID
5081 // Ops[3] = Image Operands Type ID
5082 // Ops[4] ... Ops[n] = Operands ID
5083 //
5084 Ops.clear();
5085
5086 uint32_t RetTyID = lookupType(Call->getType());
5087 ResTyIDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, RetTyID);
5088 Ops.push_back(ResTyIDOp);
5089
5090 SPIRVOperand *SampledImageIDOp =
5091 new SPIRVOperand(SPIRVOperandType::NUMBERID, SampledImageID);
5092 Ops.push_back(SampledImageIDOp);
5093
5094 uint32_t CoordinateID = VMap[Coordinate];
5095 SPIRVOperand *CoordinateIDOp =
5096 new SPIRVOperand(SPIRVOperandType::NUMBERID, CoordinateID);
5097 Ops.push_back(CoordinateIDOp);
5098
5099 std::vector<uint32_t> LiteralNum;
5100 LiteralNum.push_back(spv::ImageOperandsLodMask);
5101 SPIRVOperand *ImageOperandTyIDOp =
5102 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
5103 Ops.push_back(ImageOperandTyIDOp);
5104
5105 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
5106 uint32_t OperandID = VMap[CstFP0];
5107 SPIRVOperand *OperandIDOp =
5108 new SPIRVOperand(SPIRVOperandType::NUMBERID, OperandID);
5109 Ops.push_back(OperandIDOp);
5110
5111 VMap[&I] = nextID;
5112
5113 Inst =
5114 new SPIRVInstruction(7, spv::OpImageSampleExplicitLod, nextID++, Ops);
5115 SPIRVInstList.push_back(Inst);
5116 break;
5117 }
5118
5119 // write_imagef is mapped to OpImageWrite.
5120 if (Callee->getName().equals(
5121 "_Z12write_imagef14ocl_image2d_woDv2_iDv4_f") ||
5122 Callee->getName().equals(
5123 "_Z12write_imagef14ocl_image3d_woDv4_iDv4_f")) {
5124 //
5125 // Generate OpImageWrite.
5126 //
5127 // Ops[0] = Image ID
5128 // Ops[1] = Coordinate ID
5129 // Ops[2] = Texel ID
5130 // Ops[3] = (Optional) Image Operands Type (Literal Number)
5131 // Ops[4] ... Ops[n] = (Optional) Operands ID
5132 //
5133 SPIRVOperandList Ops;
5134
5135 Value *Image = Call->getArgOperand(0);
5136 Value *Coordinate = Call->getArgOperand(1);
5137 Value *Texel = Call->getArgOperand(2);
5138
5139 uint32_t ImageID = VMap[Image];
5140 SPIRVOperand *ImageIDOp =
5141 new SPIRVOperand(SPIRVOperandType::NUMBERID, ImageID);
5142 Ops.push_back(ImageIDOp);
5143
5144 uint32_t CoordinateID = VMap[Coordinate];
5145 SPIRVOperand *CoordinateIDOp =
5146 new SPIRVOperand(SPIRVOperandType::NUMBERID, CoordinateID);
5147 Ops.push_back(CoordinateIDOp);
5148
5149 uint32_t TexelID = VMap[Texel];
5150 SPIRVOperand *TexelIDOp =
5151 new SPIRVOperand(SPIRVOperandType::NUMBERID, TexelID);
5152 Ops.push_back(TexelIDOp);
5153
5154 SPIRVInstruction *Inst =
5155 new SPIRVInstruction(4, spv::OpImageWrite, 0 /* No id */, Ops);
5156 SPIRVInstList.push_back(Inst);
5157 break;
5158 }
5159
David Neto5c22a252018-03-15 16:07:41 -04005160 // get_image_width is mapped to OpImageQuerySize
5161 if (Callee->getName().equals("_Z15get_image_width14ocl_image2d_ro") ||
5162 Callee->getName().equals("_Z15get_image_width14ocl_image2d_wo") ||
5163 Callee->getName().equals("_Z16get_image_height14ocl_image2d_ro") ||
5164 Callee->getName().equals("_Z16get_image_height14ocl_image2d_wo")) {
5165 //
5166 // Generate OpImageQuerySize, then pull out the right component.
5167 // Assume 2D image for now.
5168 //
5169 // Ops[0] = Image ID
5170 //
5171 // %sizes = OpImageQuerySizes %uint2 %im
5172 // %result = OpCompositeExtract %uint %sizes 0-or-1
5173 SPIRVOperandList Ops;
5174
5175 // Implement:
5176 // %sizes = OpImageQuerySizes %uint2 %im
5177 uint32_t SizesTypeID =
5178 TypeMap[VectorType::get(Type::getInt32Ty(Context), 2)];
5179 SPIRVOperand *SizesTypeIDOp =
5180 new SPIRVOperand(SPIRVOperandType::NUMBERID, SizesTypeID);
5181 Ops.push_back(SizesTypeIDOp);
5182
5183 Value *Image = Call->getArgOperand(0);
5184 uint32_t ImageID = VMap[Image];
5185 SPIRVOperand *ImageIDOp =
5186 new SPIRVOperand(SPIRVOperandType::NUMBERID, ImageID);
5187 Ops.push_back(ImageIDOp);
5188
5189 uint32_t SizesID = nextID++;
5190 SPIRVInstruction *QueryInst =
5191 new SPIRVInstruction(4, spv::OpImageQuerySize, SizesID, Ops);
5192 SPIRVInstList.push_back(QueryInst);
5193
5194 // Reset value map entry since we generated an intermediate instruction.
5195 VMap[&I] = nextID;
5196
5197 // Implement:
5198 // %result = OpCompositeExtract %uint %sizes 0-or-1
5199 Ops.clear();
5200
5201 SPIRVOperand *ResultTypeOp =
5202 new SPIRVOperand(SPIRVOperandType::NUMBERID, TypeMap[I.getType()]);
5203 Ops.push_back(ResultTypeOp);
5204
5205 SPIRVOperand *SizesOp =
5206 new SPIRVOperand(SPIRVOperandType::NUMBERID, SizesID);
5207 Ops.push_back(SizesOp);
5208
5209 uint32_t component = Callee->getName().contains("height") ? 1 : 0;
5210 Ops.push_back(new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, component));
5211
5212 SPIRVInstruction *Inst =
5213 new SPIRVInstruction(5, spv::OpCompositeExtract, nextID++, Ops);
5214 SPIRVInstList.push_back(Inst);
5215 break;
5216 }
5217
David Neto22f144c2017-06-12 14:26:21 -04005218 // Call instrucion is deferred because it needs function's ID. Record
5219 // slot's location on SPIRVInstructionList.
5220 DeferredInsts.push_back(
5221 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
5222
David Neto3fbb4072017-10-16 11:28:14 -04005223 // Check whether the implementation of this call uses an extended
5224 // instruction plus one more value-producing instruction. If so, then
5225 // reserve the id for the extra value-producing slot.
5226 glsl::ExtInst EInst = getIndirectExtInstEnum(Callee->getName());
5227 if (EInst != kGlslExtInstBad) {
5228 // Reserve a spot for the extra value.
David Neto4d02a532017-09-17 12:57:44 -04005229 // Increase nextID.
David Neto22f144c2017-06-12 14:26:21 -04005230 VMap[&I] = nextID;
5231 nextID++;
5232 }
5233 break;
5234 }
5235 case Instruction::Ret: {
5236 unsigned NumOps = I.getNumOperands();
5237 if (NumOps == 0) {
5238 //
5239 // Generate OpReturn.
5240 //
5241
5242 // Empty Ops
5243 SPIRVOperandList Ops;
5244 SPIRVInstruction *Inst =
5245 new SPIRVInstruction(1, spv::OpReturn, 0 /* No id */, Ops);
5246 SPIRVInstList.push_back(Inst);
5247 } else {
5248 //
5249 // Generate OpReturnValue.
5250 //
5251
5252 // Ops[0] = Return Value ID
5253 SPIRVOperandList Ops;
5254 uint32_t RetValID = VMap[I.getOperand(0)];
5255 SPIRVOperand *RetValIDOp =
5256 new SPIRVOperand(SPIRVOperandType::NUMBERID, RetValID);
5257 Ops.push_back(RetValIDOp);
5258
5259 SPIRVInstruction *Inst =
5260 new SPIRVInstruction(2, spv::OpReturnValue, 0 /* No id */, Ops);
5261 SPIRVInstList.push_back(Inst);
5262 break;
5263 }
5264 break;
5265 }
5266 }
5267}
5268
5269void SPIRVProducerPass::GenerateFuncEpilogue() {
5270 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5271
5272 //
5273 // Generate OpFunctionEnd
5274 //
5275
5276 // Empty Ops
5277 SPIRVOperandList Ops;
5278 SPIRVInstruction *Inst =
5279 new SPIRVInstruction(1, spv::OpFunctionEnd, 0 /* No id */, Ops);
5280 SPIRVInstList.push_back(Inst);
5281}
5282
5283bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
5284 LLVMContext &Context = Ty->getContext();
5285 if (Ty->isVectorTy()) {
5286 if (Ty->getVectorElementType() == Type::getInt8Ty(Context) &&
5287 Ty->getVectorNumElements() == 4) {
5288 return true;
5289 }
5290 }
5291
5292 return false;
5293}
5294
5295void SPIRVProducerPass::HandleDeferredInstruction() {
5296 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5297 ValueMapType &VMap = getValueMap();
5298 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
5299
5300 for (auto DeferredInst = DeferredInsts.rbegin();
5301 DeferredInst != DeferredInsts.rend(); ++DeferredInst) {
5302 Value *Inst = std::get<0>(*DeferredInst);
5303 SPIRVInstructionList::iterator InsertPoint = ++std::get<1>(*DeferredInst);
5304 if (InsertPoint != SPIRVInstList.end()) {
5305 while ((*InsertPoint)->getOpcode() == spv::OpPhi) {
5306 ++InsertPoint;
5307 }
5308 }
5309
5310 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
5311 // Check whether basic block, which has this branch instruction, is loop
5312 // header or not. If it is loop header, generate OpLoopMerge and
5313 // OpBranchConditional.
5314 Function *Func = Br->getParent()->getParent();
5315 DominatorTree &DT =
5316 getAnalysis<DominatorTreeWrapperPass>(*Func).getDomTree();
5317 const LoopInfo &LI =
5318 getAnalysis<LoopInfoWrapperPass>(*Func).getLoopInfo();
5319
5320 BasicBlock *BrBB = Br->getParent();
5321 if (LI.isLoopHeader(BrBB)) {
5322 Value *ContinueBB = nullptr;
5323 Value *MergeBB = nullptr;
5324
5325 Loop *L = LI.getLoopFor(BrBB);
5326 MergeBB = L->getExitBlock();
5327 if (!MergeBB) {
5328 // StructurizeCFG pass converts CFG into triangle shape and the cfg
5329 // has regions with single entry/exit. As a result, loop should not
5330 // have multiple exits.
5331 llvm_unreachable("Loop has multiple exits???");
5332 }
5333
5334 if (L->isLoopLatch(BrBB)) {
5335 ContinueBB = BrBB;
5336 } else {
5337 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
5338 // block.
5339 BasicBlock *Header = L->getHeader();
5340 BasicBlock *Latch = L->getLoopLatch();
5341 for (BasicBlock *BB : L->blocks()) {
5342 if (BB == Header) {
5343 continue;
5344 }
5345
5346 // Check whether block dominates block with back-edge.
5347 if (DT.dominates(BB, Latch)) {
5348 ContinueBB = BB;
5349 }
5350 }
5351
5352 if (!ContinueBB) {
5353 llvm_unreachable("Wrong continue block from loop");
5354 }
5355 }
5356
5357 //
5358 // Generate OpLoopMerge.
5359 //
5360 // Ops[0] = Merge Block ID
5361 // Ops[1] = Continue Target ID
5362 // Ops[2] = Selection Control
5363 SPIRVOperandList Ops;
5364
5365 // StructurizeCFG pass already manipulated CFG. Just use false block of
5366 // branch instruction as merge block.
5367 uint32_t MergeBBID = VMap[MergeBB];
5368 SPIRVOperand *MergeBBIDOp =
5369 new SPIRVOperand(SPIRVOperandType::NUMBERID, MergeBBID);
5370 Ops.push_back(MergeBBIDOp);
5371
5372 uint32_t ContinueBBID = VMap[ContinueBB];
5373 SPIRVOperand *ContinueBBIDOp =
5374 new SPIRVOperand(SPIRVOperandType::NUMBERID, ContinueBBID);
5375 Ops.push_back(ContinueBBIDOp);
5376
5377 SPIRVOperand *SelectionControlOp = new SPIRVOperand(
5378 SPIRVOperandType::NUMBERID, spv::SelectionControlMaskNone);
5379 Ops.push_back(SelectionControlOp);
5380
5381 SPIRVInstruction *MergeInst =
5382 new SPIRVInstruction(4, spv::OpLoopMerge, 0 /* No id */, Ops);
5383 SPIRVInstList.insert(InsertPoint, MergeInst);
5384
5385 } else if (Br->isConditional()) {
5386 bool HasBackEdge = false;
5387
5388 for (unsigned i = 0; i < Br->getNumSuccessors(); i++) {
5389 if (LI.isLoopHeader(Br->getSuccessor(i))) {
5390 HasBackEdge = true;
5391 }
5392 }
5393 if (!HasBackEdge) {
5394 //
5395 // Generate OpSelectionMerge.
5396 //
5397 // Ops[0] = Merge Block ID
5398 // Ops[1] = Selection Control
5399 SPIRVOperandList Ops;
5400
5401 // StructurizeCFG pass already manipulated CFG. Just use false block
5402 // of branch instruction as merge block.
5403 uint32_t MergeBBID = VMap[Br->getSuccessor(1)];
5404 SPIRVOperand *MergeBBIDOp =
5405 new SPIRVOperand(SPIRVOperandType::NUMBERID, MergeBBID);
5406 Ops.push_back(MergeBBIDOp);
5407
5408 SPIRVOperand *SelectionControlOp = new SPIRVOperand(
5409 SPIRVOperandType::NUMBERID, spv::SelectionControlMaskNone);
5410 Ops.push_back(SelectionControlOp);
5411
5412 SPIRVInstruction *MergeInst = new SPIRVInstruction(
5413 3, spv::OpSelectionMerge, 0 /* No id */, Ops);
5414 SPIRVInstList.insert(InsertPoint, MergeInst);
5415 }
5416 }
5417
5418 if (Br->isConditional()) {
5419 //
5420 // Generate OpBranchConditional.
5421 //
5422 // Ops[0] = Condition ID
5423 // Ops[1] = True Label ID
5424 // Ops[2] = False Label ID
5425 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
5426 SPIRVOperandList Ops;
5427
5428 uint32_t CondID = VMap[Br->getCondition()];
5429 SPIRVOperand *CondIDOp =
5430 new SPIRVOperand(SPIRVOperandType::NUMBERID, CondID);
5431 Ops.push_back(CondIDOp);
5432
5433 uint32_t TrueBBID = VMap[Br->getSuccessor(0)];
5434 SPIRVOperand *TrueBBIDOp =
5435 new SPIRVOperand(SPIRVOperandType::NUMBERID, TrueBBID);
5436 Ops.push_back(TrueBBIDOp);
5437
5438 uint32_t FalseBBID = VMap[Br->getSuccessor(1)];
5439 SPIRVOperand *FalseBBIDOp =
5440 new SPIRVOperand(SPIRVOperandType::NUMBERID, FalseBBID);
5441 Ops.push_back(FalseBBIDOp);
5442
5443 SPIRVInstruction *BrInst = new SPIRVInstruction(
5444 4, spv::OpBranchConditional, 0 /* No id */, Ops);
5445 SPIRVInstList.insert(InsertPoint, BrInst);
5446 } else {
5447 //
5448 // Generate OpBranch.
5449 //
5450 // Ops[0] = Target Label ID
5451 SPIRVOperandList Ops;
5452
5453 uint32_t TargetID = VMap[Br->getSuccessor(0)];
5454 SPIRVOperand *TargetIDOp =
5455 new SPIRVOperand(SPIRVOperandType::NUMBERID, TargetID);
5456 Ops.push_back(TargetIDOp);
5457
5458 SPIRVInstList.insert(
5459 InsertPoint,
5460 new SPIRVInstruction(2, spv::OpBranch, 0 /* No id */, Ops));
5461 }
5462 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
5463 //
5464 // Generate OpPhi.
5465 //
5466 // Ops[0] = Result Type ID
5467 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
5468 SPIRVOperandList Ops;
5469
5470 uint32_t ResTyID = lookupType(PHI->getType());
5471 SPIRVOperand *ResTyIDOp =
5472 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
5473 Ops.push_back(ResTyIDOp);
5474
5475 uint16_t WordCount = 3;
5476 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
5477 uint32_t VarID = VMap[PHI->getIncomingValue(i)];
5478 SPIRVOperand *VarIDOp =
5479 new SPIRVOperand(SPIRVOperandType::NUMBERID, VarID);
5480 Ops.push_back(VarIDOp);
5481
5482 uint32_t ParentID = VMap[PHI->getIncomingBlock(i)];
5483 SPIRVOperand *ParentIDOp =
5484 new SPIRVOperand(SPIRVOperandType::NUMBERID, ParentID);
5485 Ops.push_back(ParentIDOp);
5486
5487 WordCount += 2;
5488 }
5489
5490 SPIRVInstList.insert(
5491 InsertPoint, new SPIRVInstruction(WordCount, spv::OpPhi,
5492 std::get<2>(*DeferredInst), Ops));
5493 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
5494 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04005495 auto callee_name = Callee->getName();
5496 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04005497
5498 if (EInst) {
5499 uint32_t &ExtInstImportID = getOpExtInstImportID();
5500
5501 //
5502 // Generate OpExtInst.
5503 //
5504
5505 // Ops[0] = Result Type ID
5506 // Ops[1] = Set ID (OpExtInstImport ID)
5507 // Ops[2] = Instruction Number (Literal Number)
5508 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5509 SPIRVOperandList Ops;
5510
5511 uint32_t ResTyID = lookupType(Call->getType());
5512 SPIRVOperand *ResTyIDOp =
5513 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
5514 Ops.push_back(ResTyIDOp);
5515
5516 SPIRVOperand *SetIDOp =
5517 new SPIRVOperand(SPIRVOperandType::NUMBERID, ExtInstImportID);
5518 Ops.push_back(SetIDOp);
5519
5520 std::vector<uint32_t> LiteralNum;
5521 LiteralNum.push_back(EInst);
5522 SPIRVOperand *InstructionOp =
5523 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
5524 Ops.push_back(InstructionOp);
5525
5526 uint16_t WordCount = 5;
5527
5528 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5529 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
5530 uint32_t ArgID = VMap[Call->getOperand(i)];
5531 SPIRVOperand *ArgIDOp =
5532 new SPIRVOperand(SPIRVOperandType::NUMBERID, ArgID);
5533 Ops.push_back(ArgIDOp);
5534 WordCount++;
5535 }
5536
5537 SPIRVInstruction *ExtInst = new SPIRVInstruction(
5538 WordCount, spv::OpExtInst, std::get<2>(*DeferredInst), Ops);
5539 SPIRVInstList.insert(InsertPoint, ExtInst);
5540
David Neto3fbb4072017-10-16 11:28:14 -04005541 const auto IndirectExtInst = getIndirectExtInstEnum(callee_name);
5542 if (IndirectExtInst != kGlslExtInstBad) {
5543 // Generate one more instruction that uses the result of the extended
5544 // instruction. Its result id is one more than the id of the
5545 // extended instruction.
David Neto22f144c2017-06-12 14:26:21 -04005546 LLVMContext &Context =
5547 Call->getParent()->getParent()->getParent()->getContext();
David Neto22f144c2017-06-12 14:26:21 -04005548
David Neto3fbb4072017-10-16 11:28:14 -04005549 auto generate_extra_inst = [this, &Context, &Call, &DeferredInst,
5550 &VMap, &SPIRVInstList, &InsertPoint](
5551 spv::Op opcode, Constant *constant) {
5552 //
5553 // Generate instruction like:
5554 // result = opcode constant <extinst-result>
5555 //
5556 // Ops[0] = Result Type ID
5557 // Ops[1] = Operand 0 ;; the constant, suitably splatted
5558 // Ops[2] = Operand 1 ;; the result of the extended instruction
5559 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04005560
David Neto3fbb4072017-10-16 11:28:14 -04005561 Type *resultTy = Call->getType();
5562 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID,
5563 lookupType(resultTy)));
5564
5565 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
5566 constant = ConstantVector::getSplat(
5567 static_cast<unsigned>(vectorTy->getNumElements()), constant);
5568 }
5569 uint32_t Op0ID = VMap[constant];
5570 SPIRVOperand *Op0IDOp =
5571 new SPIRVOperand(SPIRVOperandType::NUMBERID, Op0ID);
5572 Ops.push_back(Op0IDOp);
5573
5574 SPIRVOperand *Op1IDOp = new SPIRVOperand(
5575 SPIRVOperandType::NUMBERID, std::get<2>(*DeferredInst));
5576 Ops.push_back(Op1IDOp);
5577
5578 SPIRVInstList.insert(
5579 InsertPoint,
5580 new SPIRVInstruction(5, opcode, std::get<2>(*DeferredInst) + 1,
5581 Ops));
5582 };
5583
5584 switch (IndirectExtInst) {
5585 case glsl::ExtInstFindUMsb: // Implementing clz
5586 generate_extra_inst(
5587 spv::OpISub, ConstantInt::get(Type::getInt32Ty(Context), 31));
5588 break;
5589 case glsl::ExtInstAcos: // Implementing acospi
5590 case glsl::ExtInstAsin: // Implementing asinpi
5591 case glsl::ExtInstAtan2: // Implementing atan2pi
5592 generate_extra_inst(
5593 spv::OpFMul,
5594 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
5595 break;
5596
5597 default:
5598 assert(false && "internally inconsistent");
David Neto4d02a532017-09-17 12:57:44 -04005599 }
David Neto22f144c2017-06-12 14:26:21 -04005600 }
David Neto3fbb4072017-10-16 11:28:14 -04005601
David Neto22f144c2017-06-12 14:26:21 -04005602 } else if (Callee->getName().equals("_Z8popcounti") ||
5603 Callee->getName().equals("_Z8popcountj") ||
5604 Callee->getName().equals("_Z8popcountDv2_i") ||
5605 Callee->getName().equals("_Z8popcountDv3_i") ||
5606 Callee->getName().equals("_Z8popcountDv4_i") ||
5607 Callee->getName().equals("_Z8popcountDv2_j") ||
5608 Callee->getName().equals("_Z8popcountDv3_j") ||
5609 Callee->getName().equals("_Z8popcountDv4_j")) {
5610 //
5611 // Generate OpBitCount
5612 //
5613 // Ops[0] = Result Type ID
5614 // Ops[1] = Base ID
5615 SPIRVOperand *Ops[2]{new SPIRVOperand(SPIRVOperandType::NUMBERID,
5616 lookupType(Call->getType())),
5617 new SPIRVOperand(SPIRVOperandType::NUMBERID,
5618 VMap[Call->getOperand(0)])};
5619
5620 SPIRVInstList.insert(
5621 InsertPoint, new SPIRVInstruction(4, spv::OpBitCount,
5622 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005623
5624 } else if (Callee->getName().startswith(kCompositeConstructFunctionPrefix)) {
5625
5626 // Generate an OpCompositeConstruct
5627 SPIRVOperandList Ops;
5628
5629 // The result type.
5630 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID,
5631 lookupType(Call->getType())));
5632
5633 for (Use &use : Call->arg_operands()) {
5634 Value* val = use.get();
5635 Ops.push_back(
5636 new SPIRVOperand(SPIRVOperandType::NUMBERID, VMap[use.get()]));
5637 }
5638
5639 SPIRVInstList.insert(
5640 InsertPoint,
5641 new SPIRVInstruction(2 + Ops.size(), spv::OpCompositeConstruct,
5642 std::get<2>(*DeferredInst), Ops));
5643
David Neto22f144c2017-06-12 14:26:21 -04005644 } else {
5645 //
5646 // Generate OpFunctionCall.
5647 //
5648
5649 // Ops[0] = Result Type ID
5650 // Ops[1] = Callee Function ID
5651 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
5652 SPIRVOperandList Ops;
5653
5654 uint32_t ResTyID = lookupType(Call->getType());
5655 SPIRVOperand *ResTyIDOp =
5656 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
5657 Ops.push_back(ResTyIDOp);
5658
5659 uint32_t CalleeID = VMap[Callee];
David Neto43568eb2017-10-13 18:25:25 -04005660 if (CalleeID == 0) {
5661 errs() << "Can't translate function call. Missing builtin? "
5662 << Callee->getName() << " in: " << *Call << "\n";
5663 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
5664 // causes an infinite loop. Instead, go ahead and generate
5665 // the bad function call. A validator will catch the 0-Id.
5666 // llvm_unreachable("Can't translate function call");
5667 }
David Neto22f144c2017-06-12 14:26:21 -04005668
5669 SPIRVOperand *CalleeIDOp =
5670 new SPIRVOperand(SPIRVOperandType::NUMBERID, CalleeID);
5671 Ops.push_back(CalleeIDOp);
5672
5673 uint16_t WordCount = 4;
5674
5675 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5676 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
5677 uint32_t ArgID = VMap[Call->getOperand(i)];
5678 SPIRVOperand *ArgIDOp =
5679 new SPIRVOperand(SPIRVOperandType::NUMBERID, ArgID);
5680 Ops.push_back(ArgIDOp);
5681 WordCount++;
5682 }
5683
5684 SPIRVInstruction *CallInst = new SPIRVInstruction(
5685 WordCount, spv::OpFunctionCall, std::get<2>(*DeferredInst), Ops);
5686 SPIRVInstList.insert(InsertPoint, CallInst);
5687 }
5688 }
5689 }
5690}
5691
David Neto1a1a0582017-07-07 12:01:44 -04005692void SPIRVProducerPass::HandleDeferredDecorations(const DataLayout &DL) {
5693 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
5694 // instructions we generated earlier.
5695 if (getPointerTypesNeedingArrayStride().empty())
5696 return;
5697
5698 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto1a1a0582017-07-07 12:01:44 -04005699
5700 // Find an iterator pointing just past the last decoration.
5701 bool seen_decorations = false;
5702 auto DecoInsertPoint =
5703 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
5704 [&seen_decorations](SPIRVInstruction *Inst) -> bool {
5705 const bool is_decoration =
5706 Inst->getOpcode() == spv::OpDecorate ||
5707 Inst->getOpcode() == spv::OpMemberDecorate;
5708 if (is_decoration) {
5709 seen_decorations = true;
5710 return false;
5711 } else {
5712 return seen_decorations;
5713 }
5714 });
5715
5716 for (auto *type : getPointerTypesNeedingArrayStride()) {
5717 auto *ptrType = cast<PointerType>(type);
5718
5719 // Ops[0] = Target ID
5720 // Ops[1] = Decoration (ArrayStride)
5721 // Ops[2] = Stride number (Literal Number)
5722 SPIRVOperandList Ops;
5723
5724 Ops.push_back(
5725 new SPIRVOperand(SPIRVOperandType::NUMBERID, lookupType(ptrType)));
5726 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID,
5727 spv::DecorationArrayStride));
5728 Type *elemTy = ptrType->getElementType();
5729 // Same as DL.getIndexedOfffsetInType( elemTy, { 1 } );
Neil Henning39672102017-09-29 14:33:13 +01005730 const uint32_t stride = static_cast<uint32_t>(DL.getTypeAllocSize(elemTy));
David Neto1a1a0582017-07-07 12:01:44 -04005731 Ops.push_back(new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, stride));
5732
5733 SPIRVInstruction *DecoInst =
5734 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, Ops);
5735 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
5736 }
5737}
5738
David Neto22f144c2017-06-12 14:26:21 -04005739glsl::ExtInst SPIRVProducerPass::getExtInstEnum(StringRef Name) {
5740 return StringSwitch<glsl::ExtInst>(Name)
5741 .Case("_Z3absi", glsl::ExtInst::ExtInstSAbs)
5742 .Case("_Z3absDv2_i", glsl::ExtInst::ExtInstSAbs)
5743 .Case("_Z3absDv3_i", glsl::ExtInst::ExtInstSAbs)
5744 .Case("_Z3absDv4_i", glsl::ExtInst::ExtInstSAbs)
5745 .Case("_Z5clampiii", glsl::ExtInst::ExtInstSClamp)
5746 .Case("_Z5clampDv2_iS_S_", glsl::ExtInst::ExtInstSClamp)
5747 .Case("_Z5clampDv3_iS_S_", glsl::ExtInst::ExtInstSClamp)
5748 .Case("_Z5clampDv4_iS_S_", glsl::ExtInst::ExtInstSClamp)
5749 .Case("_Z5clampjjj", glsl::ExtInst::ExtInstUClamp)
5750 .Case("_Z5clampDv2_jS_S_", glsl::ExtInst::ExtInstUClamp)
5751 .Case("_Z5clampDv3_jS_S_", glsl::ExtInst::ExtInstUClamp)
5752 .Case("_Z5clampDv4_jS_S_", glsl::ExtInst::ExtInstUClamp)
5753 .Case("_Z5clampfff", glsl::ExtInst::ExtInstFClamp)
5754 .Case("_Z5clampDv2_fS_S_", glsl::ExtInst::ExtInstFClamp)
5755 .Case("_Z5clampDv3_fS_S_", glsl::ExtInst::ExtInstFClamp)
5756 .Case("_Z5clampDv4_fS_S_", glsl::ExtInst::ExtInstFClamp)
David Neto22f144c2017-06-12 14:26:21 -04005757 .Case("_Z3maxii", glsl::ExtInst::ExtInstSMax)
5758 .Case("_Z3maxDv2_iS_", glsl::ExtInst::ExtInstSMax)
5759 .Case("_Z3maxDv3_iS_", glsl::ExtInst::ExtInstSMax)
5760 .Case("_Z3maxDv4_iS_", glsl::ExtInst::ExtInstSMax)
5761 .Case("_Z3maxjj", glsl::ExtInst::ExtInstUMax)
5762 .Case("_Z3maxDv2_jS_", glsl::ExtInst::ExtInstUMax)
5763 .Case("_Z3maxDv3_jS_", glsl::ExtInst::ExtInstUMax)
5764 .Case("_Z3maxDv4_jS_", glsl::ExtInst::ExtInstUMax)
5765 .Case("_Z3maxff", glsl::ExtInst::ExtInstFMax)
5766 .Case("_Z3maxDv2_fS_", glsl::ExtInst::ExtInstFMax)
5767 .Case("_Z3maxDv3_fS_", glsl::ExtInst::ExtInstFMax)
5768 .Case("_Z3maxDv4_fS_", glsl::ExtInst::ExtInstFMax)
5769 .StartsWith("_Z4fmax", glsl::ExtInst::ExtInstFMax)
5770 .Case("_Z3minii", glsl::ExtInst::ExtInstSMin)
5771 .Case("_Z3minDv2_iS_", glsl::ExtInst::ExtInstSMin)
5772 .Case("_Z3minDv3_iS_", glsl::ExtInst::ExtInstSMin)
5773 .Case("_Z3minDv4_iS_", glsl::ExtInst::ExtInstSMin)
5774 .Case("_Z3minjj", glsl::ExtInst::ExtInstUMin)
5775 .Case("_Z3minDv2_jS_", glsl::ExtInst::ExtInstUMin)
5776 .Case("_Z3minDv3_jS_", glsl::ExtInst::ExtInstUMin)
5777 .Case("_Z3minDv4_jS_", glsl::ExtInst::ExtInstUMin)
5778 .Case("_Z3minff", glsl::ExtInst::ExtInstFMin)
5779 .Case("_Z3minDv2_fS_", glsl::ExtInst::ExtInstFMin)
5780 .Case("_Z3minDv3_fS_", glsl::ExtInst::ExtInstFMin)
5781 .Case("_Z3minDv4_fS_", glsl::ExtInst::ExtInstFMin)
5782 .StartsWith("_Z4fmin", glsl::ExtInst::ExtInstFMin)
5783 .StartsWith("_Z7degrees", glsl::ExtInst::ExtInstDegrees)
5784 .StartsWith("_Z7radians", glsl::ExtInst::ExtInstRadians)
5785 .StartsWith("_Z3mix", glsl::ExtInst::ExtInstFMix)
5786 .StartsWith("_Z4acos", glsl::ExtInst::ExtInstAcos)
5787 .StartsWith("_Z5acosh", glsl::ExtInst::ExtInstAcosh)
5788 .StartsWith("_Z4asin", glsl::ExtInst::ExtInstAsin)
5789 .StartsWith("_Z5asinh", glsl::ExtInst::ExtInstAsinh)
5790 .StartsWith("_Z4atan", glsl::ExtInst::ExtInstAtan)
5791 .StartsWith("_Z5atan2", glsl::ExtInst::ExtInstAtan2)
5792 .StartsWith("_Z5atanh", glsl::ExtInst::ExtInstAtanh)
5793 .StartsWith("_Z4ceil", glsl::ExtInst::ExtInstCeil)
5794 .StartsWith("_Z3sin", glsl::ExtInst::ExtInstSin)
5795 .StartsWith("_Z4sinh", glsl::ExtInst::ExtInstSinh)
5796 .StartsWith("_Z8half_sin", glsl::ExtInst::ExtInstSin)
5797 .StartsWith("_Z10native_sin", glsl::ExtInst::ExtInstSin)
5798 .StartsWith("_Z3cos", glsl::ExtInst::ExtInstCos)
5799 .StartsWith("_Z4cosh", glsl::ExtInst::ExtInstCosh)
5800 .StartsWith("_Z8half_cos", glsl::ExtInst::ExtInstCos)
5801 .StartsWith("_Z10native_cos", glsl::ExtInst::ExtInstCos)
5802 .StartsWith("_Z3tan", glsl::ExtInst::ExtInstTan)
5803 .StartsWith("_Z4tanh", glsl::ExtInst::ExtInstTanh)
5804 .StartsWith("_Z8half_tan", glsl::ExtInst::ExtInstTan)
5805 .StartsWith("_Z10native_tan", glsl::ExtInst::ExtInstTan)
5806 .StartsWith("_Z3exp", glsl::ExtInst::ExtInstExp)
5807 .StartsWith("_Z8half_exp", glsl::ExtInst::ExtInstExp)
5808 .StartsWith("_Z10native_exp", glsl::ExtInst::ExtInstExp)
5809 .StartsWith("_Z4exp2", glsl::ExtInst::ExtInstExp2)
5810 .StartsWith("_Z9half_exp2", glsl::ExtInst::ExtInstExp2)
5811 .StartsWith("_Z11native_exp2", glsl::ExtInst::ExtInstExp2)
5812 .StartsWith("_Z3log", glsl::ExtInst::ExtInstLog)
5813 .StartsWith("_Z8half_log", glsl::ExtInst::ExtInstLog)
5814 .StartsWith("_Z10native_log", glsl::ExtInst::ExtInstLog)
5815 .StartsWith("_Z4log2", glsl::ExtInst::ExtInstLog2)
5816 .StartsWith("_Z9half_log2", glsl::ExtInst::ExtInstLog2)
5817 .StartsWith("_Z11native_log2", glsl::ExtInst::ExtInstLog2)
5818 .StartsWith("_Z4fabs", glsl::ExtInst::ExtInstFAbs)
5819 .StartsWith("_Z5floor", glsl::ExtInst::ExtInstFloor)
5820 .StartsWith("_Z5ldexp", glsl::ExtInst::ExtInstLdexp)
5821 .StartsWith("_Z3pow", glsl::ExtInst::ExtInstPow)
5822 .StartsWith("_Z4powr", glsl::ExtInst::ExtInstPow)
5823 .StartsWith("_Z9half_powr", glsl::ExtInst::ExtInstPow)
5824 .StartsWith("_Z11native_powr", glsl::ExtInst::ExtInstPow)
5825 .StartsWith("_Z5round", glsl::ExtInst::ExtInstRound)
5826 .StartsWith("_Z4sqrt", glsl::ExtInst::ExtInstSqrt)
5827 .StartsWith("_Z9half_sqrt", glsl::ExtInst::ExtInstSqrt)
5828 .StartsWith("_Z11native_sqrt", glsl::ExtInst::ExtInstSqrt)
5829 .StartsWith("_Z5rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5830 .StartsWith("_Z10half_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5831 .StartsWith("_Z12native_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5832 .StartsWith("_Z5trunc", glsl::ExtInst::ExtInstTrunc)
5833 .StartsWith("_Z5frexp", glsl::ExtInst::ExtInstFrexp)
5834 .StartsWith("_Z4sign", glsl::ExtInst::ExtInstFSign)
5835 .StartsWith("_Z6length", glsl::ExtInst::ExtInstLength)
5836 .StartsWith("_Z8distance", glsl::ExtInst::ExtInstDistance)
David Netoe9a03512017-10-16 10:08:27 -04005837 .StartsWith("_Z4step", glsl::ExtInst::ExtInstStep)
David Neto22f144c2017-06-12 14:26:21 -04005838 .Case("_Z5crossDv3_fS_", glsl::ExtInst::ExtInstCross)
5839 .StartsWith("_Z9normalize", glsl::ExtInst::ExtInstNormalize)
5840 .StartsWith("llvm.fmuladd.", glsl::ExtInst::ExtInstFma)
5841 .Case("spirv.unpack.v2f16", glsl::ExtInst::ExtInstUnpackHalf2x16)
5842 .Case("spirv.pack.v2f16", glsl::ExtInst::ExtInstPackHalf2x16)
David Neto62653202017-10-16 19:05:18 -04005843 .Case("clspv.fract.f", glsl::ExtInst::ExtInstFract)
5844 .Case("clspv.fract.v2f", glsl::ExtInst::ExtInstFract)
5845 .Case("clspv.fract.v3f", glsl::ExtInst::ExtInstFract)
5846 .Case("clspv.fract.v4f", glsl::ExtInst::ExtInstFract)
David Neto3fbb4072017-10-16 11:28:14 -04005847 .Default(kGlslExtInstBad);
5848}
5849
5850glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(StringRef Name) {
5851 // Check indirect cases.
5852 return StringSwitch<glsl::ExtInst>(Name)
5853 .StartsWith("_Z3clz", glsl::ExtInst::ExtInstFindUMsb)
5854 // Use exact match on float arg because these need a multiply
5855 // of a constant of the right floating point type.
5856 .Case("_Z6acospif", glsl::ExtInst::ExtInstAcos)
5857 .Case("_Z6acospiDv2_f", glsl::ExtInst::ExtInstAcos)
5858 .Case("_Z6acospiDv3_f", glsl::ExtInst::ExtInstAcos)
5859 .Case("_Z6acospiDv4_f", glsl::ExtInst::ExtInstAcos)
5860 .Case("_Z6asinpif", glsl::ExtInst::ExtInstAsin)
5861 .Case("_Z6asinpiDv2_f", glsl::ExtInst::ExtInstAsin)
5862 .Case("_Z6asinpiDv3_f", glsl::ExtInst::ExtInstAsin)
5863 .Case("_Z6asinpiDv4_f", glsl::ExtInst::ExtInstAsin)
5864 .Case("_Z7atan2piff", glsl::ExtInst::ExtInstAtan2)
5865 .Case("_Z7atan2piDv2_fS_", glsl::ExtInst::ExtInstAtan2)
5866 .Case("_Z7atan2piDv3_fS_", glsl::ExtInst::ExtInstAtan2)
5867 .Case("_Z7atan2piDv4_fS_", glsl::ExtInst::ExtInstAtan2)
5868 .Default(kGlslExtInstBad);
5869}
5870
5871glsl::ExtInst SPIRVProducerPass::getDirectOrIndirectExtInstEnum(StringRef Name) {
5872 auto direct = getExtInstEnum(Name);
5873 if (direct != kGlslExtInstBad)
5874 return direct;
5875 return getIndirectExtInstEnum(Name);
David Neto22f144c2017-06-12 14:26:21 -04005876}
5877
5878void SPIRVProducerPass::PrintResID(SPIRVInstruction *Inst) {
5879 out << "%" << Inst->getResultID();
5880}
5881
5882void SPIRVProducerPass::PrintOpcode(SPIRVInstruction *Inst) {
5883 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5884 out << "\t" << spv::getOpName(Opcode);
5885}
5886
5887void SPIRVProducerPass::PrintOperand(SPIRVOperand *Op) {
5888 SPIRVOperandType OpTy = Op->getType();
5889 switch (OpTy) {
5890 default: {
5891 llvm_unreachable("Unsupported SPIRV Operand Type???");
5892 break;
5893 }
5894 case SPIRVOperandType::NUMBERID: {
5895 out << "%" << Op->getNumID();
5896 break;
5897 }
5898 case SPIRVOperandType::LITERAL_STRING: {
5899 out << "\"" << Op->getLiteralStr() << "\"";
5900 break;
5901 }
5902 case SPIRVOperandType::LITERAL_INTEGER: {
5903 // TODO: Handle LiteralNum carefully.
5904 for (auto Word : Op->getLiteralNum()) {
5905 out << Word;
5906 }
5907 break;
5908 }
5909 case SPIRVOperandType::LITERAL_FLOAT: {
5910 // TODO: Handle LiteralNum carefully.
5911 for (auto Word : Op->getLiteralNum()) {
5912 APFloat APF = APFloat(APFloat::IEEEsingle(), APInt(32, Word));
5913 SmallString<8> Str;
5914 APF.toString(Str, 6, 2);
5915 out << Str;
5916 }
5917 break;
5918 }
5919 }
5920}
5921
5922void SPIRVProducerPass::PrintCapability(SPIRVOperand *Op) {
5923 spv::Capability Cap = static_cast<spv::Capability>(Op->getNumID());
5924 out << spv::getCapabilityName(Cap);
5925}
5926
5927void SPIRVProducerPass::PrintExtInst(SPIRVOperand *Op) {
5928 auto LiteralNum = Op->getLiteralNum();
5929 glsl::ExtInst Ext = static_cast<glsl::ExtInst>(LiteralNum[0]);
5930 out << glsl::getExtInstName(Ext);
5931}
5932
5933void SPIRVProducerPass::PrintAddrModel(SPIRVOperand *Op) {
5934 spv::AddressingModel AddrModel =
5935 static_cast<spv::AddressingModel>(Op->getNumID());
5936 out << spv::getAddressingModelName(AddrModel);
5937}
5938
5939void SPIRVProducerPass::PrintMemModel(SPIRVOperand *Op) {
5940 spv::MemoryModel MemModel = static_cast<spv::MemoryModel>(Op->getNumID());
5941 out << spv::getMemoryModelName(MemModel);
5942}
5943
5944void SPIRVProducerPass::PrintExecModel(SPIRVOperand *Op) {
5945 spv::ExecutionModel ExecModel =
5946 static_cast<spv::ExecutionModel>(Op->getNumID());
5947 out << spv::getExecutionModelName(ExecModel);
5948}
5949
5950void SPIRVProducerPass::PrintExecMode(SPIRVOperand *Op) {
5951 spv::ExecutionMode ExecMode = static_cast<spv::ExecutionMode>(Op->getNumID());
5952 out << spv::getExecutionModeName(ExecMode);
5953}
5954
5955void SPIRVProducerPass::PrintSourceLanguage(SPIRVOperand *Op) {
5956 spv::SourceLanguage SourceLang = static_cast<spv::SourceLanguage>(Op->getNumID());
5957 out << spv::getSourceLanguageName(SourceLang);
5958}
5959
5960void SPIRVProducerPass::PrintFuncCtrl(SPIRVOperand *Op) {
5961 spv::FunctionControlMask FuncCtrl =
5962 static_cast<spv::FunctionControlMask>(Op->getNumID());
5963 out << spv::getFunctionControlName(FuncCtrl);
5964}
5965
5966void SPIRVProducerPass::PrintStorageClass(SPIRVOperand *Op) {
5967 spv::StorageClass StClass = static_cast<spv::StorageClass>(Op->getNumID());
5968 out << getStorageClassName(StClass);
5969}
5970
5971void SPIRVProducerPass::PrintDecoration(SPIRVOperand *Op) {
5972 spv::Decoration Deco = static_cast<spv::Decoration>(Op->getNumID());
5973 out << getDecorationName(Deco);
5974}
5975
5976void SPIRVProducerPass::PrintBuiltIn(SPIRVOperand *Op) {
5977 spv::BuiltIn BIn = static_cast<spv::BuiltIn>(Op->getNumID());
5978 out << getBuiltInName(BIn);
5979}
5980
5981void SPIRVProducerPass::PrintSelectionControl(SPIRVOperand *Op) {
5982 spv::SelectionControlMask BIn =
5983 static_cast<spv::SelectionControlMask>(Op->getNumID());
5984 out << getSelectionControlName(BIn);
5985}
5986
5987void SPIRVProducerPass::PrintLoopControl(SPIRVOperand *Op) {
5988 spv::LoopControlMask BIn = static_cast<spv::LoopControlMask>(Op->getNumID());
5989 out << getLoopControlName(BIn);
5990}
5991
5992void SPIRVProducerPass::PrintDimensionality(SPIRVOperand *Op) {
5993 spv::Dim DIM = static_cast<spv::Dim>(Op->getNumID());
5994 out << getDimName(DIM);
5995}
5996
5997void SPIRVProducerPass::PrintImageFormat(SPIRVOperand *Op) {
5998 spv::ImageFormat Format = static_cast<spv::ImageFormat>(Op->getNumID());
5999 out << getImageFormatName(Format);
6000}
6001
6002void SPIRVProducerPass::PrintMemoryAccess(SPIRVOperand *Op) {
6003 out << spv::getMemoryAccessName(
6004 static_cast<spv::MemoryAccessMask>(Op->getNumID()));
6005}
6006
6007void SPIRVProducerPass::PrintImageOperandsType(SPIRVOperand *Op) {
6008 auto LiteralNum = Op->getLiteralNum();
6009 spv::ImageOperandsMask Type =
6010 static_cast<spv::ImageOperandsMask>(LiteralNum[0]);
6011 out << getImageOperandsName(Type);
6012}
6013
6014void SPIRVProducerPass::WriteSPIRVAssembly() {
6015 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
6016
6017 for (auto Inst : SPIRVInstList) {
6018 SPIRVOperandList Ops = Inst->getOperands();
6019 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
6020
6021 switch (Opcode) {
6022 default: {
6023 llvm_unreachable("Unsupported SPIRV instruction");
6024 break;
6025 }
6026 case spv::OpCapability: {
6027 // Ops[0] = Capability
6028 PrintOpcode(Inst);
6029 out << " ";
6030 PrintCapability(Ops[0]);
6031 out << "\n";
6032 break;
6033 }
6034 case spv::OpMemoryModel: {
6035 // Ops[0] = Addressing Model
6036 // Ops[1] = Memory Model
6037 PrintOpcode(Inst);
6038 out << " ";
6039 PrintAddrModel(Ops[0]);
6040 out << " ";
6041 PrintMemModel(Ops[1]);
6042 out << "\n";
6043 break;
6044 }
6045 case spv::OpEntryPoint: {
6046 // Ops[0] = Execution Model
6047 // Ops[1] = EntryPoint ID
6048 // Ops[2] = Name (Literal String)
6049 // Ops[3] ... Ops[n] = Interface ID
6050 PrintOpcode(Inst);
6051 out << " ";
6052 PrintExecModel(Ops[0]);
6053 for (uint32_t i = 1; i < Ops.size(); i++) {
6054 out << " ";
6055 PrintOperand(Ops[i]);
6056 }
6057 out << "\n";
6058 break;
6059 }
6060 case spv::OpExecutionMode: {
6061 // Ops[0] = Entry Point ID
6062 // Ops[1] = Execution Mode
6063 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
6064 PrintOpcode(Inst);
6065 out << " ";
6066 PrintOperand(Ops[0]);
6067 out << " ";
6068 PrintExecMode(Ops[1]);
6069 for (uint32_t i = 2; i < Ops.size(); i++) {
6070 out << " ";
6071 PrintOperand(Ops[i]);
6072 }
6073 out << "\n";
6074 break;
6075 }
6076 case spv::OpSource: {
6077 // Ops[0] = SourceLanguage ID
6078 // Ops[1] = Version (LiteralNum)
6079 PrintOpcode(Inst);
6080 out << " ";
6081 PrintSourceLanguage(Ops[0]);
6082 out << " ";
6083 PrintOperand(Ops[1]);
6084 out << "\n";
6085 break;
6086 }
6087 case spv::OpDecorate: {
6088 // Ops[0] = Target ID
6089 // Ops[1] = Decoration (Block or BufferBlock)
6090 // Ops[2] ... Ops[n] = Optional literals according to Decoration
6091 PrintOpcode(Inst);
6092 out << " ";
6093 PrintOperand(Ops[0]);
6094 out << " ";
6095 PrintDecoration(Ops[1]);
6096 // Handle BuiltIn OpDecorate specially.
6097 if (Ops[1]->getNumID() == spv::DecorationBuiltIn) {
6098 out << " ";
6099 PrintBuiltIn(Ops[2]);
6100 } else {
6101 for (uint32_t i = 2; i < Ops.size(); i++) {
6102 out << " ";
6103 PrintOperand(Ops[i]);
6104 }
6105 }
6106 out << "\n";
6107 break;
6108 }
6109 case spv::OpMemberDecorate: {
6110 // Ops[0] = Structure Type ID
6111 // Ops[1] = Member Index(Literal Number)
6112 // Ops[2] = Decoration
6113 // Ops[3] ... Ops[n] = Optional literals according to Decoration
6114 PrintOpcode(Inst);
6115 out << " ";
6116 PrintOperand(Ops[0]);
6117 out << " ";
6118 PrintOperand(Ops[1]);
6119 out << " ";
6120 PrintDecoration(Ops[2]);
6121 for (uint32_t i = 3; i < Ops.size(); i++) {
6122 out << " ";
6123 PrintOperand(Ops[i]);
6124 }
6125 out << "\n";
6126 break;
6127 }
6128 case spv::OpTypePointer: {
6129 // Ops[0] = Storage Class
6130 // Ops[1] = Element Type ID
6131 PrintResID(Inst);
6132 out << " = ";
6133 PrintOpcode(Inst);
6134 out << " ";
6135 PrintStorageClass(Ops[0]);
6136 out << " ";
6137 PrintOperand(Ops[1]);
6138 out << "\n";
6139 break;
6140 }
6141 case spv::OpTypeImage: {
6142 // Ops[0] = Sampled Type ID
6143 // Ops[1] = Dim ID
6144 // Ops[2] = Depth (Literal Number)
6145 // Ops[3] = Arrayed (Literal Number)
6146 // Ops[4] = MS (Literal Number)
6147 // Ops[5] = Sampled (Literal Number)
6148 // Ops[6] = Image Format ID
6149 PrintResID(Inst);
6150 out << " = ";
6151 PrintOpcode(Inst);
6152 out << " ";
6153 PrintOperand(Ops[0]);
6154 out << " ";
6155 PrintDimensionality(Ops[1]);
6156 out << " ";
6157 PrintOperand(Ops[2]);
6158 out << " ";
6159 PrintOperand(Ops[3]);
6160 out << " ";
6161 PrintOperand(Ops[4]);
6162 out << " ";
6163 PrintOperand(Ops[5]);
6164 out << " ";
6165 PrintImageFormat(Ops[6]);
6166 out << "\n";
6167 break;
6168 }
6169 case spv::OpFunction: {
6170 // Ops[0] : Result Type ID
6171 // Ops[1] : Function Control
6172 // Ops[2] : Function Type ID
6173 PrintResID(Inst);
6174 out << " = ";
6175 PrintOpcode(Inst);
6176 out << " ";
6177 PrintOperand(Ops[0]);
6178 out << " ";
6179 PrintFuncCtrl(Ops[1]);
6180 out << " ";
6181 PrintOperand(Ops[2]);
6182 out << "\n";
6183 break;
6184 }
6185 case spv::OpSelectionMerge: {
6186 // Ops[0] = Merge Block ID
6187 // Ops[1] = Selection Control
6188 PrintOpcode(Inst);
6189 out << " ";
6190 PrintOperand(Ops[0]);
6191 out << " ";
6192 PrintSelectionControl(Ops[1]);
6193 out << "\n";
6194 break;
6195 }
6196 case spv::OpLoopMerge: {
6197 // Ops[0] = Merge Block ID
6198 // Ops[1] = Continue Target ID
6199 // Ops[2] = Selection Control
6200 PrintOpcode(Inst);
6201 out << " ";
6202 PrintOperand(Ops[0]);
6203 out << " ";
6204 PrintOperand(Ops[1]);
6205 out << " ";
6206 PrintLoopControl(Ops[2]);
6207 out << "\n";
6208 break;
6209 }
6210 case spv::OpImageSampleExplicitLod: {
6211 // Ops[0] = Result Type ID
6212 // Ops[1] = Sampled Image ID
6213 // Ops[2] = Coordinate ID
6214 // Ops[3] = Image Operands Type ID
6215 // Ops[4] ... Ops[n] = Operands ID
6216 PrintResID(Inst);
6217 out << " = ";
6218 PrintOpcode(Inst);
6219 for (uint32_t i = 0; i < 3; i++) {
6220 out << " ";
6221 PrintOperand(Ops[i]);
6222 }
6223 out << " ";
6224 PrintImageOperandsType(Ops[3]);
6225 for (uint32_t i = 4; i < Ops.size(); i++) {
6226 out << " ";
6227 PrintOperand(Ops[i]);
6228 }
6229 out << "\n";
6230 break;
6231 }
6232 case spv::OpVariable: {
6233 // Ops[0] : Result Type ID
6234 // Ops[1] : Storage Class
6235 // Ops[2] ... Ops[n] = Initializer IDs
6236 PrintResID(Inst);
6237 out << " = ";
6238 PrintOpcode(Inst);
6239 out << " ";
6240 PrintOperand(Ops[0]);
6241 out << " ";
6242 PrintStorageClass(Ops[1]);
6243 for (uint32_t i = 2; i < Ops.size(); i++) {
6244 out << " ";
6245 PrintOperand(Ops[i]);
6246 }
6247 out << "\n";
6248 break;
6249 }
6250 case spv::OpExtInst: {
6251 // Ops[0] = Result Type ID
6252 // Ops[1] = Set ID (OpExtInstImport ID)
6253 // Ops[2] = Instruction Number (Literal Number)
6254 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
6255 PrintResID(Inst);
6256 out << " = ";
6257 PrintOpcode(Inst);
6258 out << " ";
6259 PrintOperand(Ops[0]);
6260 out << " ";
6261 PrintOperand(Ops[1]);
6262 out << " ";
6263 PrintExtInst(Ops[2]);
6264 for (uint32_t i = 3; i < Ops.size(); i++) {
6265 out << " ";
6266 PrintOperand(Ops[i]);
6267 }
6268 out << "\n";
6269 break;
6270 }
6271 case spv::OpCopyMemory: {
6272 // Ops[0] = Addressing Model
6273 // Ops[1] = Memory Model
6274 PrintOpcode(Inst);
6275 out << " ";
6276 PrintOperand(Ops[0]);
6277 out << " ";
6278 PrintOperand(Ops[1]);
6279 out << " ";
6280 PrintMemoryAccess(Ops[2]);
6281 out << " ";
6282 PrintOperand(Ops[3]);
6283 out << "\n";
6284 break;
6285 }
6286 case spv::OpExtension:
6287 case spv::OpControlBarrier:
6288 case spv::OpMemoryBarrier:
6289 case spv::OpBranch:
6290 case spv::OpBranchConditional:
6291 case spv::OpStore:
6292 case spv::OpImageWrite:
6293 case spv::OpReturnValue:
6294 case spv::OpReturn:
6295 case spv::OpFunctionEnd: {
6296 PrintOpcode(Inst);
6297 for (uint32_t i = 0; i < Ops.size(); i++) {
6298 out << " ";
6299 PrintOperand(Ops[i]);
6300 }
6301 out << "\n";
6302 break;
6303 }
6304 case spv::OpExtInstImport:
6305 case spv::OpTypeRuntimeArray:
6306 case spv::OpTypeStruct:
6307 case spv::OpTypeSampler:
6308 case spv::OpTypeSampledImage:
6309 case spv::OpTypeInt:
6310 case spv::OpTypeFloat:
6311 case spv::OpTypeArray:
6312 case spv::OpTypeVector:
6313 case spv::OpTypeBool:
6314 case spv::OpTypeVoid:
6315 case spv::OpTypeFunction:
6316 case spv::OpFunctionParameter:
6317 case spv::OpLabel:
6318 case spv::OpPhi:
6319 case spv::OpLoad:
6320 case spv::OpSelect:
6321 case spv::OpAccessChain:
6322 case spv::OpPtrAccessChain:
6323 case spv::OpInBoundsAccessChain:
6324 case spv::OpUConvert:
6325 case spv::OpSConvert:
6326 case spv::OpConvertFToU:
6327 case spv::OpConvertFToS:
6328 case spv::OpConvertUToF:
6329 case spv::OpConvertSToF:
6330 case spv::OpFConvert:
6331 case spv::OpConvertPtrToU:
6332 case spv::OpConvertUToPtr:
6333 case spv::OpBitcast:
6334 case spv::OpIAdd:
6335 case spv::OpFAdd:
6336 case spv::OpISub:
6337 case spv::OpFSub:
6338 case spv::OpIMul:
6339 case spv::OpFMul:
6340 case spv::OpUDiv:
6341 case spv::OpSDiv:
6342 case spv::OpFDiv:
6343 case spv::OpUMod:
6344 case spv::OpSRem:
6345 case spv::OpFRem:
6346 case spv::OpBitwiseOr:
6347 case spv::OpBitwiseXor:
6348 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04006349 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04006350 case spv::OpShiftLeftLogical:
6351 case spv::OpShiftRightLogical:
6352 case spv::OpShiftRightArithmetic:
6353 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04006354 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04006355 case spv::OpCompositeExtract:
6356 case spv::OpVectorExtractDynamic:
6357 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04006358 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04006359 case spv::OpVectorInsertDynamic:
6360 case spv::OpVectorShuffle:
6361 case spv::OpIEqual:
6362 case spv::OpINotEqual:
6363 case spv::OpUGreaterThan:
6364 case spv::OpUGreaterThanEqual:
6365 case spv::OpULessThan:
6366 case spv::OpULessThanEqual:
6367 case spv::OpSGreaterThan:
6368 case spv::OpSGreaterThanEqual:
6369 case spv::OpSLessThan:
6370 case spv::OpSLessThanEqual:
6371 case spv::OpFOrdEqual:
6372 case spv::OpFOrdGreaterThan:
6373 case spv::OpFOrdGreaterThanEqual:
6374 case spv::OpFOrdLessThan:
6375 case spv::OpFOrdLessThanEqual:
6376 case spv::OpFOrdNotEqual:
6377 case spv::OpFUnordEqual:
6378 case spv::OpFUnordGreaterThan:
6379 case spv::OpFUnordGreaterThanEqual:
6380 case spv::OpFUnordLessThan:
6381 case spv::OpFUnordLessThanEqual:
6382 case spv::OpFUnordNotEqual:
6383 case spv::OpSampledImage:
6384 case spv::OpFunctionCall:
6385 case spv::OpConstantTrue:
6386 case spv::OpConstantFalse:
6387 case spv::OpConstant:
6388 case spv::OpSpecConstant:
6389 case spv::OpConstantComposite:
6390 case spv::OpSpecConstantComposite:
6391 case spv::OpConstantNull:
6392 case spv::OpLogicalOr:
6393 case spv::OpLogicalAnd:
6394 case spv::OpLogicalNot:
6395 case spv::OpLogicalNotEqual:
6396 case spv::OpUndef:
6397 case spv::OpIsInf:
6398 case spv::OpIsNan:
6399 case spv::OpAny:
6400 case spv::OpAll:
David Neto5c22a252018-03-15 16:07:41 -04006401 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04006402 case spv::OpAtomicIAdd:
6403 case spv::OpAtomicISub:
6404 case spv::OpAtomicExchange:
6405 case spv::OpAtomicIIncrement:
6406 case spv::OpAtomicIDecrement:
6407 case spv::OpAtomicCompareExchange:
6408 case spv::OpAtomicUMin:
6409 case spv::OpAtomicSMin:
6410 case spv::OpAtomicUMax:
6411 case spv::OpAtomicSMax:
6412 case spv::OpAtomicAnd:
6413 case spv::OpAtomicOr:
6414 case spv::OpAtomicXor:
6415 case spv::OpDot: {
6416 PrintResID(Inst);
6417 out << " = ";
6418 PrintOpcode(Inst);
6419 for (uint32_t i = 0; i < Ops.size(); i++) {
6420 out << " ";
6421 PrintOperand(Ops[i]);
6422 }
6423 out << "\n";
6424 break;
6425 }
6426 }
6427 }
6428}
6429
6430void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04006431 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04006432}
6433
6434void SPIRVProducerPass::WriteResultID(SPIRVInstruction *Inst) {
6435 WriteOneWord(Inst->getResultID());
6436}
6437
6438void SPIRVProducerPass::WriteWordCountAndOpcode(SPIRVInstruction *Inst) {
6439 // High 16 bit : Word Count
6440 // Low 16 bit : Opcode
6441 uint32_t Word = Inst->getOpcode();
6442 Word |= Inst->getWordCount() << 16;
6443 WriteOneWord(Word);
6444}
6445
6446void SPIRVProducerPass::WriteOperand(SPIRVOperand *Op) {
6447 SPIRVOperandType OpTy = Op->getType();
6448 switch (OpTy) {
6449 default: {
6450 llvm_unreachable("Unsupported SPIRV Operand Type???");
6451 break;
6452 }
6453 case SPIRVOperandType::NUMBERID: {
6454 WriteOneWord(Op->getNumID());
6455 break;
6456 }
6457 case SPIRVOperandType::LITERAL_STRING: {
6458 std::string Str = Op->getLiteralStr();
6459 const char *Data = Str.c_str();
6460 size_t WordSize = Str.size() / 4;
6461 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
6462 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
6463 }
6464
6465 uint32_t Remainder = Str.size() % 4;
6466 uint32_t LastWord = 0;
6467 if (Remainder) {
6468 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
6469 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
6470 }
6471 }
6472
6473 WriteOneWord(LastWord);
6474 break;
6475 }
6476 case SPIRVOperandType::LITERAL_INTEGER:
6477 case SPIRVOperandType::LITERAL_FLOAT: {
6478 auto LiteralNum = Op->getLiteralNum();
6479 // TODO: Handle LiteranNum carefully.
6480 for (auto Word : LiteralNum) {
6481 WriteOneWord(Word);
6482 }
6483 break;
6484 }
6485 }
6486}
6487
6488void SPIRVProducerPass::WriteSPIRVBinary() {
6489 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
6490
6491 for (auto Inst : SPIRVInstList) {
6492 SPIRVOperandList Ops = Inst->getOperands();
6493 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
6494
6495 switch (Opcode) {
6496 default: {
David Neto5c22a252018-03-15 16:07:41 -04006497 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04006498 llvm_unreachable("Unsupported SPIRV instruction");
6499 break;
6500 }
6501 case spv::OpCapability:
6502 case spv::OpExtension:
6503 case spv::OpMemoryModel:
6504 case spv::OpEntryPoint:
6505 case spv::OpExecutionMode:
6506 case spv::OpSource:
6507 case spv::OpDecorate:
6508 case spv::OpMemberDecorate:
6509 case spv::OpBranch:
6510 case spv::OpBranchConditional:
6511 case spv::OpSelectionMerge:
6512 case spv::OpLoopMerge:
6513 case spv::OpStore:
6514 case spv::OpImageWrite:
6515 case spv::OpReturnValue:
6516 case spv::OpControlBarrier:
6517 case spv::OpMemoryBarrier:
6518 case spv::OpReturn:
6519 case spv::OpFunctionEnd:
6520 case spv::OpCopyMemory: {
6521 WriteWordCountAndOpcode(Inst);
6522 for (uint32_t i = 0; i < Ops.size(); i++) {
6523 WriteOperand(Ops[i]);
6524 }
6525 break;
6526 }
6527 case spv::OpTypeBool:
6528 case spv::OpTypeVoid:
6529 case spv::OpTypeSampler:
6530 case spv::OpLabel:
6531 case spv::OpExtInstImport:
6532 case spv::OpTypePointer:
6533 case spv::OpTypeRuntimeArray:
6534 case spv::OpTypeStruct:
6535 case spv::OpTypeImage:
6536 case spv::OpTypeSampledImage:
6537 case spv::OpTypeInt:
6538 case spv::OpTypeFloat:
6539 case spv::OpTypeArray:
6540 case spv::OpTypeVector:
6541 case spv::OpTypeFunction: {
6542 WriteWordCountAndOpcode(Inst);
6543 WriteResultID(Inst);
6544 for (uint32_t i = 0; i < Ops.size(); i++) {
6545 WriteOperand(Ops[i]);
6546 }
6547 break;
6548 }
6549 case spv::OpFunction:
6550 case spv::OpFunctionParameter:
6551 case spv::OpAccessChain:
6552 case spv::OpPtrAccessChain:
6553 case spv::OpInBoundsAccessChain:
6554 case spv::OpUConvert:
6555 case spv::OpSConvert:
6556 case spv::OpConvertFToU:
6557 case spv::OpConvertFToS:
6558 case spv::OpConvertUToF:
6559 case spv::OpConvertSToF:
6560 case spv::OpFConvert:
6561 case spv::OpConvertPtrToU:
6562 case spv::OpConvertUToPtr:
6563 case spv::OpBitcast:
6564 case spv::OpIAdd:
6565 case spv::OpFAdd:
6566 case spv::OpISub:
6567 case spv::OpFSub:
6568 case spv::OpIMul:
6569 case spv::OpFMul:
6570 case spv::OpUDiv:
6571 case spv::OpSDiv:
6572 case spv::OpFDiv:
6573 case spv::OpUMod:
6574 case spv::OpSRem:
6575 case spv::OpFRem:
6576 case spv::OpBitwiseOr:
6577 case spv::OpBitwiseXor:
6578 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04006579 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04006580 case spv::OpShiftLeftLogical:
6581 case spv::OpShiftRightLogical:
6582 case spv::OpShiftRightArithmetic:
6583 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04006584 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04006585 case spv::OpCompositeExtract:
6586 case spv::OpVectorExtractDynamic:
6587 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04006588 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04006589 case spv::OpVectorInsertDynamic:
6590 case spv::OpVectorShuffle:
6591 case spv::OpIEqual:
6592 case spv::OpINotEqual:
6593 case spv::OpUGreaterThan:
6594 case spv::OpUGreaterThanEqual:
6595 case spv::OpULessThan:
6596 case spv::OpULessThanEqual:
6597 case spv::OpSGreaterThan:
6598 case spv::OpSGreaterThanEqual:
6599 case spv::OpSLessThan:
6600 case spv::OpSLessThanEqual:
6601 case spv::OpFOrdEqual:
6602 case spv::OpFOrdGreaterThan:
6603 case spv::OpFOrdGreaterThanEqual:
6604 case spv::OpFOrdLessThan:
6605 case spv::OpFOrdLessThanEqual:
6606 case spv::OpFOrdNotEqual:
6607 case spv::OpFUnordEqual:
6608 case spv::OpFUnordGreaterThan:
6609 case spv::OpFUnordGreaterThanEqual:
6610 case spv::OpFUnordLessThan:
6611 case spv::OpFUnordLessThanEqual:
6612 case spv::OpFUnordNotEqual:
6613 case spv::OpExtInst:
6614 case spv::OpIsInf:
6615 case spv::OpIsNan:
6616 case spv::OpAny:
6617 case spv::OpAll:
6618 case spv::OpUndef:
6619 case spv::OpConstantNull:
6620 case spv::OpLogicalOr:
6621 case spv::OpLogicalAnd:
6622 case spv::OpLogicalNot:
6623 case spv::OpLogicalNotEqual:
6624 case spv::OpConstantComposite:
6625 case spv::OpSpecConstantComposite:
6626 case spv::OpConstantTrue:
6627 case spv::OpConstantFalse:
6628 case spv::OpConstant:
6629 case spv::OpSpecConstant:
6630 case spv::OpVariable:
6631 case spv::OpFunctionCall:
6632 case spv::OpSampledImage:
6633 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04006634 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04006635 case spv::OpSelect:
6636 case spv::OpPhi:
6637 case spv::OpLoad:
6638 case spv::OpAtomicIAdd:
6639 case spv::OpAtomicISub:
6640 case spv::OpAtomicExchange:
6641 case spv::OpAtomicIIncrement:
6642 case spv::OpAtomicIDecrement:
6643 case spv::OpAtomicCompareExchange:
6644 case spv::OpAtomicUMin:
6645 case spv::OpAtomicSMin:
6646 case spv::OpAtomicUMax:
6647 case spv::OpAtomicSMax:
6648 case spv::OpAtomicAnd:
6649 case spv::OpAtomicOr:
6650 case spv::OpAtomicXor:
6651 case spv::OpDot: {
6652 WriteWordCountAndOpcode(Inst);
6653 WriteOperand(Ops[0]);
6654 WriteResultID(Inst);
6655 for (uint32_t i = 1; i < Ops.size(); i++) {
6656 WriteOperand(Ops[i]);
6657 }
6658 break;
6659 }
6660 }
6661 }
6662}