blob: 83d365cdf7e2eabb961725236c7a1117c5bbcffd [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 Fischer04fcc662016-11-10 10:11:50 -070030
31namespace spvtools {
32namespace opt {
33
34uint32_t InlinePass::FindPointerToType(uint32_t type_id,
35 SpvStorageClass storage_class) {
Diego Novillo1040a952017-10-25 13:26:25 -040036 ir::Module::inst_iterator type_itr = get_module()->types_values_begin();
37 for (; type_itr != get_module()->types_values_end(); ++type_itr) {
Greg Fischer04fcc662016-11-10 10:11:50 -070038 const ir::Instruction* type_inst = &*type_itr;
39 if (type_inst->opcode() == SpvOpTypePointer &&
40 type_inst->GetSingleWordOperand(kSpvTypePointerTypeId) == type_id &&
41 type_inst->GetSingleWordOperand(kSpvTypePointerStorageClass) ==
42 storage_class)
43 return type_inst->result_id();
44 }
45 return 0;
46}
47
48uint32_t InlinePass::AddPointerToType(uint32_t type_id,
49 SpvStorageClass storage_class) {
50 uint32_t resultId = TakeNextId();
51 std::unique_ptr<ir::Instruction> type_inst(new ir::Instruction(
52 SpvOpTypePointer, 0, resultId,
53 {{spv_operand_type_t::SPV_OPERAND_TYPE_STORAGE_CLASS,
54 {uint32_t(storage_class)}},
55 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {type_id}}}));
Steven Perron476cae62017-10-30 11:13:24 -040056 context()->AddType(std::move(type_inst));
Greg Fischer04fcc662016-11-10 10:11:50 -070057 return resultId;
58}
59
60void InlinePass::AddBranch(uint32_t label_id,
Greg Fischerbba812f2017-05-04 20:55:53 -060061 std::unique_ptr<ir::BasicBlock>* block_ptr) {
Greg Fischer04fcc662016-11-10 10:11:50 -070062 std::unique_ptr<ir::Instruction> newBranch(new ir::Instruction(
Greg Fischerbba812f2017-05-04 20:55:53 -060063 SpvOpBranch, 0, 0,
64 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {label_id}}}));
Greg Fischer04fcc662016-11-10 10:11:50 -070065 (*block_ptr)->AddInstruction(std::move(newBranch));
66}
67
Greg Fischerbba812f2017-05-04 20:55:53 -060068void InlinePass::AddBranchCond(uint32_t cond_id, uint32_t true_id,
69 uint32_t false_id, std::unique_ptr<ir::BasicBlock>* block_ptr) {
70 std::unique_ptr<ir::Instruction> newBranch(new ir::Instruction(
71 SpvOpBranchConditional, 0, 0,
72 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {cond_id}},
73 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {true_id}},
74 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {false_id}}}));
75 (*block_ptr)->AddInstruction(std::move(newBranch));
76}
77
78void InlinePass::AddLoopMerge(uint32_t merge_id, uint32_t continue_id,
79 std::unique_ptr<ir::BasicBlock>* block_ptr) {
80 std::unique_ptr<ir::Instruction> newLoopMerge(new ir::Instruction(
81 SpvOpLoopMerge, 0, 0,
82 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {merge_id}},
83 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {continue_id}},
84 {spv_operand_type_t::SPV_OPERAND_TYPE_LOOP_CONTROL, {0}}}));
85 (*block_ptr)->AddInstruction(std::move(newLoopMerge));
86}
87
Greg Fischer04fcc662016-11-10 10:11:50 -070088void InlinePass::AddStore(uint32_t ptr_id, uint32_t val_id,
89 std::unique_ptr<ir::BasicBlock>* block_ptr) {
90 std::unique_ptr<ir::Instruction> newStore(new ir::Instruction(
91 SpvOpStore, 0, 0, {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {ptr_id}},
92 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {val_id}}}));
93 (*block_ptr)->AddInstruction(std::move(newStore));
94}
95
96void InlinePass::AddLoad(uint32_t type_id, uint32_t resultId, uint32_t ptr_id,
97 std::unique_ptr<ir::BasicBlock>* block_ptr) {
98 std::unique_ptr<ir::Instruction> newLoad(new ir::Instruction(
99 SpvOpLoad, type_id, resultId,
100 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {ptr_id}}}));
101 (*block_ptr)->AddInstruction(std::move(newLoad));
102}
103
104std::unique_ptr<ir::Instruction> InlinePass::NewLabel(uint32_t label_id) {
105 std::unique_ptr<ir::Instruction> newLabel(
106 new ir::Instruction(SpvOpLabel, 0, label_id, {}));
107 return newLabel;
108}
109
Greg Fischerbba812f2017-05-04 20:55:53 -0600110uint32_t InlinePass::GetFalseId() {
111 if (false_id_ != 0)
112 return false_id_;
Diego Novillo1040a952017-10-25 13:26:25 -0400113 false_id_ = get_module()->GetGlobalValue(SpvOpConstantFalse);
Greg Fischerbba812f2017-05-04 20:55:53 -0600114 if (false_id_ != 0)
115 return false_id_;
Diego Novillo1040a952017-10-25 13:26:25 -0400116 uint32_t boolId = get_module()->GetGlobalValue(SpvOpTypeBool);
Greg Fischerbba812f2017-05-04 20:55:53 -0600117 if (boolId == 0) {
118 boolId = TakeNextId();
Diego Novillo1040a952017-10-25 13:26:25 -0400119 get_module()->AddGlobalValue(SpvOpTypeBool, boolId, 0);
Greg Fischerbba812f2017-05-04 20:55:53 -0600120 }
121 false_id_ = TakeNextId();
Diego Novillo1040a952017-10-25 13:26:25 -0400122 get_module()->AddGlobalValue(SpvOpConstantFalse, false_id_, boolId);
Greg Fischerbba812f2017-05-04 20:55:53 -0600123 return false_id_;
124}
125
Greg Fischer04fcc662016-11-10 10:11:50 -0700126void InlinePass::MapParams(
127 ir::Function* calleeFn,
Steven Perronbb7802b2017-10-13 14:25:21 -0400128 ir::BasicBlock::iterator call_inst_itr,
Greg Fischer04fcc662016-11-10 10:11:50 -0700129 std::unordered_map<uint32_t, uint32_t>* callee2caller) {
130 int param_idx = 0;
131 calleeFn->ForEachParam(
132 [&call_inst_itr, &param_idx, &callee2caller](const ir::Instruction* cpi) {
133 const uint32_t pid = cpi->result_id();
134 (*callee2caller)[pid] = call_inst_itr->GetSingleWordOperand(
135 kSpvFunctionCallArgumentId + param_idx);
Greg Fischerbba812f2017-05-04 20:55:53 -0600136 ++param_idx;
Greg Fischer04fcc662016-11-10 10:11:50 -0700137 });
138}
139
140void InlinePass::CloneAndMapLocals(
141 ir::Function* calleeFn,
142 std::vector<std::unique_ptr<ir::Instruction>>* new_vars,
143 std::unordered_map<uint32_t, uint32_t>* callee2caller) {
144 auto callee_block_itr = calleeFn->begin();
145 auto callee_var_itr = callee_block_itr->begin();
146 while (callee_var_itr->opcode() == SpvOp::SpvOpVariable) {
Steven Perronbb7802b2017-10-13 14:25:21 -0400147 std::unique_ptr<ir::Instruction> var_inst(callee_var_itr->Clone());
Greg Fischer04fcc662016-11-10 10:11:50 -0700148 uint32_t newId = TakeNextId();
149 var_inst->SetResultId(newId);
150 (*callee2caller)[callee_var_itr->result_id()] = newId;
151 new_vars->push_back(std::move(var_inst));
Greg Fischerbba812f2017-05-04 20:55:53 -0600152 ++callee_var_itr;
Greg Fischer04fcc662016-11-10 10:11:50 -0700153 }
154}
155
156uint32_t InlinePass::CreateReturnVar(
157 ir::Function* calleeFn,
158 std::vector<std::unique_ptr<ir::Instruction>>* new_vars) {
159 uint32_t returnVarId = 0;
160 const uint32_t calleeTypeId = calleeFn->type_id();
161 const ir::Instruction* calleeType =
Diego Novillo1040a952017-10-25 13:26:25 -0400162 get_def_use_mgr()->id_to_defs().find(calleeTypeId)->second;
Greg Fischer04fcc662016-11-10 10:11:50 -0700163 if (calleeType->opcode() != SpvOpTypeVoid) {
164 // Find or create ptr to callee return type.
165 uint32_t returnVarTypeId =
166 FindPointerToType(calleeTypeId, SpvStorageClassFunction);
167 if (returnVarTypeId == 0)
168 returnVarTypeId = AddPointerToType(calleeTypeId, SpvStorageClassFunction);
169 // Add return var to new function scope variables.
170 returnVarId = TakeNextId();
171 std::unique_ptr<ir::Instruction> var_inst(new ir::Instruction(
172 SpvOpVariable, returnVarTypeId, returnVarId,
173 {{spv_operand_type_t::SPV_OPERAND_TYPE_STORAGE_CLASS,
174 {SpvStorageClassFunction}}}));
175 new_vars->push_back(std::move(var_inst));
176 }
177 return returnVarId;
178}
179
180bool InlinePass::IsSameBlockOp(const ir::Instruction* inst) const {
181 return inst->opcode() == SpvOpSampledImage || inst->opcode() == SpvOpImage;
182}
183
184void InlinePass::CloneSameBlockOps(
185 std::unique_ptr<ir::Instruction>* inst,
186 std::unordered_map<uint32_t, uint32_t>* postCallSB,
187 std::unordered_map<uint32_t, ir::Instruction*>* preCallSB,
188 std::unique_ptr<ir::BasicBlock>* block_ptr) {
189 (*inst)
190 ->ForEachInId([&postCallSB, &preCallSB, &block_ptr, this](uint32_t* iid) {
191 const auto mapItr = (*postCallSB).find(*iid);
192 if (mapItr == (*postCallSB).end()) {
193 const auto mapItr2 = (*preCallSB).find(*iid);
194 if (mapItr2 != (*preCallSB).end()) {
195 // Clone pre-call same-block ops, map result id.
196 const ir::Instruction* inInst = mapItr2->second;
Steven Perronbb7802b2017-10-13 14:25:21 -0400197 std::unique_ptr<ir::Instruction> sb_inst(inInst->Clone());
Greg Fischer04fcc662016-11-10 10:11:50 -0700198 CloneSameBlockOps(&sb_inst, postCallSB, preCallSB, block_ptr);
199 const uint32_t rid = sb_inst->result_id();
200 const uint32_t nid = this->TakeNextId();
201 sb_inst->SetResultId(nid);
202 (*postCallSB)[rid] = nid;
203 *iid = nid;
204 (*block_ptr)->AddInstruction(std::move(sb_inst));
205 }
206 } else {
207 // Reset same-block op operand.
208 *iid = mapItr->second;
209 }
210 });
211}
212
213void InlinePass::GenInlineCode(
214 std::vector<std::unique_ptr<ir::BasicBlock>>* new_blocks,
215 std::vector<std::unique_ptr<ir::Instruction>>* new_vars,
Steven Perronbb7802b2017-10-13 14:25:21 -0400216 ir::BasicBlock::iterator call_inst_itr,
Greg Fischer04fcc662016-11-10 10:11:50 -0700217 ir::UptrVectorIterator<ir::BasicBlock> call_block_itr) {
218 // Map from all ids in the callee to their equivalent id in the caller
219 // as callee instructions are copied into caller.
220 std::unordered_map<uint32_t, uint32_t> callee2caller;
221 // Pre-call same-block insts
222 std::unordered_map<uint32_t, ir::Instruction*> preCallSB;
223 // Post-call same-block op ids
224 std::unordered_map<uint32_t, uint32_t> postCallSB;
225
226 ir::Function* calleeFn = id2function_[call_inst_itr->GetSingleWordOperand(
227 kSpvFunctionCallFunctionId)];
228
David Neto2a1014b2017-08-09 14:59:04 -0400229 // Check for multiple returns in the callee.
230 auto fi = multi_return_funcs_.find(calleeFn->result_id());
231 const bool multiReturn = fi != multi_return_funcs_.end();
Greg Fischerbba812f2017-05-04 20:55:53 -0600232
Greg Fischer04fcc662016-11-10 10:11:50 -0700233 // Map parameters to actual arguments.
234 MapParams(calleeFn, call_inst_itr, &callee2caller);
235
236 // Define caller local variables for all callee variables and create map to
237 // them.
238 CloneAndMapLocals(calleeFn, new_vars, &callee2caller);
239
240 // Create return var if needed.
241 uint32_t returnVarId = CreateReturnVar(calleeFn, new_vars);
242
GregFa699d1a2017-08-29 18:35:05 -0600243 // Create set of callee result ids. Used to detect forward references
244 std::unordered_set<uint32_t> callee_result_ids;
245 calleeFn->ForEachInst([&callee_result_ids](
246 const ir::Instruction* cpi) {
247 const uint32_t rid = cpi->result_id();
248 if (rid != 0)
249 callee_result_ids.insert(rid);
250 });
251
David Netoefff5fa2017-08-31 15:47:31 -0400252 // If the caller is in a single-block loop, and the callee has multiple
253 // blocks, then the normal inlining logic will place the OpLoopMerge in
254 // the last of several blocks in the loop. Instead, it should be placed
255 // at the end of the first block. First determine if the caller is in a
256 // single block loop. We'll wait to move the OpLoopMerge until the end
257 // of the regular inlining logic, and only if necessary.
258 bool caller_is_single_block_loop = false;
David Neto25ddfec2017-09-02 19:01:03 -0400259 bool caller_is_loop_header = false;
David Netoefff5fa2017-08-31 15:47:31 -0400260 if (auto* loop_merge = call_block_itr->GetLoopMergeInst()) {
David Neto25ddfec2017-09-02 19:01:03 -0400261 caller_is_loop_header = true;
David Netoefff5fa2017-08-31 15:47:31 -0400262 caller_is_single_block_loop =
263 call_block_itr->id() ==
264 loop_merge->GetSingleWordInOperand(kSpvLoopMergeContinueTargetIdInIdx);
265 }
266
267 bool callee_begins_with_structured_header =
268 (*(calleeFn->begin())).GetMergeInst() != nullptr;
269
Greg Fischer04fcc662016-11-10 10:11:50 -0700270 // Clone and map callee code. Copy caller block code to beginning of
271 // first block and end of last block.
272 bool prevInstWasReturn = false;
Greg Fischerbba812f2017-05-04 20:55:53 -0600273 uint32_t singleTripLoopHeaderId = 0;
274 uint32_t singleTripLoopContinueId = 0;
Greg Fischer04fcc662016-11-10 10:11:50 -0700275 uint32_t returnLabelId = 0;
276 bool multiBlocks = false;
277 const uint32_t calleeTypeId = calleeFn->type_id();
David Neto2a1014b2017-08-09 14:59:04 -0400278 // new_blk_ptr is a new basic block in the caller. New instructions are
279 // written to it. It is created when we encounter the OpLabel
David Netoefff5fa2017-08-31 15:47:31 -0400280 // of the first callee block. It is appended to new_blocks only when
281 // it is complete.
Greg Fischer04fcc662016-11-10 10:11:50 -0700282 std::unique_ptr<ir::BasicBlock> new_blk_ptr;
283 calleeFn->ForEachInst([&new_blocks, &callee2caller, &call_block_itr,
284 &call_inst_itr, &new_blk_ptr, &prevInstWasReturn,
David Neto25ddfec2017-09-02 19:01:03 -0400285 &returnLabelId, &returnVarId, caller_is_loop_header,
David Netoefff5fa2017-08-31 15:47:31 -0400286 callee_begins_with_structured_header, &calleeTypeId,
David Neto2a1014b2017-08-09 14:59:04 -0400287 &multiBlocks, &postCallSB, &preCallSB, multiReturn,
Greg Fischerbba812f2017-05-04 20:55:53 -0600288 &singleTripLoopHeaderId, &singleTripLoopContinueId,
David Netoefff5fa2017-08-31 15:47:31 -0400289 &callee_result_ids, this](const ir::Instruction* cpi) {
Greg Fischer04fcc662016-11-10 10:11:50 -0700290 switch (cpi->opcode()) {
291 case SpvOpFunction:
292 case SpvOpFunctionParameter:
293 case SpvOpVariable:
294 // Already processed
295 break;
296 case SpvOpLabel: {
297 // If previous instruction was early return, insert branch
298 // instruction to return block.
299 if (prevInstWasReturn) {
300 if (returnLabelId == 0) returnLabelId = this->TakeNextId();
301 AddBranch(returnLabelId, &new_blk_ptr);
302 prevInstWasReturn = false;
303 }
304 // Finish current block (if it exists) and get label for next block.
305 uint32_t labelId;
306 bool firstBlock = false;
307 if (new_blk_ptr != nullptr) {
308 new_blocks->push_back(std::move(new_blk_ptr));
309 // If result id is already mapped, use it, otherwise get a new
310 // one.
311 const uint32_t rid = cpi->result_id();
312 const auto mapItr = callee2caller.find(rid);
313 labelId = (mapItr != callee2caller.end()) ? mapItr->second
314 : this->TakeNextId();
315 } else {
316 // First block needs to use label of original block
317 // but map callee label in case of phi reference.
Greg Fischerbba812f2017-05-04 20:55:53 -0600318 labelId = call_block_itr->id();
Greg Fischer04fcc662016-11-10 10:11:50 -0700319 callee2caller[cpi->result_id()] = labelId;
320 firstBlock = true;
321 }
322 // Create first/next block.
323 new_blk_ptr.reset(new ir::BasicBlock(NewLabel(labelId)));
324 if (firstBlock) {
325 // Copy contents of original caller block up to call instruction.
326 for (auto cii = call_block_itr->begin(); cii != call_inst_itr;
Greg Fischerbba812f2017-05-04 20:55:53 -0600327 ++cii) {
Steven Perronbb7802b2017-10-13 14:25:21 -0400328 std::unique_ptr<ir::Instruction> cp_inst(cii->Clone());
Greg Fischer04fcc662016-11-10 10:11:50 -0700329 // Remember same-block ops for possible regeneration.
330 if (IsSameBlockOp(&*cp_inst)) {
331 auto* sb_inst_ptr = cp_inst.get();
332 preCallSB[cp_inst->result_id()] = sb_inst_ptr;
333 }
334 new_blk_ptr->AddInstruction(std::move(cp_inst));
335 }
David Neto25ddfec2017-09-02 19:01:03 -0400336 if (caller_is_loop_header &&
David Netoefff5fa2017-08-31 15:47:31 -0400337 callee_begins_with_structured_header) {
338 // We can't place both the caller's merge instruction and another
339 // merge instruction in the same block. So split the calling block.
340 // Insert an unconditional branch to a new guard block. Later,
341 // once we know the ID of the last block, we will move the caller's
342 // OpLoopMerge from the last generated block into the first block.
343 // We also wait to avoid invalidating various iterators.
344 const auto guard_block_id = this->TakeNextId();
345 AddBranch(guard_block_id, &new_blk_ptr);
346 new_blocks->push_back(std::move(new_blk_ptr));
347 // Start the next block.
348 new_blk_ptr.reset(new ir::BasicBlock(NewLabel(guard_block_id)));
349 // Reset the mapping of the callee's entry block to point to
350 // the guard block. Do this so we can fix up phis later on to
351 // satisfy dominance.
352 callee2caller[cpi->result_id()] = guard_block_id;
353 }
354 // If callee has multiple returns, insert a header block for
David Neto2a1014b2017-08-09 14:59:04 -0400355 // single-trip loop that will encompass callee code. Start postheader
Greg Fischerbba812f2017-05-04 20:55:53 -0600356 // block.
David Netoefff5fa2017-08-31 15:47:31 -0400357 //
358 // Note: Consider the following combination:
359 // - the caller is a single block loop
360 // - the callee does not begin with a structure header
361 // - the callee has multiple returns.
362 // We still need to split the caller block and insert a guard block.
363 // But we only need to do it once. We haven't done it yet, but the
364 // single-trip loop header will serve the same purpose.
David Neto2a1014b2017-08-09 14:59:04 -0400365 if (multiReturn) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600366 singleTripLoopHeaderId = this->TakeNextId();
367 AddBranch(singleTripLoopHeaderId, &new_blk_ptr);
368 new_blocks->push_back(std::move(new_blk_ptr));
369 new_blk_ptr.reset(new ir::BasicBlock(NewLabel(
370 singleTripLoopHeaderId)));
371 returnLabelId = this->TakeNextId();
372 singleTripLoopContinueId = this->TakeNextId();
373 AddLoopMerge(returnLabelId, singleTripLoopContinueId, &new_blk_ptr);
374 uint32_t postHeaderId = this->TakeNextId();
375 AddBranch(postHeaderId, &new_blk_ptr);
376 new_blocks->push_back(std::move(new_blk_ptr));
377 new_blk_ptr.reset(new ir::BasicBlock(NewLabel(postHeaderId)));
378 multiBlocks = true;
David Neto860c4192017-08-31 17:33:44 -0400379 // Reset the mapping of the callee's entry block to point to
380 // the post-header block. Do this so we can fix up phis later
381 // on to satisfy dominance.
382 callee2caller[cpi->result_id()] = postHeaderId;
Greg Fischerbba812f2017-05-04 20:55:53 -0600383 }
Greg Fischer04fcc662016-11-10 10:11:50 -0700384 } else {
385 multiBlocks = true;
386 }
387 } break;
388 case SpvOpReturnValue: {
389 // Store return value to return variable.
390 assert(returnVarId != 0);
391 uint32_t valId = cpi->GetInOperand(kSpvReturnValueId).words[0];
392 const auto mapItr = callee2caller.find(valId);
393 if (mapItr != callee2caller.end()) {
394 valId = mapItr->second;
395 }
396 AddStore(returnVarId, valId, &new_blk_ptr);
397
398 // Remember we saw a return; if followed by a label, will need to
399 // insert branch.
400 prevInstWasReturn = true;
401 } break;
402 case SpvOpReturn: {
403 // Remember we saw a return; if followed by a label, will need to
404 // insert branch.
405 prevInstWasReturn = true;
406 } break;
407 case SpvOpFunctionEnd: {
David Neto2a1014b2017-08-09 14:59:04 -0400408 // If there was an early return, we generated a return label id
409 // for it. Now we have to generate the return block with that Id.
Greg Fischer04fcc662016-11-10 10:11:50 -0700410 if (returnLabelId != 0) {
David Neto2a1014b2017-08-09 14:59:04 -0400411 // If previous instruction was return, insert branch instruction
412 // to return block.
Greg Fischer04fcc662016-11-10 10:11:50 -0700413 if (prevInstWasReturn) AddBranch(returnLabelId, &new_blk_ptr);
David Neto2a1014b2017-08-09 14:59:04 -0400414 if (multiReturn) {
415 // If we generated a loop header to for the single-trip loop
416 // to accommodate multiple returns, insert the continue
417 // target block now, with a false branch back to the loop header.
418 new_blocks->push_back(std::move(new_blk_ptr));
419 new_blk_ptr.reset(
420 new ir::BasicBlock(NewLabel(singleTripLoopContinueId)));
421 AddBranchCond(GetFalseId(), singleTripLoopHeaderId, returnLabelId,
422 &new_blk_ptr);
423 }
424 // Generate the return block.
Greg Fischerbba812f2017-05-04 20:55:53 -0600425 new_blocks->push_back(std::move(new_blk_ptr));
Greg Fischer04fcc662016-11-10 10:11:50 -0700426 new_blk_ptr.reset(new ir::BasicBlock(NewLabel(returnLabelId)));
427 multiBlocks = true;
428 }
429 // Load return value into result id of call, if it exists.
430 if (returnVarId != 0) {
431 const uint32_t resId = call_inst_itr->result_id();
432 assert(resId != 0);
433 AddLoad(calleeTypeId, resId, returnVarId, &new_blk_ptr);
434 }
435 // Copy remaining instructions from caller block.
436 auto cii = call_inst_itr;
Greg Fischerbba812f2017-05-04 20:55:53 -0600437 for (++cii; cii != call_block_itr->end(); ++cii) {
Steven Perronbb7802b2017-10-13 14:25:21 -0400438 std::unique_ptr<ir::Instruction> cp_inst(cii->Clone());
Greg Fischer04fcc662016-11-10 10:11:50 -0700439 // If multiple blocks generated, regenerate any same-block
440 // instruction that has not been seen in this last block.
441 if (multiBlocks) {
442 CloneSameBlockOps(&cp_inst, &postCallSB, &preCallSB, &new_blk_ptr);
443 // Remember same-block ops in this block.
444 if (IsSameBlockOp(&*cp_inst)) {
445 const uint32_t rid = cp_inst->result_id();
446 postCallSB[rid] = rid;
447 }
448 }
449 new_blk_ptr->AddInstruction(std::move(cp_inst));
450 }
451 // Finalize inline code.
452 new_blocks->push_back(std::move(new_blk_ptr));
453 } break;
454 default: {
455 // Copy callee instruction and remap all input Ids.
Steven Perronbb7802b2017-10-13 14:25:21 -0400456 std::unique_ptr<ir::Instruction> cp_inst(cpi->Clone());
David Netoefff5fa2017-08-31 15:47:31 -0400457 cp_inst->ForEachInId([&callee2caller, &callee_result_ids,
458 this](uint32_t* iid) {
Greg Fischer04fcc662016-11-10 10:11:50 -0700459 const auto mapItr = callee2caller.find(*iid);
460 if (mapItr != callee2caller.end()) {
461 *iid = mapItr->second;
GregFa699d1a2017-08-29 18:35:05 -0600462 } else if (callee_result_ids.find(*iid) != callee_result_ids.end()) {
463 // Forward reference. Allocate a new id, map it,
464 // use it and check for it when remapping result ids
465 const uint32_t nid = this->TakeNextId();
466 callee2caller[*iid] = nid;
467 *iid = nid;
Greg Fischer04fcc662016-11-10 10:11:50 -0700468 }
469 });
GregFa699d1a2017-08-29 18:35:05 -0600470 // If result id is non-zero, remap it. If already mapped, use mapped
471 // value, else use next id.
Greg Fischer04fcc662016-11-10 10:11:50 -0700472 const uint32_t rid = cp_inst->result_id();
473 if (rid != 0) {
GregFa699d1a2017-08-29 18:35:05 -0600474 const auto mapItr = callee2caller.find(rid);
475 uint32_t nid;
476 if (mapItr != callee2caller.end()) {
477 nid = mapItr->second;
478 }
479 else {
480 nid = this->TakeNextId();
481 callee2caller[rid] = nid;
482 }
Greg Fischer04fcc662016-11-10 10:11:50 -0700483 cp_inst->SetResultId(nid);
484 }
485 new_blk_ptr->AddInstruction(std::move(cp_inst));
486 } break;
487 }
488 });
David Netoefff5fa2017-08-31 15:47:31 -0400489
David Neto25ddfec2017-09-02 19:01:03 -0400490 if (caller_is_loop_header && (new_blocks->size() > 1)) {
David Netoefff5fa2017-08-31 15:47:31 -0400491 // Move the OpLoopMerge from the last block back to the first, where
David Neto25ddfec2017-09-02 19:01:03 -0400492 // it belongs.
David Netoefff5fa2017-08-31 15:47:31 -0400493 auto& first = new_blocks->front();
494 auto& last = new_blocks->back();
495 assert(first != last);
496
497 // Insert a modified copy of the loop merge into the first block.
498 auto loop_merge_itr = last->tail();
499 --loop_merge_itr;
500 assert(loop_merge_itr->opcode() == SpvOpLoopMerge);
Steven Perronbb7802b2017-10-13 14:25:21 -0400501 std::unique_ptr<ir::Instruction> cp_inst(loop_merge_itr->Clone());
David Neto25ddfec2017-09-02 19:01:03 -0400502 if (caller_is_single_block_loop) {
503 // Also, update its continue target to point to the last block.
504 cp_inst->SetInOperand(kSpvLoopMergeContinueTargetIdInIdx, {last->id()});
505 }
David Netoefff5fa2017-08-31 15:47:31 -0400506 first->tail().InsertBefore(std::move(cp_inst));
507
508 // Remove the loop merge from the last block.
Steven Perronbb7802b2017-10-13 14:25:21 -0400509 loop_merge_itr->RemoveFromList();
510 delete &*loop_merge_itr;
David Netoefff5fa2017-08-31 15:47:31 -0400511 }
512
Greg Fischer04fcc662016-11-10 10:11:50 -0700513 // Update block map given replacement blocks.
514 for (auto& blk : *new_blocks) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600515 id2block_[blk->id()] = &*blk;
Greg Fischer04fcc662016-11-10 10:11:50 -0700516 }
517}
518
David Netoceb1d4f2017-03-31 10:36:58 -0400519bool InlinePass::IsInlinableFunctionCall(const ir::Instruction* inst) {
520 if (inst->opcode() != SpvOp::SpvOpFunctionCall) return false;
GregFa107d342017-04-25 13:57:20 -0600521 const uint32_t calleeFnId =
522 inst->GetSingleWordOperand(kSpvFunctionCallFunctionId);
523 const auto ci = inlinable_.find(calleeFnId);
524 return ci != inlinable_.cend();
David Netoceb1d4f2017-03-31 10:36:58 -0400525}
526
GregFe28bd392017-08-01 17:20:13 -0600527void InlinePass::UpdateSucceedingPhis(
528 std::vector<std::unique_ptr<ir::BasicBlock>>& new_blocks) {
529 const auto firstBlk = new_blocks.begin();
530 const auto lastBlk = new_blocks.end() - 1;
531 const uint32_t firstId = (*firstBlk)->id();
532 const uint32_t lastId = (*lastBlk)->id();
533 (*lastBlk)->ForEachSuccessorLabel(
534 [&firstId, &lastId, this](uint32_t succ) {
535 ir::BasicBlock* sbp = this->id2block_[succ];
536 sbp->ForEachPhiInst([&firstId, &lastId](ir::Instruction* phi) {
537 phi->ForEachInId([&firstId, &lastId](uint32_t* id) {
538 if (*id == firstId) *id = lastId;
539 });
540 });
541 });
Greg Fischer04fcc662016-11-10 10:11:50 -0700542}
543
Greg Fischerbba812f2017-05-04 20:55:53 -0600544bool InlinePass::HasMultipleReturns(ir::Function* func) {
545 bool seenReturn = false;
546 bool multipleReturns = false;
547 for (auto& blk : *func) {
548 auto terminal_ii = blk.cend();
549 --terminal_ii;
550 if (terminal_ii->opcode() == SpvOpReturn ||
551 terminal_ii->opcode() == SpvOpReturnValue) {
552 if (seenReturn) {
553 multipleReturns = true;
554 break;
555 }
556 seenReturn = true;
557 }
558 }
559 return multipleReturns;
560}
561
Greg Fischerbba812f2017-05-04 20:55:53 -0600562
563void InlinePass::ComputeStructuredSuccessors(ir::Function* func) {
564 // If header, make merge block first successor.
565 for (auto& blk : *func) {
Diego Novillofef669f2017-10-30 17:42:26 -0400566 uint32_t mbid = blk.MergeBlockIdIfAny();
567 if (mbid != 0) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600568 block2structured_succs_[&blk].push_back(id2block_[mbid]);
Diego Novillofef669f2017-10-30 17:42:26 -0400569 }
570
571 // Add true successors.
Greg Fischerbba812f2017-05-04 20:55:53 -0600572 blk.ForEachSuccessorLabel([&blk, this](uint32_t sbid) {
573 block2structured_succs_[&blk].push_back(id2block_[sbid]);
574 });
575 }
576}
Diego Novillofef669f2017-10-30 17:42:26 -0400577
Greg Fischerbba812f2017-05-04 20:55:53 -0600578InlinePass::GetBlocksFunction InlinePass::StructuredSuccessorsFunction() {
579 return [this](const ir::BasicBlock* block) {
580 return &(block2structured_succs_[block]);
581 };
582}
583
584bool InlinePass::HasNoReturnInLoop(ir::Function* func) {
585 // If control not structured, do not do loop/return analysis
586 // TODO: Analyze returns in non-structured control flow
Diego Novillo1040a952017-10-25 13:26:25 -0400587 if (!get_module()->HasCapability(SpvCapabilityShader))
Greg Fischerbba812f2017-05-04 20:55:53 -0600588 return false;
589 // Compute structured block order. This order has the property
590 // that dominators are before all blocks they dominate and merge blocks
591 // are after all blocks that are in the control constructs of their header.
592 ComputeStructuredSuccessors(func);
593 auto ignore_block = [](cbb_ptr) {};
594 auto ignore_edge = [](cbb_ptr, cbb_ptr) {};
595 std::list<const ir::BasicBlock*> structuredOrder;
596 spvtools::CFA<ir::BasicBlock>::DepthFirstTraversal(
597 &*func->begin(), StructuredSuccessorsFunction(), ignore_block,
598 [&](cbb_ptr b) { structuredOrder.push_front(b); }, ignore_edge);
599 // Search for returns in loops. Only need to track outermost loop
600 bool return_in_loop = false;
601 uint32_t outerLoopMergeId = 0;
602 for (auto& blk : structuredOrder) {
603 // Exiting current outer loop
604 if (blk->id() == outerLoopMergeId)
605 outerLoopMergeId = 0;
606 // Return block
607 auto terminal_ii = blk->cend();
608 --terminal_ii;
609 if (terminal_ii->opcode() == SpvOpReturn ||
610 terminal_ii->opcode() == SpvOpReturnValue) {
611 if (outerLoopMergeId != 0) {
612 return_in_loop = true;
613 break;
614 }
615 }
616 else if (terminal_ii != blk->cbegin()) {
617 auto merge_ii = terminal_ii;
618 --merge_ii;
619 // Entering outermost loop
620 if (merge_ii->opcode() == SpvOpLoopMerge && outerLoopMergeId == 0)
621 outerLoopMergeId = merge_ii->GetSingleWordOperand(
622 kSpvLoopMergeMergeBlockId);
623 }
624 }
625 return !return_in_loop;
626}
627
628void InlinePass::AnalyzeReturns(ir::Function* func) {
629 // Look for multiple returns
630 if (!HasMultipleReturns(func)) {
631 no_return_in_loop_.insert(func->result_id());
632 return;
633 }
David Neto2a1014b2017-08-09 14:59:04 -0400634 multi_return_funcs_.insert(func->result_id());
Greg Fischerbba812f2017-05-04 20:55:53 -0600635 // If multiple returns, see if any are in a loop
636 if (HasNoReturnInLoop(func))
637 no_return_in_loop_.insert(func->result_id());
638}
639
640bool InlinePass::IsInlinableFunction(ir::Function* func) {
GregFa107d342017-04-25 13:57:20 -0600641 // We can only inline a function if it has blocks.
642 if (func->cbegin() == func->cend())
643 return false;
Greg Fischerbba812f2017-05-04 20:55:53 -0600644 // Do not inline functions with returns in loops. Currently early return
645 // functions are inlined by wrapping them in a one trip loop and implementing
646 // the returns as a branch to the loop's merge block. However, this can only
647 // done validly if the return was not in a loop in the original function.
648 // Also remember functions with multiple (early) returns.
649 AnalyzeReturns(func);
David Netoefff5fa2017-08-31 15:47:31 -0400650 return no_return_in_loop_.find(func->result_id()) !=
651 no_return_in_loop_.cend();
GregFa107d342017-04-25 13:57:20 -0600652}
653
Steven Perron476cae62017-10-30 11:13:24 -0400654void InlinePass::InitializeInline(ir::IRContext* c) {
655 InitializeProcessing(c);
Greg Fischer04fcc662016-11-10 10:11:50 -0700656
Greg Fischerbba812f2017-05-04 20:55:53 -0600657 false_id_ = 0;
658
GregFe28bd392017-08-01 17:20:13 -0600659 // clear collections
Greg Fischer04fcc662016-11-10 10:11:50 -0700660 id2function_.clear();
661 id2block_.clear();
Greg Fischerbba812f2017-05-04 20:55:53 -0600662 block2structured_succs_.clear();
GregFa107d342017-04-25 13:57:20 -0600663 inlinable_.clear();
GregFe28bd392017-08-01 17:20:13 -0600664 no_return_in_loop_.clear();
David Neto2a1014b2017-08-09 14:59:04 -0400665 multi_return_funcs_.clear();
GregFe28bd392017-08-01 17:20:13 -0600666
Diego Novillo1040a952017-10-25 13:26:25 -0400667 for (auto& fn : *get_module()) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600668 // Initialize function and block maps.
Greg Fischer04fcc662016-11-10 10:11:50 -0700669 id2function_[fn.result_id()] = &fn;
670 for (auto& blk : fn) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600671 id2block_[blk.id()] = &blk;
Greg Fischer04fcc662016-11-10 10:11:50 -0700672 }
Greg Fischerbba812f2017-05-04 20:55:53 -0600673 // Compute inlinability
GregFa107d342017-04-25 13:57:20 -0600674 if (IsInlinableFunction(&fn))
675 inlinable_.insert(fn.result_id());
Greg Fischer04fcc662016-11-10 10:11:50 -0700676 }
677};
678
Diego Novillo1040a952017-10-25 13:26:25 -0400679InlinePass::InlinePass() {}
Greg Fischer04fcc662016-11-10 10:11:50 -0700680
Greg Fischer04fcc662016-11-10 10:11:50 -0700681} // namespace opt
682} // namespace spvtools