blob: a0506424278263f0054b4fe1755ed3f5674fab23 [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(
Alan Bakera7717132017-11-14 14:11:50 -050052 context(), SpvOpTypePointer, 0, resultId,
Greg Fischer04fcc662016-11-10 10:11:50 -070053 {{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,
Diego Novillod2938e42017-11-08 12:40:02 -050061 std::unique_ptr<ir::BasicBlock>* block_ptr) {
Greg Fischer04fcc662016-11-10 10:11:50 -070062 std::unique_ptr<ir::Instruction> newBranch(new ir::Instruction(
Alan Bakera7717132017-11-14 14:11:50 -050063 context(), SpvOpBranch, 0, 0,
Diego Novillod2938e42017-11-08 12:40:02 -050064 {{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,
Diego Novillod2938e42017-11-08 12:40:02 -050069 uint32_t false_id,
70 std::unique_ptr<ir::BasicBlock>* block_ptr) {
Greg Fischerbba812f2017-05-04 20:55:53 -060071 std::unique_ptr<ir::Instruction> newBranch(new ir::Instruction(
Alan Bakera7717132017-11-14 14:11:50 -050072 context(), SpvOpBranchConditional, 0, 0,
Diego Novillod2938e42017-11-08 12:40:02 -050073 {{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}}}));
Greg Fischerbba812f2017-05-04 20:55:53 -060076 (*block_ptr)->AddInstruction(std::move(newBranch));
77}
78
79void InlinePass::AddLoopMerge(uint32_t merge_id, uint32_t continue_id,
Diego Novillod2938e42017-11-08 12:40:02 -050080 std::unique_ptr<ir::BasicBlock>* block_ptr) {
Greg Fischerbba812f2017-05-04 20:55:53 -060081 std::unique_ptr<ir::Instruction> newLoopMerge(new ir::Instruction(
Alan Bakera7717132017-11-14 14:11:50 -050082 context(), SpvOpLoopMerge, 0, 0,
Greg Fischerbba812f2017-05-04 20:55:53 -060083 {{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(
Alan Bakera7717132017-11-14 14:11:50 -050092 context(), SpvOpStore, 0, 0,
Diego Novillod2938e42017-11-08 12:40:02 -050093 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {ptr_id}},
94 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {val_id}}}));
Greg Fischer04fcc662016-11-10 10:11:50 -070095 (*block_ptr)->AddInstruction(std::move(newStore));
96}
97
98void InlinePass::AddLoad(uint32_t type_id, uint32_t resultId, uint32_t ptr_id,
99 std::unique_ptr<ir::BasicBlock>* block_ptr) {
100 std::unique_ptr<ir::Instruction> newLoad(new ir::Instruction(
Alan Bakera7717132017-11-14 14:11:50 -0500101 context(), SpvOpLoad, type_id, resultId,
Greg Fischer04fcc662016-11-10 10:11:50 -0700102 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {ptr_id}}}));
103 (*block_ptr)->AddInstruction(std::move(newLoad));
104}
105
106std::unique_ptr<ir::Instruction> InlinePass::NewLabel(uint32_t label_id) {
107 std::unique_ptr<ir::Instruction> newLabel(
Alan Bakera7717132017-11-14 14:11:50 -0500108 new ir::Instruction(context(), SpvOpLabel, 0, label_id, {}));
Greg Fischer04fcc662016-11-10 10:11:50 -0700109 return newLabel;
110}
111
Greg Fischerbba812f2017-05-04 20:55:53 -0600112uint32_t InlinePass::GetFalseId() {
Diego Novillod2938e42017-11-08 12:40:02 -0500113 if (false_id_ != 0) return false_id_;
Diego Novillo1040a952017-10-25 13:26:25 -0400114 false_id_ = get_module()->GetGlobalValue(SpvOpConstantFalse);
Diego Novillod2938e42017-11-08 12:40:02 -0500115 if (false_id_ != 0) 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(
Diego Novillod2938e42017-11-08 12:40:02 -0500127 ir::Function* calleeFn, ir::BasicBlock::iterator call_inst_itr,
Greg Fischer04fcc662016-11-10 10:11:50 -0700128 std::unordered_map<uint32_t, uint32_t>* callee2caller) {
129 int param_idx = 0;
130 calleeFn->ForEachParam(
131 [&call_inst_itr, &param_idx, &callee2caller](const ir::Instruction* cpi) {
132 const uint32_t pid = cpi->result_id();
133 (*callee2caller)[pid] = call_inst_itr->GetSingleWordOperand(
134 kSpvFunctionCallArgumentId + param_idx);
Greg Fischerbba812f2017-05-04 20:55:53 -0600135 ++param_idx;
Greg Fischer04fcc662016-11-10 10:11:50 -0700136 });
137}
138
139void InlinePass::CloneAndMapLocals(
140 ir::Function* calleeFn,
141 std::vector<std::unique_ptr<ir::Instruction>>* new_vars,
142 std::unordered_map<uint32_t, uint32_t>* callee2caller) {
143 auto callee_block_itr = calleeFn->begin();
144 auto callee_var_itr = callee_block_itr->begin();
145 while (callee_var_itr->opcode() == SpvOp::SpvOpVariable) {
Alan Bakera7717132017-11-14 14:11:50 -0500146 std::unique_ptr<ir::Instruction> var_inst(
147 callee_var_itr->Clone(callee_var_itr->context()));
Greg Fischer04fcc662016-11-10 10:11:50 -0700148 uint32_t newId = TakeNextId();
Diego Novillo83228132017-11-27 10:16:41 -0500149 get_decoration_mgr()->CloneDecorations(callee_var_itr->result_id(), newId,
150 update_def_use_mgr_);
Greg Fischer04fcc662016-11-10 10:11:50 -0700151 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 =
Diego Novillo1040a952017-10-25 13:26:25 -0400164 get_def_use_mgr()->id_to_defs().find(calleeTypeId)->second;
Greg Fischer04fcc662016-11-10 10:11:50 -0700165 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(
Alan Bakera7717132017-11-14 14:11:50 -0500174 context(), SpvOpVariable, returnVarTypeId, returnVarId,
Greg Fischer04fcc662016-11-10 10:11:50 -0700175 {{spv_operand_type_t::SPV_OPERAND_TYPE_STORAGE_CLASS,
176 {SpvStorageClassFunction}}}));
177 new_vars->push_back(std::move(var_inst));
178 }
Diego Novillo83228132017-11-27 10:16:41 -0500179 get_decoration_mgr()->CloneDecorations(calleeFn->result_id(), returnVarId,
180 update_def_use_mgr_);
Greg Fischer04fcc662016-11-10 10:11:50 -0700181 return returnVarId;
182}
183
184bool InlinePass::IsSameBlockOp(const ir::Instruction* inst) const {
185 return inst->opcode() == SpvOpSampledImage || inst->opcode() == SpvOpImage;
186}
187
188void InlinePass::CloneSameBlockOps(
189 std::unique_ptr<ir::Instruction>* inst,
190 std::unordered_map<uint32_t, uint32_t>* postCallSB,
191 std::unordered_map<uint32_t, ir::Instruction*>* preCallSB,
192 std::unique_ptr<ir::BasicBlock>* block_ptr) {
Diego Novillo83228132017-11-27 10:16:41 -0500193 (*inst)->ForEachInId([&postCallSB, &preCallSB, &block_ptr,
194 this](uint32_t* iid) {
195 const auto mapItr = (*postCallSB).find(*iid);
196 if (mapItr == (*postCallSB).end()) {
197 const auto mapItr2 = (*preCallSB).find(*iid);
198 if (mapItr2 != (*preCallSB).end()) {
199 // Clone pre-call same-block ops, map result id.
200 const ir::Instruction* inInst = mapItr2->second;
201 std::unique_ptr<ir::Instruction> sb_inst(
202 inInst->Clone(inInst->context()));
203 CloneSameBlockOps(&sb_inst, postCallSB, preCallSB, block_ptr);
204 const uint32_t rid = sb_inst->result_id();
205 const uint32_t nid = this->TakeNextId();
206 get_decoration_mgr()->CloneDecorations(rid, nid, update_def_use_mgr_);
207 sb_inst->SetResultId(nid);
208 (*postCallSB)[rid] = nid;
209 *iid = nid;
210 (*block_ptr)->AddInstruction(std::move(sb_inst));
211 }
212 } else {
213 // Reset same-block op operand.
214 *iid = mapItr->second;
215 }
216 });
Greg Fischer04fcc662016-11-10 10:11:50 -0700217}
218
219void InlinePass::GenInlineCode(
220 std::vector<std::unique_ptr<ir::BasicBlock>>* new_blocks,
221 std::vector<std::unique_ptr<ir::Instruction>>* new_vars,
Steven Perronbb7802b2017-10-13 14:25:21 -0400222 ir::BasicBlock::iterator call_inst_itr,
Greg Fischer04fcc662016-11-10 10:11:50 -0700223 ir::UptrVectorIterator<ir::BasicBlock> call_block_itr) {
224 // Map from all ids in the callee to their equivalent id in the caller
225 // as callee instructions are copied into caller.
226 std::unordered_map<uint32_t, uint32_t> callee2caller;
227 // Pre-call same-block insts
228 std::unordered_map<uint32_t, ir::Instruction*> preCallSB;
229 // Post-call same-block op ids
230 std::unordered_map<uint32_t, uint32_t> postCallSB;
231
232 ir::Function* calleeFn = id2function_[call_inst_itr->GetSingleWordOperand(
233 kSpvFunctionCallFunctionId)];
234
David Neto2a1014b2017-08-09 14:59:04 -0400235 // Check for multiple returns in the callee.
236 auto fi = multi_return_funcs_.find(calleeFn->result_id());
237 const bool multiReturn = fi != multi_return_funcs_.end();
Greg Fischerbba812f2017-05-04 20:55:53 -0600238
Greg Fischer04fcc662016-11-10 10:11:50 -0700239 // Map parameters to actual arguments.
240 MapParams(calleeFn, call_inst_itr, &callee2caller);
241
242 // Define caller local variables for all callee variables and create map to
243 // them.
244 CloneAndMapLocals(calleeFn, new_vars, &callee2caller);
245
246 // Create return var if needed.
247 uint32_t returnVarId = CreateReturnVar(calleeFn, new_vars);
248
GregFa699d1a2017-08-29 18:35:05 -0600249 // Create set of callee result ids. Used to detect forward references
250 std::unordered_set<uint32_t> callee_result_ids;
Diego Novillod2938e42017-11-08 12:40:02 -0500251 calleeFn->ForEachInst([&callee_result_ids](const ir::Instruction* cpi) {
GregFa699d1a2017-08-29 18:35:05 -0600252 const uint32_t rid = cpi->result_id();
Diego Novillod2938e42017-11-08 12:40:02 -0500253 if (rid != 0) callee_result_ids.insert(rid);
GregFa699d1a2017-08-29 18:35:05 -0600254 });
255
David Netoefff5fa2017-08-31 15:47:31 -0400256 // If the caller is in a single-block loop, and the callee has multiple
257 // blocks, then the normal inlining logic will place the OpLoopMerge in
258 // the last of several blocks in the loop. Instead, it should be placed
259 // at the end of the first block. First determine if the caller is in a
260 // single block loop. We'll wait to move the OpLoopMerge until the end
261 // of the regular inlining logic, and only if necessary.
262 bool caller_is_single_block_loop = false;
David Neto25ddfec2017-09-02 19:01:03 -0400263 bool caller_is_loop_header = false;
David Netoefff5fa2017-08-31 15:47:31 -0400264 if (auto* loop_merge = call_block_itr->GetLoopMergeInst()) {
David Neto25ddfec2017-09-02 19:01:03 -0400265 caller_is_loop_header = true;
David Netoefff5fa2017-08-31 15:47:31 -0400266 caller_is_single_block_loop =
267 call_block_itr->id() ==
268 loop_merge->GetSingleWordInOperand(kSpvLoopMergeContinueTargetIdInIdx);
269 }
270
271 bool callee_begins_with_structured_header =
272 (*(calleeFn->begin())).GetMergeInst() != nullptr;
273
Greg Fischer04fcc662016-11-10 10:11:50 -0700274 // Clone and map callee code. Copy caller block code to beginning of
275 // first block and end of last block.
276 bool prevInstWasReturn = false;
Greg Fischerbba812f2017-05-04 20:55:53 -0600277 uint32_t singleTripLoopHeaderId = 0;
278 uint32_t singleTripLoopContinueId = 0;
Greg Fischer04fcc662016-11-10 10:11:50 -0700279 uint32_t returnLabelId = 0;
280 bool multiBlocks = false;
281 const uint32_t calleeTypeId = calleeFn->type_id();
David Neto2a1014b2017-08-09 14:59:04 -0400282 // new_blk_ptr is a new basic block in the caller. New instructions are
283 // written to it. It is created when we encounter the OpLabel
David Netoefff5fa2017-08-31 15:47:31 -0400284 // of the first callee block. It is appended to new_blocks only when
285 // it is complete.
Greg Fischer04fcc662016-11-10 10:11:50 -0700286 std::unique_ptr<ir::BasicBlock> new_blk_ptr;
287 calleeFn->ForEachInst([&new_blocks, &callee2caller, &call_block_itr,
288 &call_inst_itr, &new_blk_ptr, &prevInstWasReturn,
David Neto25ddfec2017-09-02 19:01:03 -0400289 &returnLabelId, &returnVarId, caller_is_loop_header,
David Netoefff5fa2017-08-31 15:47:31 -0400290 callee_begins_with_structured_header, &calleeTypeId,
David Neto2a1014b2017-08-09 14:59:04 -0400291 &multiBlocks, &postCallSB, &preCallSB, multiReturn,
Greg Fischerbba812f2017-05-04 20:55:53 -0600292 &singleTripLoopHeaderId, &singleTripLoopContinueId,
David Netoefff5fa2017-08-31 15:47:31 -0400293 &callee_result_ids, this](const ir::Instruction* cpi) {
Greg Fischer04fcc662016-11-10 10:11:50 -0700294 switch (cpi->opcode()) {
295 case SpvOpFunction:
296 case SpvOpFunctionParameter:
297 case SpvOpVariable:
298 // Already processed
299 break;
300 case SpvOpLabel: {
301 // If previous instruction was early return, insert branch
302 // instruction to return block.
303 if (prevInstWasReturn) {
304 if (returnLabelId == 0) returnLabelId = this->TakeNextId();
305 AddBranch(returnLabelId, &new_blk_ptr);
306 prevInstWasReturn = false;
307 }
308 // Finish current block (if it exists) and get label for next block.
309 uint32_t labelId;
310 bool firstBlock = false;
311 if (new_blk_ptr != nullptr) {
312 new_blocks->push_back(std::move(new_blk_ptr));
313 // If result id is already mapped, use it, otherwise get a new
314 // one.
315 const uint32_t rid = cpi->result_id();
316 const auto mapItr = callee2caller.find(rid);
317 labelId = (mapItr != callee2caller.end()) ? mapItr->second
318 : this->TakeNextId();
319 } else {
320 // First block needs to use label of original block
321 // but map callee label in case of phi reference.
Greg Fischerbba812f2017-05-04 20:55:53 -0600322 labelId = call_block_itr->id();
Greg Fischer04fcc662016-11-10 10:11:50 -0700323 callee2caller[cpi->result_id()] = labelId;
324 firstBlock = true;
325 }
326 // Create first/next block.
327 new_blk_ptr.reset(new ir::BasicBlock(NewLabel(labelId)));
328 if (firstBlock) {
329 // Copy contents of original caller block up to call instruction.
330 for (auto cii = call_block_itr->begin(); cii != call_inst_itr;
Greg Fischerbba812f2017-05-04 20:55:53 -0600331 ++cii) {
Alan Bakera7717132017-11-14 14:11:50 -0500332 std::unique_ptr<ir::Instruction> cp_inst(cii->Clone(context()));
Greg Fischer04fcc662016-11-10 10:11:50 -0700333 // Remember same-block ops for possible regeneration.
334 if (IsSameBlockOp(&*cp_inst)) {
335 auto* sb_inst_ptr = cp_inst.get();
336 preCallSB[cp_inst->result_id()] = sb_inst_ptr;
337 }
338 new_blk_ptr->AddInstruction(std::move(cp_inst));
339 }
Diego Novillod2938e42017-11-08 12:40:02 -0500340 if (caller_is_loop_header && callee_begins_with_structured_header) {
David Netoefff5fa2017-08-31 15:47:31 -0400341 // 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));
Diego Novillod2938e42017-11-08 12:40:02 -0500372 new_blk_ptr.reset(
373 new ir::BasicBlock(NewLabel(singleTripLoopHeaderId)));
Greg Fischerbba812f2017-05-04 20:55:53 -0600374 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) {
Alan Bakera7717132017-11-14 14:11:50 -0500441 std::unique_ptr<ir::Instruction> cp_inst(cii->Clone(context()));
Greg Fischer04fcc662016-11-10 10:11:50 -0700442 // 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.
Alan Bakera7717132017-11-14 14:11:50 -0500459 std::unique_ptr<ir::Instruction> cp_inst(cpi->Clone(context()));
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;
Diego Novillod2938e42017-11-08 12:40:02 -0500481 } else {
GregFa699d1a2017-08-29 18:35:05 -0600482 nid = this->TakeNextId();
483 callee2caller[rid] = nid;
484 }
Greg Fischer04fcc662016-11-10 10:11:50 -0700485 cp_inst->SetResultId(nid);
Steven Perroneb4653a2017-11-13 15:31:43 -0500486 get_decoration_mgr()->CloneDecorations(rid, nid, update_def_use_mgr_);
Greg Fischer04fcc662016-11-10 10:11:50 -0700487 }
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);
Alan Bakera7717132017-11-14 14:11:50 -0500504 std::unique_ptr<ir::Instruction> cp_inst(loop_merge_itr->Clone(context()));
David Neto25ddfec2017-09-02 19:01:03 -0400505 if (caller_is_single_block_loop) {
506 // Also, update its continue target to point to the last block.
507 cp_inst->SetInOperand(kSpvLoopMergeContinueTargetIdInIdx, {last->id()});
508 }
David Netoefff5fa2017-08-31 15:47:31 -0400509 first->tail().InsertBefore(std::move(cp_inst));
510
511 // Remove the loop merge from the last block.
Steven Perronbb7802b2017-10-13 14:25:21 -0400512 loop_merge_itr->RemoveFromList();
513 delete &*loop_merge_itr;
David Netoefff5fa2017-08-31 15:47:31 -0400514 }
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();
Diego Novillod2938e42017-11-08 12:40:02 -0500536 (*lastBlk)->ForEachSuccessorLabel([&firstId, &lastId, this](uint32_t succ) {
537 ir::BasicBlock* sbp = this->id2block_[succ];
538 sbp->ForEachPhiInst([&firstId, &lastId](ir::Instruction* phi) {
539 phi->ForEachInId([&firstId, &lastId](uint32_t* id) {
540 if (*id == firstId) *id = lastId;
GregFe28bd392017-08-01 17:20:13 -0600541 });
Diego Novillod2938e42017-11-08 12:40:02 -0500542 });
543 });
Greg Fischer04fcc662016-11-10 10:11:50 -0700544}
545
Greg Fischerbba812f2017-05-04 20:55:53 -0600546bool InlinePass::HasMultipleReturns(ir::Function* func) {
547 bool seenReturn = false;
548 bool multipleReturns = false;
549 for (auto& blk : *func) {
550 auto terminal_ii = blk.cend();
551 --terminal_ii;
Diego Novillod2938e42017-11-08 12:40:02 -0500552 if (terminal_ii->opcode() == SpvOpReturn ||
Greg Fischerbba812f2017-05-04 20:55:53 -0600553 terminal_ii->opcode() == SpvOpReturnValue) {
554 if (seenReturn) {
555 multipleReturns = true;
556 break;
557 }
558 seenReturn = true;
559 }
560 }
561 return multipleReturns;
562}
563
Greg Fischerbba812f2017-05-04 20:55:53 -0600564void InlinePass::ComputeStructuredSuccessors(ir::Function* func) {
565 // If header, make merge block first successor.
566 for (auto& blk : *func) {
Diego Novillofef669f2017-10-30 17:42:26 -0400567 uint32_t mbid = blk.MergeBlockIdIfAny();
568 if (mbid != 0) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600569 block2structured_succs_[&blk].push_back(id2block_[mbid]);
Diego Novillofef669f2017-10-30 17:42:26 -0400570 }
571
572 // Add true successors.
Greg Fischerbba812f2017-05-04 20:55:53 -0600573 blk.ForEachSuccessorLabel([&blk, this](uint32_t sbid) {
574 block2structured_succs_[&blk].push_back(id2block_[sbid]);
575 });
576 }
577}
Diego Novillofef669f2017-10-30 17:42:26 -0400578
Greg Fischerbba812f2017-05-04 20:55:53 -0600579InlinePass::GetBlocksFunction InlinePass::StructuredSuccessorsFunction() {
580 return [this](const ir::BasicBlock* block) {
581 return &(block2structured_succs_[block]);
582 };
583}
584
585bool InlinePass::HasNoReturnInLoop(ir::Function* func) {
586 // If control not structured, do not do loop/return analysis
587 // TODO: Analyze returns in non-structured control flow
Diego Novillod2938e42017-11-08 12:40:02 -0500588 if (!get_module()->HasCapability(SpvCapabilityShader)) return false;
Greg Fischerbba812f2017-05-04 20:55:53 -0600589 // 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(
Diego Novillod2938e42017-11-08 12:40:02 -0500597 &*func->begin(), StructuredSuccessorsFunction(), ignore_block,
598 [&](cbb_ptr b) { structuredOrder.push_front(b); }, ignore_edge);
Greg Fischerbba812f2017-05-04 20:55:53 -0600599 // 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
Diego Novillod2938e42017-11-08 12:40:02 -0500604 if (blk->id() == outerLoopMergeId) outerLoopMergeId = 0;
Greg Fischerbba812f2017-05-04 20:55:53 -0600605 // Return block
606 auto terminal_ii = blk->cend();
607 --terminal_ii;
Diego Novillod2938e42017-11-08 12:40:02 -0500608 if (terminal_ii->opcode() == SpvOpReturn ||
Greg Fischerbba812f2017-05-04 20:55:53 -0600609 terminal_ii->opcode() == SpvOpReturnValue) {
610 if (outerLoopMergeId != 0) {
611 return_in_loop = true;
612 break;
613 }
Diego Novillod2938e42017-11-08 12:40:02 -0500614 } else if (terminal_ii != blk->cbegin()) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600615 auto merge_ii = terminal_ii;
616 --merge_ii;
617 // Entering outermost loop
618 if (merge_ii->opcode() == SpvOpLoopMerge && outerLoopMergeId == 0)
Diego Novillod2938e42017-11-08 12:40:02 -0500619 outerLoopMergeId =
620 merge_ii->GetSingleWordOperand(kSpvLoopMergeMergeBlockId);
Greg Fischerbba812f2017-05-04 20:55:53 -0600621 }
622 }
623 return !return_in_loop;
624}
625
626void InlinePass::AnalyzeReturns(ir::Function* func) {
627 // Look for multiple returns
628 if (!HasMultipleReturns(func)) {
629 no_return_in_loop_.insert(func->result_id());
630 return;
631 }
David Neto2a1014b2017-08-09 14:59:04 -0400632 multi_return_funcs_.insert(func->result_id());
Greg Fischerbba812f2017-05-04 20:55:53 -0600633 // If multiple returns, see if any are in a loop
Diego Novillod2938e42017-11-08 12:40:02 -0500634 if (HasNoReturnInLoop(func)) no_return_in_loop_.insert(func->result_id());
Greg Fischerbba812f2017-05-04 20:55:53 -0600635}
636
637bool InlinePass::IsInlinableFunction(ir::Function* func) {
GregFa107d342017-04-25 13:57:20 -0600638 // We can only inline a function if it has blocks.
Diego Novillod2938e42017-11-08 12:40:02 -0500639 if (func->cbegin() == func->cend()) return false;
Greg Fischerbba812f2017-05-04 20:55:53 -0600640 // Do not inline functions with returns in loops. Currently early return
641 // functions are inlined by wrapping them in a one trip loop and implementing
642 // the returns as a branch to the loop's merge block. However, this can only
643 // done validly if the return was not in a loop in the original function.
644 // Also remember functions with multiple (early) returns.
645 AnalyzeReturns(func);
David Netoefff5fa2017-08-31 15:47:31 -0400646 return no_return_in_loop_.find(func->result_id()) !=
647 no_return_in_loop_.cend();
GregFa107d342017-04-25 13:57:20 -0600648}
649
Steven Perron476cae62017-10-30 11:13:24 -0400650void InlinePass::InitializeInline(ir::IRContext* c) {
651 InitializeProcessing(c);
Greg Fischer04fcc662016-11-10 10:11:50 -0700652
Alan Baker746bfd22017-11-14 14:11:50 -0500653 // Don't bother updating the DefUseManger
Pierre Moreau69043962017-11-30 22:32:44 +0100654 update_def_use_mgr_ = [](ir::Instruction&, bool) {};
Daniel Schürmanna76d0972017-10-24 18:28:18 +0200655
Greg Fischerbba812f2017-05-04 20:55:53 -0600656 false_id_ = 0;
657
GregFe28bd392017-08-01 17:20:13 -0600658 // clear collections
Greg Fischer04fcc662016-11-10 10:11:50 -0700659 id2function_.clear();
660 id2block_.clear();
Greg Fischerbba812f2017-05-04 20:55:53 -0600661 block2structured_succs_.clear();
GregFa107d342017-04-25 13:57:20 -0600662 inlinable_.clear();
GregFe28bd392017-08-01 17:20:13 -0600663 no_return_in_loop_.clear();
David Neto2a1014b2017-08-09 14:59:04 -0400664 multi_return_funcs_.clear();
GregFe28bd392017-08-01 17:20:13 -0600665
Diego Novillo1040a952017-10-25 13:26:25 -0400666 for (auto& fn : *get_module()) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600667 // Initialize function and block maps.
Greg Fischer04fcc662016-11-10 10:11:50 -0700668 id2function_[fn.result_id()] = &fn;
669 for (auto& blk : fn) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600670 id2block_[blk.id()] = &blk;
Greg Fischer04fcc662016-11-10 10:11:50 -0700671 }
Greg Fischerbba812f2017-05-04 20:55:53 -0600672 // Compute inlinability
Diego Novillod2938e42017-11-08 12:40:02 -0500673 if (IsInlinableFunction(&fn)) inlinable_.insert(fn.result_id());
Greg Fischer04fcc662016-11-10 10:11:50 -0700674 }
675};
676
Diego Novillo1040a952017-10-25 13:26:25 -0400677InlinePass::InlinePass() {}
Greg Fischer04fcc662016-11-10 10:11:50 -0700678
Greg Fischer04fcc662016-11-10 10:11:50 -0700679} // namespace opt
680} // namespace spvtools