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