blob: bc07ff0f28f2345e8dced7fdba0b417049a24a31 [file] [log] [blame]
Greg Fischer04fcc662016-11-10 10:11:50 -07001// Copyright (c) 2017 The Khronos Group Inc.
2// Copyright (c) 2017 Valve Corporation
3// Copyright (c) 2017 LunarG Inc.
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
dan sinclaireda2cfb2018-08-03 15:06:09 -040017#include "source/opt/inline_pass.h"
GregFe28bd392017-08-01 17:20:13 -060018
dan sinclaireda2cfb2018-08-03 15:06:09 -040019#include <unordered_set>
20#include <utility>
21
22#include "source/cfa.h"
Steven Perronbd0a2da2020-05-14 10:55:47 -040023#include "source/opt/reflect.h"
dan sinclair1963a2d2018-08-14 15:01:50 -040024#include "source/util/make_unique.h"
Greg Fischer04fcc662016-11-10 10:11:50 -070025
26// Indices of operands in SPIR-V instructions
27
Greg Fischer04fcc662016-11-10 10:11:50 -070028static const int kSpvFunctionCallFunctionId = 2;
29static const int kSpvFunctionCallArgumentId = 3;
30static const int kSpvReturnValueId = 0;
Greg Fischer04fcc662016-11-10 10:11:50 -070031
32namespace spvtools {
33namespace opt {
34
Greg Fischer04fcc662016-11-10 10:11:50 -070035uint32_t InlinePass::AddPointerToType(uint32_t type_id,
36 SpvStorageClass storage_class) {
Steven Perronacd27812018-12-18 19:34:03 +000037 uint32_t resultId = context()->TakeNextId();
38 if (resultId == 0) {
39 return resultId;
40 }
41
dan sinclairc7da51a2018-07-12 15:14:43 -040042 std::unique_ptr<Instruction> type_inst(
43 new Instruction(context(), SpvOpTypePointer, 0, resultId,
44 {{spv_operand_type_t::SPV_OPERAND_TYPE_STORAGE_CLASS,
45 {uint32_t(storage_class)}},
46 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {type_id}}}));
Steven Perron476cae62017-10-30 11:13:24 -040047 context()->AddType(std::move(type_inst));
Alan Baker61690852017-12-08 15:33:19 -050048 analysis::Type* pointeeTy;
49 std::unique_ptr<analysis::Pointer> pointerTy;
50 std::tie(pointeeTy, pointerTy) =
51 context()->get_type_mgr()->GetTypeAndPointerType(type_id,
52 SpvStorageClassFunction);
53 context()->get_type_mgr()->RegisterType(resultId, *pointerTy);
Greg Fischer04fcc662016-11-10 10:11:50 -070054 return resultId;
55}
56
57void InlinePass::AddBranch(uint32_t label_id,
dan sinclairc7da51a2018-07-12 15:14:43 -040058 std::unique_ptr<BasicBlock>* block_ptr) {
59 std::unique_ptr<Instruction> newBranch(
60 new Instruction(context(), SpvOpBranch, 0, 0,
61 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {label_id}}}));
Greg Fischer04fcc662016-11-10 10:11:50 -070062 (*block_ptr)->AddInstruction(std::move(newBranch));
63}
64
Greg Fischerbba812f2017-05-04 20:55:53 -060065void InlinePass::AddBranchCond(uint32_t cond_id, uint32_t true_id,
Diego Novillod2938e42017-11-08 12:40:02 -050066 uint32_t false_id,
dan sinclairc7da51a2018-07-12 15:14:43 -040067 std::unique_ptr<BasicBlock>* block_ptr) {
68 std::unique_ptr<Instruction> newBranch(
69 new Instruction(context(), SpvOpBranchConditional, 0, 0,
70 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {cond_id}},
71 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {true_id}},
72 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {false_id}}}));
Greg Fischerbba812f2017-05-04 20:55:53 -060073 (*block_ptr)->AddInstruction(std::move(newBranch));
74}
75
76void InlinePass::AddLoopMerge(uint32_t merge_id, uint32_t continue_id,
dan sinclairc7da51a2018-07-12 15:14:43 -040077 std::unique_ptr<BasicBlock>* block_ptr) {
78 std::unique_ptr<Instruction> newLoopMerge(new Instruction(
Alan Bakera7717132017-11-14 14:11:50 -050079 context(), SpvOpLoopMerge, 0, 0,
Greg Fischerbba812f2017-05-04 20:55:53 -060080 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {merge_id}},
81 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {continue_id}},
82 {spv_operand_type_t::SPV_OPERAND_TYPE_LOOP_CONTROL, {0}}}));
83 (*block_ptr)->AddInstruction(std::move(newLoopMerge));
84}
85
Greg Fischer04fcc662016-11-10 10:11:50 -070086void InlinePass::AddStore(uint32_t ptr_id, uint32_t val_id,
dan sinclairc7da51a2018-07-12 15:14:43 -040087 std::unique_ptr<BasicBlock>* block_ptr) {
88 std::unique_ptr<Instruction> newStore(
89 new Instruction(context(), SpvOpStore, 0, 0,
90 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {ptr_id}},
91 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {val_id}}}));
Greg Fischer04fcc662016-11-10 10:11:50 -070092 (*block_ptr)->AddInstruction(std::move(newStore));
93}
94
95void InlinePass::AddLoad(uint32_t type_id, uint32_t resultId, uint32_t ptr_id,
dan sinclairc7da51a2018-07-12 15:14:43 -040096 std::unique_ptr<BasicBlock>* block_ptr) {
97 std::unique_ptr<Instruction> newLoad(
98 new Instruction(context(), SpvOpLoad, type_id, resultId,
99 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {ptr_id}}}));
Greg Fischer04fcc662016-11-10 10:11:50 -0700100 (*block_ptr)->AddInstruction(std::move(newLoad));
101}
102
dan sinclairc7da51a2018-07-12 15:14:43 -0400103std::unique_ptr<Instruction> InlinePass::NewLabel(uint32_t label_id) {
104 std::unique_ptr<Instruction> newLabel(
105 new Instruction(context(), SpvOpLabel, 0, label_id, {}));
Greg Fischer04fcc662016-11-10 10:11:50 -0700106 return newLabel;
107}
108
Greg Fischerbba812f2017-05-04 20:55:53 -0600109uint32_t InlinePass::GetFalseId() {
Diego Novillod2938e42017-11-08 12:40:02 -0500110 if (false_id_ != 0) return false_id_;
Diego Novillo1040a952017-10-25 13:26:25 -0400111 false_id_ = get_module()->GetGlobalValue(SpvOpConstantFalse);
Diego Novillod2938e42017-11-08 12:40:02 -0500112 if (false_id_ != 0) return false_id_;
Diego Novillo1040a952017-10-25 13:26:25 -0400113 uint32_t boolId = get_module()->GetGlobalValue(SpvOpTypeBool);
Greg Fischerbba812f2017-05-04 20:55:53 -0600114 if (boolId == 0) {
Steven Perronacd27812018-12-18 19:34:03 +0000115 boolId = context()->TakeNextId();
116 if (boolId == 0) {
117 return 0;
118 }
Diego Novillo1040a952017-10-25 13:26:25 -0400119 get_module()->AddGlobalValue(SpvOpTypeBool, boolId, 0);
Greg Fischerbba812f2017-05-04 20:55:53 -0600120 }
Steven Perronacd27812018-12-18 19:34:03 +0000121 false_id_ = context()->TakeNextId();
122 if (false_id_ == 0) {
123 return 0;
124 }
Diego Novillo1040a952017-10-25 13:26:25 -0400125 get_module()->AddGlobalValue(SpvOpConstantFalse, false_id_, boolId);
Greg Fischerbba812f2017-05-04 20:55:53 -0600126 return false_id_;
127}
128
Greg Fischer04fcc662016-11-10 10:11:50 -0700129void InlinePass::MapParams(
dan sinclairc7da51a2018-07-12 15:14:43 -0400130 Function* calleeFn, BasicBlock::iterator call_inst_itr,
Greg Fischer04fcc662016-11-10 10:11:50 -0700131 std::unordered_map<uint32_t, uint32_t>* callee2caller) {
132 int param_idx = 0;
Steven Perronacd27812018-12-18 19:34:03 +0000133 calleeFn->ForEachParam(
134 [&call_inst_itr, &param_idx, &callee2caller](const Instruction* cpi) {
135 const uint32_t pid = cpi->result_id();
136 (*callee2caller)[pid] = call_inst_itr->GetSingleWordOperand(
137 kSpvFunctionCallArgumentId + param_idx);
138 ++param_idx;
139 });
Greg Fischer04fcc662016-11-10 10:11:50 -0700140}
141
Steven Perronacd27812018-12-18 19:34:03 +0000142bool InlinePass::CloneAndMapLocals(
dan sinclairc7da51a2018-07-12 15:14:43 -0400143 Function* calleeFn, std::vector<std::unique_ptr<Instruction>>* new_vars,
Greg Fischer04fcc662016-11-10 10:11:50 -0700144 std::unordered_map<uint32_t, uint32_t>* callee2caller) {
145 auto callee_block_itr = calleeFn->begin();
146 auto callee_var_itr = callee_block_itr->begin();
147 while (callee_var_itr->opcode() == SpvOp::SpvOpVariable) {
dan sinclairc7da51a2018-07-12 15:14:43 -0400148 std::unique_ptr<Instruction> var_inst(callee_var_itr->Clone(context()));
Steven Perronacd27812018-12-18 19:34:03 +0000149 uint32_t newId = context()->TakeNextId();
150 if (newId == 0) {
151 return false;
152 }
Pierre Moreau5bd55f12018-02-20 19:19:57 +0100153 get_decoration_mgr()->CloneDecorations(callee_var_itr->result_id(), newId);
Greg Fischer04fcc662016-11-10 10:11:50 -0700154 var_inst->SetResultId(newId);
155 (*callee2caller)[callee_var_itr->result_id()] = newId;
156 new_vars->push_back(std::move(var_inst));
Greg Fischerbba812f2017-05-04 20:55:53 -0600157 ++callee_var_itr;
Greg Fischer04fcc662016-11-10 10:11:50 -0700158 }
Steven Perronacd27812018-12-18 19:34:03 +0000159 return true;
Greg Fischer04fcc662016-11-10 10:11:50 -0700160}
161
162uint32_t InlinePass::CreateReturnVar(
dan sinclairc7da51a2018-07-12 15:14:43 -0400163 Function* calleeFn, std::vector<std::unique_ptr<Instruction>>* new_vars) {
Greg Fischer04fcc662016-11-10 10:11:50 -0700164 uint32_t returnVarId = 0;
165 const uint32_t calleeTypeId = calleeFn->type_id();
Steven Perronacd27812018-12-18 19:34:03 +0000166 analysis::TypeManager* type_mgr = context()->get_type_mgr();
167 assert(type_mgr->GetType(calleeTypeId)->AsVoid() == nullptr &&
168 "Cannot create a return variable of type void.");
169 // Find or create ptr to callee return type.
170 uint32_t returnVarTypeId =
171 type_mgr->FindPointerToType(calleeTypeId, SpvStorageClassFunction);
172
173 if (returnVarTypeId == 0) {
174 returnVarTypeId = AddPointerToType(calleeTypeId, SpvStorageClassFunction);
175 if (returnVarTypeId == 0) {
176 return 0;
177 }
Greg Fischer04fcc662016-11-10 10:11:50 -0700178 }
Steven Perronacd27812018-12-18 19:34:03 +0000179
180 // Add return var to new function scope variables.
181 returnVarId = context()->TakeNextId();
182 if (returnVarId == 0) {
183 return 0;
184 }
185
186 std::unique_ptr<Instruction> var_inst(
187 new Instruction(context(), SpvOpVariable, returnVarTypeId, returnVarId,
188 {{spv_operand_type_t::SPV_OPERAND_TYPE_STORAGE_CLASS,
189 {SpvStorageClassFunction}}}));
190 new_vars->push_back(std::move(var_inst));
Pierre Moreau5bd55f12018-02-20 19:19:57 +0100191 get_decoration_mgr()->CloneDecorations(calleeFn->result_id(), returnVarId);
Greg Fischer04fcc662016-11-10 10:11:50 -0700192 return returnVarId;
193}
194
dan sinclairc7da51a2018-07-12 15:14:43 -0400195bool InlinePass::IsSameBlockOp(const Instruction* inst) const {
Greg Fischer04fcc662016-11-10 10:11:50 -0700196 return inst->opcode() == SpvOpSampledImage || inst->opcode() == SpvOpImage;
197}
198
Steven Perronacd27812018-12-18 19:34:03 +0000199bool InlinePass::CloneSameBlockOps(
dan sinclairc7da51a2018-07-12 15:14:43 -0400200 std::unique_ptr<Instruction>* inst,
Greg Fischer04fcc662016-11-10 10:11:50 -0700201 std::unordered_map<uint32_t, uint32_t>* postCallSB,
dan sinclairc7da51a2018-07-12 15:14:43 -0400202 std::unordered_map<uint32_t, Instruction*>* preCallSB,
203 std::unique_ptr<BasicBlock>* block_ptr) {
Steven Perronacd27812018-12-18 19:34:03 +0000204 return (*inst)->WhileEachInId([&postCallSB, &preCallSB, &block_ptr,
205 this](uint32_t* iid) {
206 const auto mapItr = (*postCallSB).find(*iid);
207 if (mapItr == (*postCallSB).end()) {
208 const auto mapItr2 = (*preCallSB).find(*iid);
209 if (mapItr2 != (*preCallSB).end()) {
210 // Clone pre-call same-block ops, map result id.
211 const Instruction* inInst = mapItr2->second;
212 std::unique_ptr<Instruction> sb_inst(inInst->Clone(context()));
213 if (!CloneSameBlockOps(&sb_inst, postCallSB, preCallSB, block_ptr)) {
214 return false;
Pierre Moreau5bd55f12018-02-20 19:19:57 +0100215 }
Steven Perronacd27812018-12-18 19:34:03 +0000216
217 const uint32_t rid = sb_inst->result_id();
218 const uint32_t nid = context()->TakeNextId();
219 if (nid == 0) {
220 return false;
221 }
222 get_decoration_mgr()->CloneDecorations(rid, nid);
223 sb_inst->SetResultId(nid);
224 (*postCallSB)[rid] = nid;
225 *iid = nid;
226 (*block_ptr)->AddInstruction(std::move(sb_inst));
227 }
228 } else {
229 // Reset same-block op operand.
230 *iid = mapItr->second;
231 }
232 return true;
233 });
Greg Fischer04fcc662016-11-10 10:11:50 -0700234}
235
Steven Perronbd0a2da2020-05-14 10:55:47 -0400236void InlinePass::MoveInstsBeforeEntryBlock(
237 std::unordered_map<uint32_t, Instruction*>* preCallSB,
238 BasicBlock* new_blk_ptr, BasicBlock::iterator call_inst_itr,
239 UptrVectorIterator<BasicBlock> call_block_itr) {
240 for (auto cii = call_block_itr->begin(); cii != call_inst_itr;
241 cii = call_block_itr->begin()) {
242 Instruction* inst = &*cii;
243 inst->RemoveFromList();
244 std::unique_ptr<Instruction> cp_inst(inst);
245 // Remember same-block ops for possible regeneration.
246 if (IsSameBlockOp(&*cp_inst)) {
247 auto* sb_inst_ptr = cp_inst.get();
248 (*preCallSB)[cp_inst->result_id()] = sb_inst_ptr;
249 }
250 new_blk_ptr->AddInstruction(std::move(cp_inst));
251 }
252}
253
254std::unique_ptr<BasicBlock> InlinePass::AddGuardBlock(
255 std::vector<std::unique_ptr<BasicBlock>>* new_blocks,
256 std::unordered_map<uint32_t, uint32_t>* callee2caller,
257 std::unique_ptr<BasicBlock> new_blk_ptr, uint32_t entry_blk_label_id) {
258 const auto guard_block_id = context()->TakeNextId();
259 if (guard_block_id == 0) {
260 return nullptr;
261 }
262 AddBranch(guard_block_id, &new_blk_ptr);
263 new_blocks->push_back(std::move(new_blk_ptr));
264 // Start the next block.
265 new_blk_ptr = MakeUnique<BasicBlock>(NewLabel(guard_block_id));
266 // Reset the mapping of the callee's entry block to point to
267 // the guard block. Do this so we can fix up phis later on to
268 // satisfy dominance.
269 (*callee2caller)[entry_blk_label_id] = guard_block_id;
270 return new_blk_ptr;
271}
272
273InstructionList::iterator InlinePass::AddStoresForVariableInitializers(
274 const std::unordered_map<uint32_t, uint32_t>& callee2caller,
275 std::unique_ptr<BasicBlock>* new_blk_ptr,
276 UptrVectorIterator<BasicBlock> callee_first_block_itr) {
277 auto callee_var_itr = callee_first_block_itr->begin();
278 while (callee_var_itr->opcode() == SpvOp::SpvOpVariable) {
279 if (callee_var_itr->NumInOperands() == 2) {
280 assert(callee2caller.count(callee_var_itr->result_id()) &&
281 "Expected the variable to have already been mapped.");
282 uint32_t new_var_id = callee2caller.at(callee_var_itr->result_id());
283
284 // The initializer must be a constant or global value. No mapped
285 // should be used.
286 uint32_t val_id = callee_var_itr->GetSingleWordInOperand(1);
287 AddStore(new_var_id, val_id, new_blk_ptr);
288 }
289 ++callee_var_itr;
290 }
291 return callee_var_itr;
292}
293
294bool InlinePass::InlineInstructionInBB(
295 const std::unordered_map<uint32_t, uint32_t>& callee2caller,
296 BasicBlock* new_blk_ptr, const Instruction* inst) {
297 // If we have return, it must be at the end of the callee. We will handle
298 // it at the end.
299 if (inst->opcode() == SpvOpReturnValue || inst->opcode() == SpvOpReturn)
300 return true;
301
302 // Copy callee instruction and remap all input Ids.
303 std::unique_ptr<Instruction> cp_inst(inst->Clone(context()));
304 cp_inst->ForEachInId([&callee2caller](uint32_t* iid) {
305 const auto mapItr = callee2caller.find(*iid);
306 if (mapItr != callee2caller.end()) {
307 *iid = mapItr->second;
308 }
309 });
310 // If result id is non-zero, remap it.
311 const uint32_t rid = cp_inst->result_id();
312 if (rid != 0) {
313 const auto mapItr = callee2caller.find(rid);
314 if (mapItr == callee2caller.end()) return false;
315 uint32_t nid = mapItr->second;
316 cp_inst->SetResultId(nid);
317 get_decoration_mgr()->CloneDecorations(rid, nid);
318 }
319 new_blk_ptr->AddInstruction(std::move(cp_inst));
320 return true;
321}
322
323std::unique_ptr<BasicBlock> InlinePass::InlineReturn(
324 const std::unordered_map<uint32_t, uint32_t>& callee2caller,
325 std::vector<std::unique_ptr<BasicBlock>>* new_blocks,
326 std::unique_ptr<BasicBlock> new_blk_ptr, Function* calleeFn,
327 const Instruction* inst, uint32_t returnVarId) {
328 // Store return value to return variable.
329 if (inst->opcode() == SpvOpReturnValue) {
330 assert(returnVarId != 0);
331 uint32_t valId = inst->GetInOperand(kSpvReturnValueId).words[0];
332 const auto mapItr = callee2caller.find(valId);
333 if (mapItr != callee2caller.end()) {
334 valId = mapItr->second;
335 }
336 AddStore(returnVarId, valId, &new_blk_ptr);
337 }
338
339 uint32_t returnLabelId = 0;
340 for (auto callee_block_itr = calleeFn->begin();
341 callee_block_itr != calleeFn->end(); ++callee_block_itr) {
342 if (callee_block_itr->tail()->opcode() == SpvOpUnreachable ||
343 callee_block_itr->tail()->opcode() == SpvOpKill) {
344 returnLabelId = context()->TakeNextId();
345 break;
346 }
347 }
348 if (returnLabelId == 0) return new_blk_ptr;
349
350 if (inst->opcode() == SpvOpReturn || inst->opcode() == SpvOpReturnValue)
351 AddBranch(returnLabelId, &new_blk_ptr);
352 new_blocks->push_back(std::move(new_blk_ptr));
353 return MakeUnique<BasicBlock>(NewLabel(returnLabelId));
354}
355
356bool InlinePass::InlineEntryBlock(
357 const std::unordered_map<uint32_t, uint32_t>& callee2caller,
358 std::unique_ptr<BasicBlock>* new_blk_ptr,
359 UptrVectorIterator<BasicBlock> callee_first_block) {
360 auto callee_inst_itr = AddStoresForVariableInitializers(
361 callee2caller, new_blk_ptr, callee_first_block);
362
363 while (callee_inst_itr != callee_first_block->end()) {
364 if (!InlineInstructionInBB(callee2caller, new_blk_ptr->get(),
365 &*callee_inst_itr)) {
366 return false;
367 }
368 ++callee_inst_itr;
369 }
370 return true;
371}
372
373std::unique_ptr<BasicBlock> InlinePass::InlineBasicBlocks(
374 std::vector<std::unique_ptr<BasicBlock>>* new_blocks,
375 const std::unordered_map<uint32_t, uint32_t>& callee2caller,
376 std::unique_ptr<BasicBlock> new_blk_ptr, Function* calleeFn) {
377 auto callee_block_itr = calleeFn->begin();
378 ++callee_block_itr;
379
380 while (callee_block_itr != calleeFn->end()) {
381 new_blocks->push_back(std::move(new_blk_ptr));
382 const auto mapItr =
383 callee2caller.find(callee_block_itr->GetLabelInst()->result_id());
384 if (mapItr == callee2caller.end()) return nullptr;
385 new_blk_ptr = MakeUnique<BasicBlock>(NewLabel(mapItr->second));
386
387 auto tail_inst_itr = callee_block_itr->end();
388 for (auto inst_itr = callee_block_itr->begin(); inst_itr != tail_inst_itr;
389 ++inst_itr) {
390 if (!InlineInstructionInBB(callee2caller, new_blk_ptr.get(),
391 &*inst_itr)) {
392 return nullptr;
393 }
394 }
395
396 ++callee_block_itr;
397 }
398 return new_blk_ptr;
399}
400
401bool InlinePass::MoveCallerInstsAfterFunctionCall(
402 std::unordered_map<uint32_t, Instruction*>* preCallSB,
403 std::unordered_map<uint32_t, uint32_t>* postCallSB,
404 std::unique_ptr<BasicBlock>* new_blk_ptr,
405 BasicBlock::iterator call_inst_itr, bool multiBlocks) {
406 // Copy remaining instructions from caller block.
407 for (Instruction* inst = call_inst_itr->NextNode(); inst;
408 inst = call_inst_itr->NextNode()) {
409 inst->RemoveFromList();
410 std::unique_ptr<Instruction> cp_inst(inst);
411 // If multiple blocks generated, regenerate any same-block
412 // instruction that has not been seen in this last block.
413 if (multiBlocks) {
414 if (!CloneSameBlockOps(&cp_inst, postCallSB, preCallSB, new_blk_ptr)) {
415 return false;
416 }
417
418 // Remember same-block ops in this block.
419 if (IsSameBlockOp(&*cp_inst)) {
420 const uint32_t rid = cp_inst->result_id();
421 (*postCallSB)[rid] = rid;
422 }
423 }
424 new_blk_ptr->get()->AddInstruction(std::move(cp_inst));
425 }
426
427 return true;
428}
429
430void InlinePass::MoveLoopMergeInstToFirstBlock(
431 std::vector<std::unique_ptr<BasicBlock>>* new_blocks) {
432 // Move the OpLoopMerge from the last block back to the first, where
433 // it belongs.
434 auto& first = new_blocks->front();
435 auto& last = new_blocks->back();
436 assert(first != last);
437
438 // Insert a modified copy of the loop merge into the first block.
439 auto loop_merge_itr = last->tail();
440 --loop_merge_itr;
441 assert(loop_merge_itr->opcode() == SpvOpLoopMerge);
442 std::unique_ptr<Instruction> cp_inst(loop_merge_itr->Clone(context()));
443 first->tail().InsertBefore(std::move(cp_inst));
444
445 // Remove the loop merge from the last block.
446 loop_merge_itr->RemoveFromList();
447 delete &*loop_merge_itr;
448}
449
Steven Perronacd27812018-12-18 19:34:03 +0000450bool InlinePass::GenInlineCode(
dan sinclairc7da51a2018-07-12 15:14:43 -0400451 std::vector<std::unique_ptr<BasicBlock>>* new_blocks,
452 std::vector<std::unique_ptr<Instruction>>* new_vars,
453 BasicBlock::iterator call_inst_itr,
454 UptrVectorIterator<BasicBlock> call_block_itr) {
Greg Fischer04fcc662016-11-10 10:11:50 -0700455 // Map from all ids in the callee to their equivalent id in the caller
456 // as callee instructions are copied into caller.
457 std::unordered_map<uint32_t, uint32_t> callee2caller;
458 // Pre-call same-block insts
dan sinclairc7da51a2018-07-12 15:14:43 -0400459 std::unordered_map<uint32_t, Instruction*> preCallSB;
Greg Fischer04fcc662016-11-10 10:11:50 -0700460 // Post-call same-block op ids
461 std::unordered_map<uint32_t, uint32_t> postCallSB;
462
Steven Perronb3daa932018-03-06 11:20:28 -0500463 // Invalidate the def-use chains. They are not kept up to date while
464 // inlining. However, certain calls try to keep them up-to-date if they are
465 // valid. These operations can fail.
dan sinclairc7da51a2018-07-12 15:14:43 -0400466 context()->InvalidateAnalyses(IRContext::kAnalysisDefUse);
Steven Perronb3daa932018-03-06 11:20:28 -0500467
Steven Perronbd0a2da2020-05-14 10:55:47 -0400468 // If the caller is a loop header and the callee has multiple blocks, then the
469 // normal inlining logic will place the OpLoopMerge in the last of several
470 // blocks in the loop. Instead, it should be placed at the end of the first
471 // block. We'll wait to move the OpLoopMerge until the end of the regular
472 // inlining logic, and only if necessary.
473 bool caller_is_loop_header = call_block_itr->GetLoopMergeInst() != nullptr;
474
475 // Single-trip loop continue block
476 std::unique_ptr<BasicBlock> single_trip_loop_cont_blk;
477
dan sinclairc7da51a2018-07-12 15:14:43 -0400478 Function* calleeFn = id2function_[call_inst_itr->GetSingleWordOperand(
Greg Fischer04fcc662016-11-10 10:11:50 -0700479 kSpvFunctionCallFunctionId)];
480
481 // Map parameters to actual arguments.
482 MapParams(calleeFn, call_inst_itr, &callee2caller);
483
484 // Define caller local variables for all callee variables and create map to
485 // them.
Steven Perronacd27812018-12-18 19:34:03 +0000486 if (!CloneAndMapLocals(calleeFn, new_vars, &callee2caller)) {
487 return false;
488 }
Greg Fischer04fcc662016-11-10 10:11:50 -0700489
Steven Perronbd0a2da2020-05-14 10:55:47 -0400490 // First block needs to use label of original block
491 // but map callee label in case of phi reference.
492 uint32_t entry_blk_label_id = calleeFn->begin()->GetLabelInst()->result_id();
493 callee2caller[entry_blk_label_id] = call_block_itr->id();
494 std::unique_ptr<BasicBlock> new_blk_ptr =
495 MakeUnique<BasicBlock>(NewLabel(call_block_itr->id()));
496
497 // Move instructions of original caller block up to call instruction.
498 MoveInstsBeforeEntryBlock(&preCallSB, new_blk_ptr.get(), call_inst_itr,
499 call_block_itr);
500
501 if (caller_is_loop_header &&
502 (*(calleeFn->begin())).GetMergeInst() != nullptr) {
503 // We can't place both the caller's merge instruction and
504 // another merge instruction in the same block. So split the
505 // calling block. Insert an unconditional branch to a new guard
506 // block. Later, once we know the ID of the last block, we
507 // will move the caller's OpLoopMerge from the last generated
508 // block into the first block. We also wait to avoid
509 // invalidating various iterators.
510 new_blk_ptr = AddGuardBlock(new_blocks, &callee2caller,
511 std::move(new_blk_ptr), entry_blk_label_id);
512 if (new_blk_ptr == nullptr) return false;
513 }
514
Greg Fischer04fcc662016-11-10 10:11:50 -0700515 // Create return var if needed.
Steven Perronacd27812018-12-18 19:34:03 +0000516 const uint32_t calleeTypeId = calleeFn->type_id();
517 uint32_t returnVarId = 0;
518 analysis::Type* calleeType = context()->get_type_mgr()->GetType(calleeTypeId);
519 if (calleeType->AsVoid() == nullptr) {
520 returnVarId = CreateReturnVar(calleeFn, new_vars);
521 if (returnVarId == 0) {
522 return false;
523 }
524 }
Greg Fischer04fcc662016-11-10 10:11:50 -0700525
Steven Perronbd0a2da2020-05-14 10:55:47 -0400526 calleeFn->WhileEachInst([&callee2caller, this](const Instruction* cpi) {
527 // Create set of callee result ids. Used to detect forward references
GregFa699d1a2017-08-29 18:35:05 -0600528 const uint32_t rid = cpi->result_id();
Steven Perronbd0a2da2020-05-14 10:55:47 -0400529 if (rid != 0 && callee2caller.find(rid) == callee2caller.end()) {
530 const uint32_t nid = context()->TakeNextId();
531 if (nid == 0) return false;
532 callee2caller[rid] = nid;
533 }
534 return true;
GregFa699d1a2017-08-29 18:35:05 -0600535 });
536
Steven Perronbd0a2da2020-05-14 10:55:47 -0400537 // Inline the entry block of the callee function.
538 if (!InlineEntryBlock(callee2caller, &new_blk_ptr, calleeFn->begin())) {
Steven Perronacd27812018-12-18 19:34:03 +0000539 return false;
540 }
David Netoefff5fa2017-08-31 15:47:31 -0400541
Steven Perronbd0a2da2020-05-14 10:55:47 -0400542 // Inline blocks of the callee function other than the entry block.
543 new_blk_ptr = InlineBasicBlocks(new_blocks, callee2caller,
544 std::move(new_blk_ptr), calleeFn);
545 if (new_blk_ptr == nullptr) return false;
David Netoefff5fa2017-08-31 15:47:31 -0400546
Steven Perronbd0a2da2020-05-14 10:55:47 -0400547 new_blk_ptr =
548 InlineReturn(callee2caller, new_blocks, std::move(new_blk_ptr), calleeFn,
549 &*(calleeFn->tail()->tail()), returnVarId);
David Netoefff5fa2017-08-31 15:47:31 -0400550
Steven Perronbd0a2da2020-05-14 10:55:47 -0400551 // Load return value into result id of call, if it exists.
552 if (returnVarId != 0) {
553 const uint32_t resId = call_inst_itr->result_id();
554 assert(resId != 0);
555 AddLoad(calleeTypeId, resId, returnVarId, &new_blk_ptr);
David Netoefff5fa2017-08-31 15:47:31 -0400556 }
557
Steven Perronbd0a2da2020-05-14 10:55:47 -0400558 // Move instructions of original caller block after call instruction.
559 if (!MoveCallerInstsAfterFunctionCall(&preCallSB, &postCallSB, &new_blk_ptr,
560 call_inst_itr,
561 calleeFn->begin() != calleeFn->end()))
562 return false;
563
564 // Finalize inline code.
565 new_blocks->push_back(std::move(new_blk_ptr));
566
567 if (caller_is_loop_header && (new_blocks->size() > 1))
568 MoveLoopMergeInstToFirstBlock(new_blocks);
569
Greg Fischer04fcc662016-11-10 10:11:50 -0700570 // Update block map given replacement blocks.
571 for (auto& blk : *new_blocks) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600572 id2block_[blk->id()] = &*blk;
Greg Fischer04fcc662016-11-10 10:11:50 -0700573 }
Steven Perronacd27812018-12-18 19:34:03 +0000574 return true;
Greg Fischer04fcc662016-11-10 10:11:50 -0700575}
576
Steven Perronaa9e8f52019-07-17 14:59:05 -0400577bool InlinePass::IsInlinableFunctionCall(const Instruction* inst) {
David Netoceb1d4f2017-03-31 10:36:58 -0400578 if (inst->opcode() != SpvOp::SpvOpFunctionCall) return false;
GregFa107d342017-04-25 13:57:20 -0600579 const uint32_t calleeFnId =
580 inst->GetSingleWordOperand(kSpvFunctionCallFunctionId);
581 const auto ci = inlinable_.find(calleeFnId);
Steven Perronbd0a2da2020-05-14 10:55:47 -0400582 if (ci == inlinable_.cend()) return false;
583
584 if (early_return_funcs_.find(calleeFnId) != early_return_funcs_.end()) {
585 // We rely on the merge-return pass to handle the early return case
586 // in advance.
587 std::string message =
588 "The function '" + id2function_[calleeFnId]->DefInst().PrettyPrint() +
589 "' could not be inlined because the return instruction "
590 "is not at the end of the function. This could be fixed by "
591 "running merge-return before inlining.";
592 consumer()(SPV_MSG_WARNING, "", {0, 0, 0}, message.c_str());
593 return false;
594 }
595
596 return true;
David Netoceb1d4f2017-03-31 10:36:58 -0400597}
598
GregFe28bd392017-08-01 17:20:13 -0600599void InlinePass::UpdateSucceedingPhis(
dan sinclairc7da51a2018-07-12 15:14:43 -0400600 std::vector<std::unique_ptr<BasicBlock>>& new_blocks) {
GregFe28bd392017-08-01 17:20:13 -0600601 const auto firstBlk = new_blocks.begin();
602 const auto lastBlk = new_blocks.end() - 1;
603 const uint32_t firstId = (*firstBlk)->id();
604 const uint32_t lastId = (*lastBlk)->id();
dan sinclairc7da51a2018-07-12 15:14:43 -0400605 const BasicBlock& const_last_block = *lastBlk->get();
David Neto87f9cfa2018-02-02 14:17:42 -0800606 const_last_block.ForEachSuccessorLabel(
607 [&firstId, &lastId, this](const uint32_t succ) {
dan sinclairc7da51a2018-07-12 15:14:43 -0400608 BasicBlock* sbp = this->id2block_[succ];
609 sbp->ForEachPhiInst([&firstId, &lastId](Instruction* phi) {
David Neto87f9cfa2018-02-02 14:17:42 -0800610 phi->ForEachInId([&firstId, &lastId](uint32_t* id) {
611 if (*id == firstId) *id = lastId;
612 });
613 });
GregFe28bd392017-08-01 17:20:13 -0600614 });
Greg Fischer04fcc662016-11-10 10:11:50 -0700615}
616
dan sinclairc7da51a2018-07-12 15:14:43 -0400617bool InlinePass::HasNoReturnInLoop(Function* func) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600618 // If control not structured, do not do loop/return analysis
619 // TODO: Analyze returns in non-structured control flow
Steven Perron756b2772017-12-19 14:18:13 -0500620 if (!context()->get_feature_mgr()->HasCapability(SpvCapabilityShader))
621 return false;
greg-lunarg67214782018-11-08 07:11:20 -0700622 const auto structured_analysis = context()->GetStructuredCFGAnalysis();
623 // Search for returns in structured construct.
Greg Fischerbba812f2017-05-04 20:55:53 -0600624 bool return_in_loop = false;
greg-lunarg67214782018-11-08 07:11:20 -0700625 for (auto& blk : *func) {
626 auto terminal_ii = blk.cend();
Greg Fischerbba812f2017-05-04 20:55:53 -0600627 --terminal_ii;
greg-lunarg67214782018-11-08 07:11:20 -0700628 if (spvOpcodeIsReturn(terminal_ii->opcode()) &&
629 structured_analysis->ContainingLoop(blk.id()) != 0) {
630 return_in_loop = true;
631 break;
Greg Fischerbba812f2017-05-04 20:55:53 -0600632 }
633 }
634 return !return_in_loop;
635}
636
dan sinclairc7da51a2018-07-12 15:14:43 -0400637void InlinePass::AnalyzeReturns(Function* func) {
Steven Perronbd0a2da2020-05-14 10:55:47 -0400638 // Analyze functions without a return in loop.
greg-lunarg67214782018-11-08 07:11:20 -0700639 if (HasNoReturnInLoop(func)) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600640 no_return_in_loop_.insert(func->result_id());
Steven Perronbd0a2da2020-05-14 10:55:47 -0400641 }
642 // Analyze functions with a return before its tail basic block.
643 for (auto& blk : *func) {
644 auto terminal_ii = blk.cend();
645 --terminal_ii;
646 if (spvOpcodeIsReturn(terminal_ii->opcode()) && &blk != func->tail()) {
greg-lunarg67214782018-11-08 07:11:20 -0700647 early_return_funcs_.insert(func->result_id());
Steven Perronbd0a2da2020-05-14 10:55:47 -0400648 break;
649 }
Greg Fischerbba812f2017-05-04 20:55:53 -0600650 }
Greg Fischerbba812f2017-05-04 20:55:53 -0600651}
652
dan sinclairc7da51a2018-07-12 15:14:43 -0400653bool InlinePass::IsInlinableFunction(Function* func) {
GregFa107d342017-04-25 13:57:20 -0600654 // We can only inline a function if it has blocks.
Diego Novillod2938e42017-11-08 12:40:02 -0500655 if (func->cbegin() == func->cend()) return false;
Greg Fischerbba812f2017-05-04 20:55:53 -0600656 // Do not inline functions with returns in loops. Currently early return
657 // functions are inlined by wrapping them in a one trip loop and implementing
658 // the returns as a branch to the loop's merge block. However, this can only
659 // done validly if the return was not in a loop in the original function.
660 // Also remember functions with multiple (early) returns.
661 AnalyzeReturns(func);
Steven Perron2d2a5122018-11-29 14:24:58 -0500662 if (no_return_in_loop_.find(func->result_id()) == no_return_in_loop_.cend()) {
663 return false;
664 }
665
666 if (func->IsRecursive()) {
667 return false;
668 }
669
Steven Perronc18c9ff2019-10-04 13:05:32 -0400670 // Do not inline functions with an OpKill if they are called from a continue
671 // construct. If it is inlined into a continue construct it will generate
672 // invalid code.
673 bool func_is_called_from_continue =
674 funcs_called_from_continue_.count(func->result_id()) != 0;
Steven Perronc7a39bc2019-09-11 13:26:55 -0400675
Steven Perronc18c9ff2019-10-04 13:05:32 -0400676 if (func_is_called_from_continue && ContainsKill(func)) {
Steven Perronc7a39bc2019-09-11 13:26:55 -0400677 return false;
678 }
679
Steven Perron2d2a5122018-11-29 14:24:58 -0500680 return true;
GregFa107d342017-04-25 13:57:20 -0600681}
682
Steven Perronc18c9ff2019-10-04 13:05:32 -0400683bool InlinePass::ContainsKill(Function* func) const {
684 return !func->WhileEachInst(
685 [](Instruction* inst) { return inst->opcode() != SpvOpKill; });
686}
687
dan sinclairf96b7f12018-07-12 09:08:45 -0400688void InlinePass::InitializeInline() {
Greg Fischerbba812f2017-05-04 20:55:53 -0600689 false_id_ = 0;
690
GregFe28bd392017-08-01 17:20:13 -0600691 // clear collections
Greg Fischer04fcc662016-11-10 10:11:50 -0700692 id2function_.clear();
693 id2block_.clear();
GregFa107d342017-04-25 13:57:20 -0600694 inlinable_.clear();
GregFe28bd392017-08-01 17:20:13 -0600695 no_return_in_loop_.clear();
greg-lunarg67214782018-11-08 07:11:20 -0700696 early_return_funcs_.clear();
Steven Perronc18c9ff2019-10-04 13:05:32 -0400697 funcs_called_from_continue_ =
698 context()->GetStructuredCFGAnalysis()->FindFuncsCalledFromContinue();
GregFe28bd392017-08-01 17:20:13 -0600699
Diego Novillo1040a952017-10-25 13:26:25 -0400700 for (auto& fn : *get_module()) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600701 // Initialize function and block maps.
Greg Fischer04fcc662016-11-10 10:11:50 -0700702 id2function_[fn.result_id()] = &fn;
703 for (auto& blk : fn) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600704 id2block_[blk.id()] = &blk;
Greg Fischer04fcc662016-11-10 10:11:50 -0700705 }
Greg Fischerbba812f2017-05-04 20:55:53 -0600706 // Compute inlinability
Diego Novillod2938e42017-11-08 12:40:02 -0500707 if (IsInlinableFunction(&fn)) inlinable_.insert(fn.result_id());
Greg Fischer04fcc662016-11-10 10:11:50 -0700708 }
Eleni Maria Stea045cc8f2018-03-21 11:15:56 +0200709}
Greg Fischer04fcc662016-11-10 10:11:50 -0700710
Diego Novillo1040a952017-10-25 13:26:25 -0400711InlinePass::InlinePass() {}
Greg Fischer04fcc662016-11-10 10:11:50 -0700712
Greg Fischer04fcc662016-11-10 10:11:50 -0700713} // namespace opt
714} // namespace spvtools