blob: 0d8f716bf33324850cb619abc30d93aace4ca7a8 [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
17#include "inline_pass.h"
GregFe28bd392017-08-01 17:20:13 -060018
Greg Fischerbba812f2017-05-04 20:55:53 -060019#include "cfa.h"
Greg Fischer04fcc662016-11-10 10:11:50 -070020
21// Indices of operands in SPIR-V instructions
22
Greg Fischer04fcc662016-11-10 10:11:50 -070023static const int kSpvFunctionCallFunctionId = 2;
24static const int kSpvFunctionCallArgumentId = 3;
25static const int kSpvReturnValueId = 0;
26static const int kSpvTypePointerStorageClass = 1;
27static const int kSpvTypePointerTypeId = 2;
Greg Fischerbba812f2017-05-04 20:55:53 -060028static const int kSpvLoopMergeMergeBlockId = 0;
David Netoefff5fa2017-08-31 15:47:31 -040029static const int kSpvLoopMergeContinueTargetIdInIdx = 1;
Greg Fischerbba812f2017-05-04 20:55:53 -060030static const int kSpvSelectionMergeMergeBlockId = 0;
Greg Fischer04fcc662016-11-10 10:11:50 -070031
32namespace spvtools {
33namespace opt {
34
35uint32_t InlinePass::FindPointerToType(uint32_t type_id,
36 SpvStorageClass storage_class) {
37 ir::Module::inst_iterator type_itr = module_->types_values_begin();
38 for (; type_itr != module_->types_values_end(); ++type_itr) {
39 const ir::Instruction* type_inst = &*type_itr;
40 if (type_inst->opcode() == SpvOpTypePointer &&
41 type_inst->GetSingleWordOperand(kSpvTypePointerTypeId) == type_id &&
42 type_inst->GetSingleWordOperand(kSpvTypePointerStorageClass) ==
43 storage_class)
44 return type_inst->result_id();
45 }
46 return 0;
47}
48
49uint32_t InlinePass::AddPointerToType(uint32_t type_id,
50 SpvStorageClass storage_class) {
51 uint32_t resultId = TakeNextId();
52 std::unique_ptr<ir::Instruction> type_inst(new ir::Instruction(
53 SpvOpTypePointer, 0, resultId,
54 {{spv_operand_type_t::SPV_OPERAND_TYPE_STORAGE_CLASS,
55 {uint32_t(storage_class)}},
56 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {type_id}}}));
57 module_->AddType(std::move(type_inst));
58 return resultId;
59}
60
61void InlinePass::AddBranch(uint32_t label_id,
Greg Fischerbba812f2017-05-04 20:55:53 -060062 std::unique_ptr<ir::BasicBlock>* block_ptr) {
Greg Fischer04fcc662016-11-10 10:11:50 -070063 std::unique_ptr<ir::Instruction> newBranch(new ir::Instruction(
Greg Fischerbba812f2017-05-04 20:55:53 -060064 SpvOpBranch, 0, 0,
65 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {label_id}}}));
Greg Fischer04fcc662016-11-10 10:11:50 -070066 (*block_ptr)->AddInstruction(std::move(newBranch));
67}
68
Greg Fischerbba812f2017-05-04 20:55:53 -060069void InlinePass::AddBranchCond(uint32_t cond_id, uint32_t true_id,
70 uint32_t false_id, std::unique_ptr<ir::BasicBlock>* block_ptr) {
71 std::unique_ptr<ir::Instruction> newBranch(new ir::Instruction(
72 SpvOpBranchConditional, 0, 0,
73 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {cond_id}},
74 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {true_id}},
75 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {false_id}}}));
76 (*block_ptr)->AddInstruction(std::move(newBranch));
77}
78
79void InlinePass::AddLoopMerge(uint32_t merge_id, uint32_t continue_id,
80 std::unique_ptr<ir::BasicBlock>* block_ptr) {
81 std::unique_ptr<ir::Instruction> newLoopMerge(new ir::Instruction(
82 SpvOpLoopMerge, 0, 0,
83 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {merge_id}},
84 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {continue_id}},
85 {spv_operand_type_t::SPV_OPERAND_TYPE_LOOP_CONTROL, {0}}}));
86 (*block_ptr)->AddInstruction(std::move(newLoopMerge));
87}
88
Greg Fischer04fcc662016-11-10 10:11:50 -070089void InlinePass::AddStore(uint32_t ptr_id, uint32_t val_id,
90 std::unique_ptr<ir::BasicBlock>* block_ptr) {
91 std::unique_ptr<ir::Instruction> newStore(new ir::Instruction(
92 SpvOpStore, 0, 0, {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {ptr_id}},
93 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {val_id}}}));
94 (*block_ptr)->AddInstruction(std::move(newStore));
95}
96
97void InlinePass::AddLoad(uint32_t type_id, uint32_t resultId, uint32_t ptr_id,
98 std::unique_ptr<ir::BasicBlock>* block_ptr) {
99 std::unique_ptr<ir::Instruction> newLoad(new ir::Instruction(
100 SpvOpLoad, type_id, resultId,
101 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {ptr_id}}}));
102 (*block_ptr)->AddInstruction(std::move(newLoad));
103}
104
105std::unique_ptr<ir::Instruction> InlinePass::NewLabel(uint32_t label_id) {
106 std::unique_ptr<ir::Instruction> newLabel(
107 new ir::Instruction(SpvOpLabel, 0, label_id, {}));
108 return newLabel;
109}
110
Greg Fischerbba812f2017-05-04 20:55:53 -0600111uint32_t InlinePass::GetFalseId() {
112 if (false_id_ != 0)
113 return false_id_;
114 false_id_ = module_->GetGlobalValue(SpvOpConstantFalse);
115 if (false_id_ != 0)
116 return false_id_;
117 uint32_t boolId = module_->GetGlobalValue(SpvOpTypeBool);
118 if (boolId == 0) {
119 boolId = TakeNextId();
120 module_->AddGlobalValue(SpvOpTypeBool, boolId, 0);
121 }
122 false_id_ = TakeNextId();
123 module_->AddGlobalValue(SpvOpConstantFalse, false_id_, boolId);
124 return false_id_;
125}
126
Greg Fischer04fcc662016-11-10 10:11:50 -0700127void InlinePass::MapParams(
128 ir::Function* calleeFn,
129 ir::UptrVectorIterator<ir::Instruction> call_inst_itr,
130 std::unordered_map<uint32_t, uint32_t>* callee2caller) {
131 int param_idx = 0;
132 calleeFn->ForEachParam(
133 [&call_inst_itr, &param_idx, &callee2caller](const ir::Instruction* cpi) {
134 const uint32_t pid = cpi->result_id();
135 (*callee2caller)[pid] = call_inst_itr->GetSingleWordOperand(
136 kSpvFunctionCallArgumentId + param_idx);
Greg Fischerbba812f2017-05-04 20:55:53 -0600137 ++param_idx;
Greg Fischer04fcc662016-11-10 10:11:50 -0700138 });
139}
140
141void InlinePass::CloneAndMapLocals(
142 ir::Function* calleeFn,
143 std::vector<std::unique_ptr<ir::Instruction>>* new_vars,
144 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) {
148 std::unique_ptr<ir::Instruction> var_inst(
149 new ir::Instruction(*callee_var_itr));
150 uint32_t newId = TakeNextId();
151 var_inst->SetResultId(newId);
152 (*callee2caller)[callee_var_itr->result_id()] = newId;
153 new_vars->push_back(std::move(var_inst));
Greg Fischerbba812f2017-05-04 20:55:53 -0600154 ++callee_var_itr;
Greg Fischer04fcc662016-11-10 10:11:50 -0700155 }
156}
157
158uint32_t InlinePass::CreateReturnVar(
159 ir::Function* calleeFn,
160 std::vector<std::unique_ptr<ir::Instruction>>* new_vars) {
161 uint32_t returnVarId = 0;
162 const uint32_t calleeTypeId = calleeFn->type_id();
163 const ir::Instruction* calleeType =
164 def_use_mgr_->id_to_defs().find(calleeTypeId)->second;
165 if (calleeType->opcode() != SpvOpTypeVoid) {
166 // Find or create ptr to callee return type.
167 uint32_t returnVarTypeId =
168 FindPointerToType(calleeTypeId, SpvStorageClassFunction);
169 if (returnVarTypeId == 0)
170 returnVarTypeId = AddPointerToType(calleeTypeId, SpvStorageClassFunction);
171 // Add return var to new function scope variables.
172 returnVarId = TakeNextId();
173 std::unique_ptr<ir::Instruction> var_inst(new ir::Instruction(
174 SpvOpVariable, returnVarTypeId, returnVarId,
175 {{spv_operand_type_t::SPV_OPERAND_TYPE_STORAGE_CLASS,
176 {SpvStorageClassFunction}}}));
177 new_vars->push_back(std::move(var_inst));
178 }
179 return returnVarId;
180}
181
182bool InlinePass::IsSameBlockOp(const ir::Instruction* inst) const {
183 return inst->opcode() == SpvOpSampledImage || inst->opcode() == SpvOpImage;
184}
185
186void InlinePass::CloneSameBlockOps(
187 std::unique_ptr<ir::Instruction>* inst,
188 std::unordered_map<uint32_t, uint32_t>* postCallSB,
189 std::unordered_map<uint32_t, ir::Instruction*>* preCallSB,
190 std::unique_ptr<ir::BasicBlock>* block_ptr) {
191 (*inst)
192 ->ForEachInId([&postCallSB, &preCallSB, &block_ptr, this](uint32_t* iid) {
193 const auto mapItr = (*postCallSB).find(*iid);
194 if (mapItr == (*postCallSB).end()) {
195 const auto mapItr2 = (*preCallSB).find(*iid);
196 if (mapItr2 != (*preCallSB).end()) {
197 // Clone pre-call same-block ops, map result id.
198 const ir::Instruction* inInst = mapItr2->second;
199 std::unique_ptr<ir::Instruction> sb_inst(
200 new ir::Instruction(*inInst));
201 CloneSameBlockOps(&sb_inst, postCallSB, preCallSB, block_ptr);
202 const uint32_t rid = sb_inst->result_id();
203 const uint32_t nid = this->TakeNextId();
204 sb_inst->SetResultId(nid);
205 (*postCallSB)[rid] = nid;
206 *iid = nid;
207 (*block_ptr)->AddInstruction(std::move(sb_inst));
208 }
209 } else {
210 // Reset same-block op operand.
211 *iid = mapItr->second;
212 }
213 });
214}
215
216void InlinePass::GenInlineCode(
217 std::vector<std::unique_ptr<ir::BasicBlock>>* new_blocks,
218 std::vector<std::unique_ptr<ir::Instruction>>* new_vars,
219 ir::UptrVectorIterator<ir::Instruction> call_inst_itr,
220 ir::UptrVectorIterator<ir::BasicBlock> call_block_itr) {
221 // Map from all ids in the callee to their equivalent id in the caller
222 // as callee instructions are copied into caller.
223 std::unordered_map<uint32_t, uint32_t> callee2caller;
224 // Pre-call same-block insts
225 std::unordered_map<uint32_t, ir::Instruction*> preCallSB;
226 // Post-call same-block op ids
227 std::unordered_map<uint32_t, uint32_t> postCallSB;
228
229 ir::Function* calleeFn = id2function_[call_inst_itr->GetSingleWordOperand(
230 kSpvFunctionCallFunctionId)];
231
David Neto2a1014b2017-08-09 14:59:04 -0400232 // Check for multiple returns in the callee.
233 auto fi = multi_return_funcs_.find(calleeFn->result_id());
234 const bool multiReturn = fi != multi_return_funcs_.end();
Greg Fischerbba812f2017-05-04 20:55:53 -0600235
Greg Fischer04fcc662016-11-10 10:11:50 -0700236 // Map parameters to actual arguments.
237 MapParams(calleeFn, call_inst_itr, &callee2caller);
238
239 // Define caller local variables for all callee variables and create map to
240 // them.
241 CloneAndMapLocals(calleeFn, new_vars, &callee2caller);
242
243 // Create return var if needed.
244 uint32_t returnVarId = CreateReturnVar(calleeFn, new_vars);
245
GregFa699d1a2017-08-29 18:35:05 -0600246 // Create set of callee result ids. Used to detect forward references
247 std::unordered_set<uint32_t> callee_result_ids;
248 calleeFn->ForEachInst([&callee_result_ids](
249 const ir::Instruction* cpi) {
250 const uint32_t rid = cpi->result_id();
251 if (rid != 0)
252 callee_result_ids.insert(rid);
253 });
254
David Netoefff5fa2017-08-31 15:47:31 -0400255 // If the caller is in a single-block loop, and the callee has multiple
256 // blocks, then the normal inlining logic will place the OpLoopMerge in
257 // the last of several blocks in the loop. Instead, it should be placed
258 // at the end of the first block. First determine if the caller is in a
259 // single block loop. We'll wait to move the OpLoopMerge until the end
260 // of the regular inlining logic, and only if necessary.
261 bool caller_is_single_block_loop = false;
David Neto25ddfec2017-09-02 19:01:03 -0400262 bool caller_is_loop_header = false;
David Netoefff5fa2017-08-31 15:47:31 -0400263 if (auto* loop_merge = call_block_itr->GetLoopMergeInst()) {
David Neto25ddfec2017-09-02 19:01:03 -0400264 caller_is_loop_header = true;
David Netoefff5fa2017-08-31 15:47:31 -0400265 caller_is_single_block_loop =
266 call_block_itr->id() ==
267 loop_merge->GetSingleWordInOperand(kSpvLoopMergeContinueTargetIdInIdx);
268 }
269
270 bool callee_begins_with_structured_header =
271 (*(calleeFn->begin())).GetMergeInst() != nullptr;
272
Greg Fischer04fcc662016-11-10 10:11:50 -0700273 // Clone and map callee code. Copy caller block code to beginning of
274 // first block and end of last block.
275 bool prevInstWasReturn = false;
Greg Fischerbba812f2017-05-04 20:55:53 -0600276 uint32_t singleTripLoopHeaderId = 0;
277 uint32_t singleTripLoopContinueId = 0;
Greg Fischer04fcc662016-11-10 10:11:50 -0700278 uint32_t returnLabelId = 0;
279 bool multiBlocks = false;
280 const uint32_t calleeTypeId = calleeFn->type_id();
David Neto2a1014b2017-08-09 14:59:04 -0400281 // new_blk_ptr is a new basic block in the caller. New instructions are
282 // written to it. It is created when we encounter the OpLabel
David Netoefff5fa2017-08-31 15:47:31 -0400283 // of the first callee block. It is appended to new_blocks only when
284 // it is complete.
Greg Fischer04fcc662016-11-10 10:11:50 -0700285 std::unique_ptr<ir::BasicBlock> new_blk_ptr;
286 calleeFn->ForEachInst([&new_blocks, &callee2caller, &call_block_itr,
287 &call_inst_itr, &new_blk_ptr, &prevInstWasReturn,
David Neto25ddfec2017-09-02 19:01:03 -0400288 &returnLabelId, &returnVarId, caller_is_loop_header,
David Netoefff5fa2017-08-31 15:47:31 -0400289 callee_begins_with_structured_header, &calleeTypeId,
David Neto2a1014b2017-08-09 14:59:04 -0400290 &multiBlocks, &postCallSB, &preCallSB, multiReturn,
Greg Fischerbba812f2017-05-04 20:55:53 -0600291 &singleTripLoopHeaderId, &singleTripLoopContinueId,
David Netoefff5fa2017-08-31 15:47:31 -0400292 &callee_result_ids, this](const ir::Instruction* cpi) {
Greg Fischer04fcc662016-11-10 10:11:50 -0700293 switch (cpi->opcode()) {
294 case SpvOpFunction:
295 case SpvOpFunctionParameter:
296 case SpvOpVariable:
297 // Already processed
298 break;
299 case SpvOpLabel: {
300 // If previous instruction was early return, insert branch
301 // instruction to return block.
302 if (prevInstWasReturn) {
303 if (returnLabelId == 0) returnLabelId = this->TakeNextId();
304 AddBranch(returnLabelId, &new_blk_ptr);
305 prevInstWasReturn = false;
306 }
307 // Finish current block (if it exists) and get label for next block.
308 uint32_t labelId;
309 bool firstBlock = false;
310 if (new_blk_ptr != nullptr) {
311 new_blocks->push_back(std::move(new_blk_ptr));
312 // If result id is already mapped, use it, otherwise get a new
313 // one.
314 const uint32_t rid = cpi->result_id();
315 const auto mapItr = callee2caller.find(rid);
316 labelId = (mapItr != callee2caller.end()) ? mapItr->second
317 : this->TakeNextId();
318 } else {
319 // First block needs to use label of original block
320 // but map callee label in case of phi reference.
Greg Fischerbba812f2017-05-04 20:55:53 -0600321 labelId = call_block_itr->id();
Greg Fischer04fcc662016-11-10 10:11:50 -0700322 callee2caller[cpi->result_id()] = labelId;
323 firstBlock = true;
324 }
325 // Create first/next block.
326 new_blk_ptr.reset(new ir::BasicBlock(NewLabel(labelId)));
327 if (firstBlock) {
328 // Copy contents of original caller block up to call instruction.
329 for (auto cii = call_block_itr->begin(); cii != call_inst_itr;
Greg Fischerbba812f2017-05-04 20:55:53 -0600330 ++cii) {
Greg Fischer04fcc662016-11-10 10:11:50 -0700331 std::unique_ptr<ir::Instruction> cp_inst(new ir::Instruction(*cii));
332 // Remember same-block ops for possible regeneration.
333 if (IsSameBlockOp(&*cp_inst)) {
334 auto* sb_inst_ptr = cp_inst.get();
335 preCallSB[cp_inst->result_id()] = sb_inst_ptr;
336 }
337 new_blk_ptr->AddInstruction(std::move(cp_inst));
338 }
David Neto25ddfec2017-09-02 19:01:03 -0400339 if (caller_is_loop_header &&
David Netoefff5fa2017-08-31 15:47:31 -0400340 callee_begins_with_structured_header) {
341 // We can't place both the caller's merge instruction and another
342 // merge instruction in the same block. So split the calling block.
343 // Insert an unconditional branch to a new guard block. Later,
344 // once we know the ID of the last block, we will move the caller's
345 // OpLoopMerge from the last generated block into the first block.
346 // We also wait to avoid invalidating various iterators.
347 const auto guard_block_id = this->TakeNextId();
348 AddBranch(guard_block_id, &new_blk_ptr);
349 new_blocks->push_back(std::move(new_blk_ptr));
350 // Start the next block.
351 new_blk_ptr.reset(new ir::BasicBlock(NewLabel(guard_block_id)));
352 // Reset the mapping of the callee's entry block to point to
353 // the guard block. Do this so we can fix up phis later on to
354 // satisfy dominance.
355 callee2caller[cpi->result_id()] = guard_block_id;
356 }
357 // If callee has multiple returns, insert a header block for
David Neto2a1014b2017-08-09 14:59:04 -0400358 // single-trip loop that will encompass callee code. Start postheader
Greg Fischerbba812f2017-05-04 20:55:53 -0600359 // block.
David Netoefff5fa2017-08-31 15:47:31 -0400360 //
361 // Note: Consider the following combination:
362 // - the caller is a single block loop
363 // - the callee does not begin with a structure header
364 // - the callee has multiple returns.
365 // We still need to split the caller block and insert a guard block.
366 // But we only need to do it once. We haven't done it yet, but the
367 // single-trip loop header will serve the same purpose.
David Neto2a1014b2017-08-09 14:59:04 -0400368 if (multiReturn) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600369 singleTripLoopHeaderId = this->TakeNextId();
370 AddBranch(singleTripLoopHeaderId, &new_blk_ptr);
371 new_blocks->push_back(std::move(new_blk_ptr));
372 new_blk_ptr.reset(new ir::BasicBlock(NewLabel(
373 singleTripLoopHeaderId)));
374 returnLabelId = this->TakeNextId();
375 singleTripLoopContinueId = this->TakeNextId();
376 AddLoopMerge(returnLabelId, singleTripLoopContinueId, &new_blk_ptr);
377 uint32_t postHeaderId = this->TakeNextId();
378 AddBranch(postHeaderId, &new_blk_ptr);
379 new_blocks->push_back(std::move(new_blk_ptr));
380 new_blk_ptr.reset(new ir::BasicBlock(NewLabel(postHeaderId)));
381 multiBlocks = true;
David Neto860c4192017-08-31 17:33:44 -0400382 // Reset the mapping of the callee's entry block to point to
383 // the post-header block. Do this so we can fix up phis later
384 // on to satisfy dominance.
385 callee2caller[cpi->result_id()] = postHeaderId;
Greg Fischerbba812f2017-05-04 20:55:53 -0600386 }
Greg Fischer04fcc662016-11-10 10:11:50 -0700387 } else {
388 multiBlocks = true;
389 }
390 } break;
391 case SpvOpReturnValue: {
392 // Store return value to return variable.
393 assert(returnVarId != 0);
394 uint32_t valId = cpi->GetInOperand(kSpvReturnValueId).words[0];
395 const auto mapItr = callee2caller.find(valId);
396 if (mapItr != callee2caller.end()) {
397 valId = mapItr->second;
398 }
399 AddStore(returnVarId, valId, &new_blk_ptr);
400
401 // Remember we saw a return; if followed by a label, will need to
402 // insert branch.
403 prevInstWasReturn = true;
404 } break;
405 case SpvOpReturn: {
406 // Remember we saw a return; if followed by a label, will need to
407 // insert branch.
408 prevInstWasReturn = true;
409 } break;
410 case SpvOpFunctionEnd: {
David Neto2a1014b2017-08-09 14:59:04 -0400411 // If there was an early return, we generated a return label id
412 // for it. Now we have to generate the return block with that Id.
Greg Fischer04fcc662016-11-10 10:11:50 -0700413 if (returnLabelId != 0) {
David Neto2a1014b2017-08-09 14:59:04 -0400414 // If previous instruction was return, insert branch instruction
415 // to return block.
Greg Fischer04fcc662016-11-10 10:11:50 -0700416 if (prevInstWasReturn) AddBranch(returnLabelId, &new_blk_ptr);
David Neto2a1014b2017-08-09 14:59:04 -0400417 if (multiReturn) {
418 // If we generated a loop header to for the single-trip loop
419 // to accommodate multiple returns, insert the continue
420 // target block now, with a false branch back to the loop header.
421 new_blocks->push_back(std::move(new_blk_ptr));
422 new_blk_ptr.reset(
423 new ir::BasicBlock(NewLabel(singleTripLoopContinueId)));
424 AddBranchCond(GetFalseId(), singleTripLoopHeaderId, returnLabelId,
425 &new_blk_ptr);
426 }
427 // Generate the return block.
Greg Fischerbba812f2017-05-04 20:55:53 -0600428 new_blocks->push_back(std::move(new_blk_ptr));
Greg Fischer04fcc662016-11-10 10:11:50 -0700429 new_blk_ptr.reset(new ir::BasicBlock(NewLabel(returnLabelId)));
430 multiBlocks = true;
431 }
432 // Load return value into result id of call, if it exists.
433 if (returnVarId != 0) {
434 const uint32_t resId = call_inst_itr->result_id();
435 assert(resId != 0);
436 AddLoad(calleeTypeId, resId, returnVarId, &new_blk_ptr);
437 }
438 // Copy remaining instructions from caller block.
439 auto cii = call_inst_itr;
Greg Fischerbba812f2017-05-04 20:55:53 -0600440 for (++cii; cii != call_block_itr->end(); ++cii) {
Greg Fischer04fcc662016-11-10 10:11:50 -0700441 std::unique_ptr<ir::Instruction> cp_inst(new ir::Instruction(*cii));
442 // If multiple blocks generated, regenerate any same-block
443 // instruction that has not been seen in this last block.
444 if (multiBlocks) {
445 CloneSameBlockOps(&cp_inst, &postCallSB, &preCallSB, &new_blk_ptr);
446 // Remember same-block ops in this block.
447 if (IsSameBlockOp(&*cp_inst)) {
448 const uint32_t rid = cp_inst->result_id();
449 postCallSB[rid] = rid;
450 }
451 }
452 new_blk_ptr->AddInstruction(std::move(cp_inst));
453 }
454 // Finalize inline code.
455 new_blocks->push_back(std::move(new_blk_ptr));
456 } break;
457 default: {
458 // Copy callee instruction and remap all input Ids.
459 std::unique_ptr<ir::Instruction> cp_inst(new ir::Instruction(*cpi));
David Netoefff5fa2017-08-31 15:47:31 -0400460 cp_inst->ForEachInId([&callee2caller, &callee_result_ids,
461 this](uint32_t* iid) {
Greg Fischer04fcc662016-11-10 10:11:50 -0700462 const auto mapItr = callee2caller.find(*iid);
463 if (mapItr != callee2caller.end()) {
464 *iid = mapItr->second;
GregFa699d1a2017-08-29 18:35:05 -0600465 } else if (callee_result_ids.find(*iid) != callee_result_ids.end()) {
466 // Forward reference. Allocate a new id, map it,
467 // use it and check for it when remapping result ids
468 const uint32_t nid = this->TakeNextId();
469 callee2caller[*iid] = nid;
470 *iid = nid;
Greg Fischer04fcc662016-11-10 10:11:50 -0700471 }
472 });
GregFa699d1a2017-08-29 18:35:05 -0600473 // If result id is non-zero, remap it. If already mapped, use mapped
474 // value, else use next id.
Greg Fischer04fcc662016-11-10 10:11:50 -0700475 const uint32_t rid = cp_inst->result_id();
476 if (rid != 0) {
GregFa699d1a2017-08-29 18:35:05 -0600477 const auto mapItr = callee2caller.find(rid);
478 uint32_t nid;
479 if (mapItr != callee2caller.end()) {
480 nid = mapItr->second;
481 }
482 else {
483 nid = this->TakeNextId();
484 callee2caller[rid] = nid;
485 }
Greg Fischer04fcc662016-11-10 10:11:50 -0700486 cp_inst->SetResultId(nid);
487 }
488 new_blk_ptr->AddInstruction(std::move(cp_inst));
489 } break;
490 }
491 });
David Netoefff5fa2017-08-31 15:47:31 -0400492
David Neto25ddfec2017-09-02 19:01:03 -0400493 if (caller_is_loop_header && (new_blocks->size() > 1)) {
David Netoefff5fa2017-08-31 15:47:31 -0400494 // Move the OpLoopMerge from the last block back to the first, where
David Neto25ddfec2017-09-02 19:01:03 -0400495 // it belongs.
David Netoefff5fa2017-08-31 15:47:31 -0400496 auto& first = new_blocks->front();
497 auto& last = new_blocks->back();
498 assert(first != last);
499
500 // Insert a modified copy of the loop merge into the first block.
501 auto loop_merge_itr = last->tail();
502 --loop_merge_itr;
503 assert(loop_merge_itr->opcode() == SpvOpLoopMerge);
David Neto25ddfec2017-09-02 19:01:03 -0400504 std::unique_ptr<ir::Instruction> cp_inst(
505 new ir::Instruction(*loop_merge_itr));
506 if (caller_is_single_block_loop) {
507 // Also, update its continue target to point to the last block.
508 cp_inst->SetInOperand(kSpvLoopMergeContinueTargetIdInIdx, {last->id()});
509 }
David Netoefff5fa2017-08-31 15:47:31 -0400510 first->tail().InsertBefore(std::move(cp_inst));
511
512 // Remove the loop merge from the last block.
513 loop_merge_itr.Erase();
514 }
515
Greg Fischer04fcc662016-11-10 10:11:50 -0700516 // Update block map given replacement blocks.
517 for (auto& blk : *new_blocks) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600518 id2block_[blk->id()] = &*blk;
Greg Fischer04fcc662016-11-10 10:11:50 -0700519 }
520}
521
David Netoceb1d4f2017-03-31 10:36:58 -0400522bool InlinePass::IsInlinableFunctionCall(const ir::Instruction* inst) {
523 if (inst->opcode() != SpvOp::SpvOpFunctionCall) return false;
GregFa107d342017-04-25 13:57:20 -0600524 const uint32_t calleeFnId =
525 inst->GetSingleWordOperand(kSpvFunctionCallFunctionId);
526 const auto ci = inlinable_.find(calleeFnId);
527 return ci != inlinable_.cend();
David Netoceb1d4f2017-03-31 10:36:58 -0400528}
529
GregFe28bd392017-08-01 17:20:13 -0600530void InlinePass::UpdateSucceedingPhis(
531 std::vector<std::unique_ptr<ir::BasicBlock>>& new_blocks) {
532 const auto firstBlk = new_blocks.begin();
533 const auto lastBlk = new_blocks.end() - 1;
534 const uint32_t firstId = (*firstBlk)->id();
535 const uint32_t lastId = (*lastBlk)->id();
536 (*lastBlk)->ForEachSuccessorLabel(
537 [&firstId, &lastId, this](uint32_t succ) {
538 ir::BasicBlock* sbp = this->id2block_[succ];
539 sbp->ForEachPhiInst([&firstId, &lastId](ir::Instruction* phi) {
540 phi->ForEachInId([&firstId, &lastId](uint32_t* id) {
541 if (*id == firstId) *id = lastId;
542 });
543 });
544 });
Greg Fischer04fcc662016-11-10 10:11:50 -0700545}
546
Greg Fischerbba812f2017-05-04 20:55:53 -0600547bool InlinePass::HasMultipleReturns(ir::Function* func) {
548 bool seenReturn = false;
549 bool multipleReturns = false;
550 for (auto& blk : *func) {
551 auto terminal_ii = blk.cend();
552 --terminal_ii;
553 if (terminal_ii->opcode() == SpvOpReturn ||
554 terminal_ii->opcode() == SpvOpReturnValue) {
555 if (seenReturn) {
556 multipleReturns = true;
557 break;
558 }
559 seenReturn = true;
560 }
561 }
562 return multipleReturns;
563}
564
565uint32_t InlinePass::MergeBlockIdIfAny(const ir::BasicBlock& blk) {
566 auto merge_ii = blk.cend();
567 --merge_ii;
568 uint32_t mbid = 0;
569 if (merge_ii != blk.cbegin()) {
570 --merge_ii;
571 if (merge_ii->opcode() == SpvOpLoopMerge)
572 mbid = merge_ii->GetSingleWordOperand(kSpvLoopMergeMergeBlockId);
573 else if (merge_ii->opcode() == SpvOpSelectionMerge)
574 mbid = merge_ii->GetSingleWordOperand(kSpvSelectionMergeMergeBlockId);
575 }
576 return mbid;
577}
578
579void InlinePass::ComputeStructuredSuccessors(ir::Function* func) {
580 // If header, make merge block first successor.
581 for (auto& blk : *func) {
582 uint32_t mbid = MergeBlockIdIfAny(blk);
583 if (mbid != 0)
584 block2structured_succs_[&blk].push_back(id2block_[mbid]);
585 // add true successors
586 blk.ForEachSuccessorLabel([&blk, this](uint32_t sbid) {
587 block2structured_succs_[&blk].push_back(id2block_[sbid]);
588 });
589 }
590}
591
592InlinePass::GetBlocksFunction InlinePass::StructuredSuccessorsFunction() {
593 return [this](const ir::BasicBlock* block) {
594 return &(block2structured_succs_[block]);
595 };
596}
597
598bool InlinePass::HasNoReturnInLoop(ir::Function* func) {
599 // If control not structured, do not do loop/return analysis
600 // TODO: Analyze returns in non-structured control flow
601 if (!module_->HasCapability(SpvCapabilityShader))
602 return false;
603 // Compute structured block order. This order has the property
604 // that dominators are before all blocks they dominate and merge blocks
605 // are after all blocks that are in the control constructs of their header.
606 ComputeStructuredSuccessors(func);
607 auto ignore_block = [](cbb_ptr) {};
608 auto ignore_edge = [](cbb_ptr, cbb_ptr) {};
609 std::list<const ir::BasicBlock*> structuredOrder;
610 spvtools::CFA<ir::BasicBlock>::DepthFirstTraversal(
611 &*func->begin(), StructuredSuccessorsFunction(), ignore_block,
612 [&](cbb_ptr b) { structuredOrder.push_front(b); }, ignore_edge);
613 // Search for returns in loops. Only need to track outermost loop
614 bool return_in_loop = false;
615 uint32_t outerLoopMergeId = 0;
616 for (auto& blk : structuredOrder) {
617 // Exiting current outer loop
618 if (blk->id() == outerLoopMergeId)
619 outerLoopMergeId = 0;
620 // Return block
621 auto terminal_ii = blk->cend();
622 --terminal_ii;
623 if (terminal_ii->opcode() == SpvOpReturn ||
624 terminal_ii->opcode() == SpvOpReturnValue) {
625 if (outerLoopMergeId != 0) {
626 return_in_loop = true;
627 break;
628 }
629 }
630 else if (terminal_ii != blk->cbegin()) {
631 auto merge_ii = terminal_ii;
632 --merge_ii;
633 // Entering outermost loop
634 if (merge_ii->opcode() == SpvOpLoopMerge && outerLoopMergeId == 0)
635 outerLoopMergeId = merge_ii->GetSingleWordOperand(
636 kSpvLoopMergeMergeBlockId);
637 }
638 }
639 return !return_in_loop;
640}
641
642void InlinePass::AnalyzeReturns(ir::Function* func) {
643 // Look for multiple returns
644 if (!HasMultipleReturns(func)) {
645 no_return_in_loop_.insert(func->result_id());
646 return;
647 }
David Neto2a1014b2017-08-09 14:59:04 -0400648 multi_return_funcs_.insert(func->result_id());
Greg Fischerbba812f2017-05-04 20:55:53 -0600649 // If multiple returns, see if any are in a loop
650 if (HasNoReturnInLoop(func))
651 no_return_in_loop_.insert(func->result_id());
652}
653
654bool InlinePass::IsInlinableFunction(ir::Function* func) {
GregFa107d342017-04-25 13:57:20 -0600655 // We can only inline a function if it has blocks.
656 if (func->cbegin() == func->cend())
657 return false;
Greg Fischerbba812f2017-05-04 20:55:53 -0600658 // Do not inline functions with returns in loops. Currently early return
659 // functions are inlined by wrapping them in a one trip loop and implementing
660 // the returns as a branch to the loop's merge block. However, this can only
661 // done validly if the return was not in a loop in the original function.
662 // Also remember functions with multiple (early) returns.
663 AnalyzeReturns(func);
David Netoefff5fa2017-08-31 15:47:31 -0400664 return no_return_in_loop_.find(func->result_id()) !=
665 no_return_in_loop_.cend();
GregFa107d342017-04-25 13:57:20 -0600666}
667
GregFe28bd392017-08-01 17:20:13 -0600668void InlinePass::InitializeInline(ir::Module* module) {
Greg Fischer04fcc662016-11-10 10:11:50 -0700669 def_use_mgr_.reset(new analysis::DefUseManager(consumer(), module));
670
671 // Initialize next unused Id.
672 next_id_ = module->id_bound();
673
674 // Save module.
675 module_ = module;
676
Greg Fischerbba812f2017-05-04 20:55:53 -0600677 false_id_ = 0;
678
GregFe28bd392017-08-01 17:20:13 -0600679 // clear collections
Greg Fischer04fcc662016-11-10 10:11:50 -0700680 id2function_.clear();
681 id2block_.clear();
Greg Fischerbba812f2017-05-04 20:55:53 -0600682 block2structured_succs_.clear();
GregFa107d342017-04-25 13:57:20 -0600683 inlinable_.clear();
GregFe28bd392017-08-01 17:20:13 -0600684 no_return_in_loop_.clear();
David Neto2a1014b2017-08-09 14:59:04 -0400685 multi_return_funcs_.clear();
GregFe28bd392017-08-01 17:20:13 -0600686
Greg Fischer04fcc662016-11-10 10:11:50 -0700687 for (auto& fn : *module_) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600688 // Initialize function and block maps.
Greg Fischer04fcc662016-11-10 10:11:50 -0700689 id2function_[fn.result_id()] = &fn;
690 for (auto& blk : fn) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600691 id2block_[blk.id()] = &blk;
Greg Fischer04fcc662016-11-10 10:11:50 -0700692 }
Greg Fischerbba812f2017-05-04 20:55:53 -0600693 // Compute inlinability
GregFa107d342017-04-25 13:57:20 -0600694 if (IsInlinableFunction(&fn))
695 inlinable_.insert(fn.result_id());
Greg Fischer04fcc662016-11-10 10:11:50 -0700696 }
697};
698
Greg Fischer04fcc662016-11-10 10:11:50 -0700699
700InlinePass::InlinePass()
701 : module_(nullptr), def_use_mgr_(nullptr), next_id_(0) {}
702
Greg Fischer04fcc662016-11-10 10:11:50 -0700703} // namespace opt
704} // namespace spvtools