blob: 665f3a7b6a4dae1106d673e091ae0f4441cbd557 [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;
Greg Fischerbba812f2017-05-04 20:55:53 -060026static const int kSpvLoopMergeMergeBlockId = 0;
David Netoefff5fa2017-08-31 15:47:31 -040027static const int kSpvLoopMergeContinueTargetIdInIdx = 1;
Greg Fischer04fcc662016-11-10 10:11:50 -070028
29namespace spvtools {
30namespace opt {
31
Greg Fischer04fcc662016-11-10 10:11:50 -070032uint32_t InlinePass::AddPointerToType(uint32_t type_id,
33 SpvStorageClass storage_class) {
34 uint32_t resultId = TakeNextId();
dan sinclairc7da51a2018-07-12 15:14:43 -040035 std::unique_ptr<Instruction> type_inst(
36 new Instruction(context(), SpvOpTypePointer, 0, resultId,
37 {{spv_operand_type_t::SPV_OPERAND_TYPE_STORAGE_CLASS,
38 {uint32_t(storage_class)}},
39 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {type_id}}}));
Steven Perron476cae62017-10-30 11:13:24 -040040 context()->AddType(std::move(type_inst));
Alan Baker61690852017-12-08 15:33:19 -050041 analysis::Type* pointeeTy;
42 std::unique_ptr<analysis::Pointer> pointerTy;
43 std::tie(pointeeTy, pointerTy) =
44 context()->get_type_mgr()->GetTypeAndPointerType(type_id,
45 SpvStorageClassFunction);
46 context()->get_type_mgr()->RegisterType(resultId, *pointerTy);
Greg Fischer04fcc662016-11-10 10:11:50 -070047 return resultId;
48}
49
50void InlinePass::AddBranch(uint32_t label_id,
dan sinclairc7da51a2018-07-12 15:14:43 -040051 std::unique_ptr<BasicBlock>* block_ptr) {
52 std::unique_ptr<Instruction> newBranch(
53 new Instruction(context(), SpvOpBranch, 0, 0,
54 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {label_id}}}));
Greg Fischer04fcc662016-11-10 10:11:50 -070055 (*block_ptr)->AddInstruction(std::move(newBranch));
56}
57
Greg Fischerbba812f2017-05-04 20:55:53 -060058void InlinePass::AddBranchCond(uint32_t cond_id, uint32_t true_id,
Diego Novillod2938e42017-11-08 12:40:02 -050059 uint32_t false_id,
dan sinclairc7da51a2018-07-12 15:14:43 -040060 std::unique_ptr<BasicBlock>* block_ptr) {
61 std::unique_ptr<Instruction> newBranch(
62 new Instruction(context(), SpvOpBranchConditional, 0, 0,
63 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {cond_id}},
64 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {true_id}},
65 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {false_id}}}));
Greg Fischerbba812f2017-05-04 20:55:53 -060066 (*block_ptr)->AddInstruction(std::move(newBranch));
67}
68
69void InlinePass::AddLoopMerge(uint32_t merge_id, uint32_t continue_id,
dan sinclairc7da51a2018-07-12 15:14:43 -040070 std::unique_ptr<BasicBlock>* block_ptr) {
71 std::unique_ptr<Instruction> newLoopMerge(new Instruction(
Alan Bakera7717132017-11-14 14:11:50 -050072 context(), SpvOpLoopMerge, 0, 0,
Greg Fischerbba812f2017-05-04 20:55:53 -060073 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {merge_id}},
74 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {continue_id}},
75 {spv_operand_type_t::SPV_OPERAND_TYPE_LOOP_CONTROL, {0}}}));
76 (*block_ptr)->AddInstruction(std::move(newLoopMerge));
77}
78
Greg Fischer04fcc662016-11-10 10:11:50 -070079void InlinePass::AddStore(uint32_t ptr_id, uint32_t val_id,
dan sinclairc7da51a2018-07-12 15:14:43 -040080 std::unique_ptr<BasicBlock>* block_ptr) {
81 std::unique_ptr<Instruction> newStore(
82 new Instruction(context(), SpvOpStore, 0, 0,
83 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {ptr_id}},
84 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {val_id}}}));
Greg Fischer04fcc662016-11-10 10:11:50 -070085 (*block_ptr)->AddInstruction(std::move(newStore));
86}
87
88void InlinePass::AddLoad(uint32_t type_id, uint32_t resultId, uint32_t ptr_id,
dan sinclairc7da51a2018-07-12 15:14:43 -040089 std::unique_ptr<BasicBlock>* block_ptr) {
90 std::unique_ptr<Instruction> newLoad(
91 new Instruction(context(), SpvOpLoad, type_id, resultId,
92 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {ptr_id}}}));
Greg Fischer04fcc662016-11-10 10:11:50 -070093 (*block_ptr)->AddInstruction(std::move(newLoad));
94}
95
dan sinclairc7da51a2018-07-12 15:14:43 -040096std::unique_ptr<Instruction> InlinePass::NewLabel(uint32_t label_id) {
97 std::unique_ptr<Instruction> newLabel(
98 new Instruction(context(), SpvOpLabel, 0, label_id, {}));
Greg Fischer04fcc662016-11-10 10:11:50 -070099 return newLabel;
100}
101
Greg Fischerbba812f2017-05-04 20:55:53 -0600102uint32_t InlinePass::GetFalseId() {
Diego Novillod2938e42017-11-08 12:40:02 -0500103 if (false_id_ != 0) return false_id_;
Diego Novillo1040a952017-10-25 13:26:25 -0400104 false_id_ = get_module()->GetGlobalValue(SpvOpConstantFalse);
Diego Novillod2938e42017-11-08 12:40:02 -0500105 if (false_id_ != 0) return false_id_;
Diego Novillo1040a952017-10-25 13:26:25 -0400106 uint32_t boolId = get_module()->GetGlobalValue(SpvOpTypeBool);
Greg Fischerbba812f2017-05-04 20:55:53 -0600107 if (boolId == 0) {
108 boolId = TakeNextId();
Diego Novillo1040a952017-10-25 13:26:25 -0400109 get_module()->AddGlobalValue(SpvOpTypeBool, boolId, 0);
Greg Fischerbba812f2017-05-04 20:55:53 -0600110 }
111 false_id_ = TakeNextId();
Diego Novillo1040a952017-10-25 13:26:25 -0400112 get_module()->AddGlobalValue(SpvOpConstantFalse, false_id_, boolId);
Greg Fischerbba812f2017-05-04 20:55:53 -0600113 return false_id_;
114}
115
Greg Fischer04fcc662016-11-10 10:11:50 -0700116void InlinePass::MapParams(
dan sinclairc7da51a2018-07-12 15:14:43 -0400117 Function* calleeFn, BasicBlock::iterator call_inst_itr,
Greg Fischer04fcc662016-11-10 10:11:50 -0700118 std::unordered_map<uint32_t, uint32_t>* callee2caller) {
119 int param_idx = 0;
dan sinclaire6b95332018-07-09 11:32:29 -0400120 calleeFn->ForEachParam([&call_inst_itr, &param_idx,
dan sinclairc7da51a2018-07-12 15:14:43 -0400121 &callee2caller](const Instruction* cpi) {
dan sinclaire6b95332018-07-09 11:32:29 -0400122 const uint32_t pid = cpi->result_id();
123 (*callee2caller)[pid] = call_inst_itr->GetSingleWordOperand(
124 kSpvFunctionCallArgumentId + param_idx);
125 ++param_idx;
126 });
Greg Fischer04fcc662016-11-10 10:11:50 -0700127}
128
129void InlinePass::CloneAndMapLocals(
dan sinclairc7da51a2018-07-12 15:14:43 -0400130 Function* calleeFn, std::vector<std::unique_ptr<Instruction>>* new_vars,
Greg Fischer04fcc662016-11-10 10:11:50 -0700131 std::unordered_map<uint32_t, uint32_t>* callee2caller) {
132 auto callee_block_itr = calleeFn->begin();
133 auto callee_var_itr = callee_block_itr->begin();
134 while (callee_var_itr->opcode() == SpvOp::SpvOpVariable) {
dan sinclairc7da51a2018-07-12 15:14:43 -0400135 std::unique_ptr<Instruction> var_inst(callee_var_itr->Clone(context()));
Greg Fischer04fcc662016-11-10 10:11:50 -0700136 uint32_t newId = TakeNextId();
Pierre Moreau5bd55f12018-02-20 19:19:57 +0100137 get_decoration_mgr()->CloneDecorations(callee_var_itr->result_id(), newId);
Greg Fischer04fcc662016-11-10 10:11:50 -0700138 var_inst->SetResultId(newId);
139 (*callee2caller)[callee_var_itr->result_id()] = newId;
140 new_vars->push_back(std::move(var_inst));
Greg Fischerbba812f2017-05-04 20:55:53 -0600141 ++callee_var_itr;
Greg Fischer04fcc662016-11-10 10:11:50 -0700142 }
143}
144
145uint32_t InlinePass::CreateReturnVar(
dan sinclairc7da51a2018-07-12 15:14:43 -0400146 Function* calleeFn, std::vector<std::unique_ptr<Instruction>>* new_vars) {
Greg Fischer04fcc662016-11-10 10:11:50 -0700147 uint32_t returnVarId = 0;
148 const uint32_t calleeTypeId = calleeFn->type_id();
Steven Perron06b437d2018-02-09 20:33:06 -0500149 analysis::Type* calleeType = context()->get_type_mgr()->GetType(calleeTypeId);
150 if (calleeType->AsVoid() == nullptr) {
Greg Fischer04fcc662016-11-10 10:11:50 -0700151 // Find or create ptr to callee return type.
Steven Perronb86eb682017-12-11 13:10:24 -0500152 uint32_t returnVarTypeId = context()->get_type_mgr()->FindPointerToType(
153 calleeTypeId, SpvStorageClassFunction);
Greg Fischer04fcc662016-11-10 10:11:50 -0700154 if (returnVarTypeId == 0)
155 returnVarTypeId = AddPointerToType(calleeTypeId, SpvStorageClassFunction);
156 // Add return var to new function scope variables.
157 returnVarId = TakeNextId();
dan sinclairc7da51a2018-07-12 15:14:43 -0400158 std::unique_ptr<Instruction> var_inst(
159 new Instruction(context(), SpvOpVariable, returnVarTypeId, returnVarId,
160 {{spv_operand_type_t::SPV_OPERAND_TYPE_STORAGE_CLASS,
161 {SpvStorageClassFunction}}}));
Greg Fischer04fcc662016-11-10 10:11:50 -0700162 new_vars->push_back(std::move(var_inst));
163 }
Pierre Moreau5bd55f12018-02-20 19:19:57 +0100164 get_decoration_mgr()->CloneDecorations(calleeFn->result_id(), returnVarId);
Greg Fischer04fcc662016-11-10 10:11:50 -0700165 return returnVarId;
166}
167
dan sinclairc7da51a2018-07-12 15:14:43 -0400168bool InlinePass::IsSameBlockOp(const Instruction* inst) const {
Greg Fischer04fcc662016-11-10 10:11:50 -0700169 return inst->opcode() == SpvOpSampledImage || inst->opcode() == SpvOpImage;
170}
171
172void InlinePass::CloneSameBlockOps(
dan sinclairc7da51a2018-07-12 15:14:43 -0400173 std::unique_ptr<Instruction>* inst,
Greg Fischer04fcc662016-11-10 10:11:50 -0700174 std::unordered_map<uint32_t, uint32_t>* postCallSB,
dan sinclairc7da51a2018-07-12 15:14:43 -0400175 std::unordered_map<uint32_t, Instruction*>* preCallSB,
176 std::unique_ptr<BasicBlock>* block_ptr) {
Pierre Moreau5bd55f12018-02-20 19:19:57 +0100177 (*inst)->ForEachInId(
178 [&postCallSB, &preCallSB, &block_ptr, this](uint32_t* iid) {
179 const auto mapItr = (*postCallSB).find(*iid);
180 if (mapItr == (*postCallSB).end()) {
181 const auto mapItr2 = (*preCallSB).find(*iid);
182 if (mapItr2 != (*preCallSB).end()) {
183 // Clone pre-call same-block ops, map result id.
dan sinclairc7da51a2018-07-12 15:14:43 -0400184 const Instruction* inInst = mapItr2->second;
185 std::unique_ptr<Instruction> sb_inst(inInst->Clone(context()));
Pierre Moreau5bd55f12018-02-20 19:19:57 +0100186 CloneSameBlockOps(&sb_inst, postCallSB, preCallSB, block_ptr);
187 const uint32_t rid = sb_inst->result_id();
188 const uint32_t nid = this->TakeNextId();
189 get_decoration_mgr()->CloneDecorations(rid, nid);
190 sb_inst->SetResultId(nid);
191 (*postCallSB)[rid] = nid;
192 *iid = nid;
193 (*block_ptr)->AddInstruction(std::move(sb_inst));
194 }
195 } else {
196 // Reset same-block op operand.
197 *iid = mapItr->second;
198 }
199 });
Greg Fischer04fcc662016-11-10 10:11:50 -0700200}
201
202void InlinePass::GenInlineCode(
dan sinclairc7da51a2018-07-12 15:14:43 -0400203 std::vector<std::unique_ptr<BasicBlock>>* new_blocks,
204 std::vector<std::unique_ptr<Instruction>>* new_vars,
205 BasicBlock::iterator call_inst_itr,
206 UptrVectorIterator<BasicBlock> call_block_itr) {
Greg Fischer04fcc662016-11-10 10:11:50 -0700207 // Map from all ids in the callee to their equivalent id in the caller
208 // as callee instructions are copied into caller.
209 std::unordered_map<uint32_t, uint32_t> callee2caller;
210 // Pre-call same-block insts
dan sinclairc7da51a2018-07-12 15:14:43 -0400211 std::unordered_map<uint32_t, Instruction*> preCallSB;
Greg Fischer04fcc662016-11-10 10:11:50 -0700212 // Post-call same-block op ids
213 std::unordered_map<uint32_t, uint32_t> postCallSB;
214
Steven Perronb3daa932018-03-06 11:20:28 -0500215 // Invalidate the def-use chains. They are not kept up to date while
216 // inlining. However, certain calls try to keep them up-to-date if they are
217 // valid. These operations can fail.
dan sinclairc7da51a2018-07-12 15:14:43 -0400218 context()->InvalidateAnalyses(IRContext::kAnalysisDefUse);
Steven Perronb3daa932018-03-06 11:20:28 -0500219
dan sinclairc7da51a2018-07-12 15:14:43 -0400220 Function* calleeFn = id2function_[call_inst_itr->GetSingleWordOperand(
Greg Fischer04fcc662016-11-10 10:11:50 -0700221 kSpvFunctionCallFunctionId)];
222
David Neto2a1014b2017-08-09 14:59:04 -0400223 // Check for multiple returns in the callee.
224 auto fi = multi_return_funcs_.find(calleeFn->result_id());
225 const bool multiReturn = fi != multi_return_funcs_.end();
Greg Fischerbba812f2017-05-04 20:55:53 -0600226
Greg Fischer04fcc662016-11-10 10:11:50 -0700227 // Map parameters to actual arguments.
228 MapParams(calleeFn, call_inst_itr, &callee2caller);
229
230 // Define caller local variables for all callee variables and create map to
231 // them.
232 CloneAndMapLocals(calleeFn, new_vars, &callee2caller);
233
234 // Create return var if needed.
235 uint32_t returnVarId = CreateReturnVar(calleeFn, new_vars);
236
GregFa699d1a2017-08-29 18:35:05 -0600237 // Create set of callee result ids. Used to detect forward references
238 std::unordered_set<uint32_t> callee_result_ids;
dan sinclairc7da51a2018-07-12 15:14:43 -0400239 calleeFn->ForEachInst([&callee_result_ids](const Instruction* cpi) {
GregFa699d1a2017-08-29 18:35:05 -0600240 const uint32_t rid = cpi->result_id();
Diego Novillod2938e42017-11-08 12:40:02 -0500241 if (rid != 0) callee_result_ids.insert(rid);
GregFa699d1a2017-08-29 18:35:05 -0600242 });
243
David Netoefff5fa2017-08-31 15:47:31 -0400244 // If the caller is in a single-block loop, and the callee has multiple
245 // blocks, then the normal inlining logic will place the OpLoopMerge in
246 // the last of several blocks in the loop. Instead, it should be placed
247 // at the end of the first block. First determine if the caller is in a
248 // single block loop. We'll wait to move the OpLoopMerge until the end
249 // of the regular inlining logic, and only if necessary.
250 bool caller_is_single_block_loop = false;
David Neto25ddfec2017-09-02 19:01:03 -0400251 bool caller_is_loop_header = false;
David Netoefff5fa2017-08-31 15:47:31 -0400252 if (auto* loop_merge = call_block_itr->GetLoopMergeInst()) {
David Neto25ddfec2017-09-02 19:01:03 -0400253 caller_is_loop_header = true;
David Netoefff5fa2017-08-31 15:47:31 -0400254 caller_is_single_block_loop =
255 call_block_itr->id() ==
256 loop_merge->GetSingleWordInOperand(kSpvLoopMergeContinueTargetIdInIdx);
257 }
258
259 bool callee_begins_with_structured_header =
260 (*(calleeFn->begin())).GetMergeInst() != nullptr;
261
Greg Fischer04fcc662016-11-10 10:11:50 -0700262 // Clone and map callee code. Copy caller block code to beginning of
263 // first block and end of last block.
264 bool prevInstWasReturn = false;
Greg Fischerbba812f2017-05-04 20:55:53 -0600265 uint32_t singleTripLoopHeaderId = 0;
266 uint32_t singleTripLoopContinueId = 0;
Greg Fischer04fcc662016-11-10 10:11:50 -0700267 uint32_t returnLabelId = 0;
268 bool multiBlocks = false;
269 const uint32_t calleeTypeId = calleeFn->type_id();
David Neto2a1014b2017-08-09 14:59:04 -0400270 // new_blk_ptr is a new basic block in the caller. New instructions are
271 // written to it. It is created when we encounter the OpLabel
David Netoefff5fa2017-08-31 15:47:31 -0400272 // of the first callee block. It is appended to new_blocks only when
273 // it is complete.
dan sinclairc7da51a2018-07-12 15:14:43 -0400274 std::unique_ptr<BasicBlock> new_blk_ptr;
Greg Fischer04fcc662016-11-10 10:11:50 -0700275 calleeFn->ForEachInst([&new_blocks, &callee2caller, &call_block_itr,
276 &call_inst_itr, &new_blk_ptr, &prevInstWasReturn,
David Neto25ddfec2017-09-02 19:01:03 -0400277 &returnLabelId, &returnVarId, caller_is_loop_header,
David Netoefff5fa2017-08-31 15:47:31 -0400278 callee_begins_with_structured_header, &calleeTypeId,
David Neto2a1014b2017-08-09 14:59:04 -0400279 &multiBlocks, &postCallSB, &preCallSB, multiReturn,
Greg Fischerbba812f2017-05-04 20:55:53 -0600280 &singleTripLoopHeaderId, &singleTripLoopContinueId,
dan sinclairc7da51a2018-07-12 15:14:43 -0400281 &callee_result_ids, this](const Instruction* cpi) {
Greg Fischer04fcc662016-11-10 10:11:50 -0700282 switch (cpi->opcode()) {
283 case SpvOpFunction:
284 case SpvOpFunctionParameter:
Greg Fischer04fcc662016-11-10 10:11:50 -0700285 // Already processed
286 break;
Steven Perron9a008832018-05-31 20:28:19 -0400287 case SpvOpVariable:
288 if (cpi->NumInOperands() == 2) {
289 assert(callee2caller.count(cpi->result_id()) &&
290 "Expected the variable to have already been mapped.");
291 uint32_t new_var_id = callee2caller.at(cpi->result_id());
292
293 // The initializer must be a constant or global value. No mapped
294 // should be used.
295 uint32_t val_id = cpi->GetSingleWordInOperand(1);
296 AddStore(new_var_id, val_id, &new_blk_ptr);
297 }
298 break;
Alan Baker4246abd2018-04-26 12:22:08 -0400299 case SpvOpUnreachable:
300 case SpvOpKill: {
301 // Generate a return label so that we split the block with the function
302 // call. Copy the terminator into the new block.
303 if (returnLabelId == 0) returnLabelId = this->TakeNextId();
dan sinclairc7da51a2018-07-12 15:14:43 -0400304 std::unique_ptr<Instruction> terminator(
305 new Instruction(context(), cpi->opcode(), 0, 0, {}));
Alan Baker4246abd2018-04-26 12:22:08 -0400306 new_blk_ptr->AddInstruction(std::move(terminator));
307 break;
308 }
Greg Fischer04fcc662016-11-10 10:11:50 -0700309 case SpvOpLabel: {
310 // If previous instruction was early return, insert branch
311 // instruction to return block.
312 if (prevInstWasReturn) {
313 if (returnLabelId == 0) returnLabelId = this->TakeNextId();
314 AddBranch(returnLabelId, &new_blk_ptr);
315 prevInstWasReturn = false;
316 }
317 // Finish current block (if it exists) and get label for next block.
318 uint32_t labelId;
319 bool firstBlock = false;
320 if (new_blk_ptr != nullptr) {
321 new_blocks->push_back(std::move(new_blk_ptr));
322 // If result id is already mapped, use it, otherwise get a new
323 // one.
324 const uint32_t rid = cpi->result_id();
325 const auto mapItr = callee2caller.find(rid);
326 labelId = (mapItr != callee2caller.end()) ? mapItr->second
327 : this->TakeNextId();
328 } else {
329 // First block needs to use label of original block
330 // but map callee label in case of phi reference.
Greg Fischerbba812f2017-05-04 20:55:53 -0600331 labelId = call_block_itr->id();
Greg Fischer04fcc662016-11-10 10:11:50 -0700332 callee2caller[cpi->result_id()] = labelId;
333 firstBlock = true;
334 }
335 // Create first/next block.
dan sinclairc7da51a2018-07-12 15:14:43 -0400336 new_blk_ptr.reset(new BasicBlock(NewLabel(labelId)));
Greg Fischer04fcc662016-11-10 10:11:50 -0700337 if (firstBlock) {
338 // Copy contents of original caller block up to call instruction.
339 for (auto cii = call_block_itr->begin(); cii != call_inst_itr;
Steven Perron51ecc732018-02-20 11:24:08 -0500340 cii = call_block_itr->begin()) {
dan sinclairc7da51a2018-07-12 15:14:43 -0400341 Instruction* inst = &*cii;
Steven Perron51ecc732018-02-20 11:24:08 -0500342 inst->RemoveFromList();
dan sinclairc7da51a2018-07-12 15:14:43 -0400343 std::unique_ptr<Instruction> cp_inst(inst);
Greg Fischer04fcc662016-11-10 10:11:50 -0700344 // Remember same-block ops for possible regeneration.
345 if (IsSameBlockOp(&*cp_inst)) {
346 auto* sb_inst_ptr = cp_inst.get();
347 preCallSB[cp_inst->result_id()] = sb_inst_ptr;
348 }
349 new_blk_ptr->AddInstruction(std::move(cp_inst));
350 }
Diego Novillod2938e42017-11-08 12:40:02 -0500351 if (caller_is_loop_header && callee_begins_with_structured_header) {
David Netoefff5fa2017-08-31 15:47:31 -0400352 // We can't place both the caller's merge instruction and another
353 // merge instruction in the same block. So split the calling block.
354 // Insert an unconditional branch to a new guard block. Later,
355 // once we know the ID of the last block, we will move the caller's
356 // OpLoopMerge from the last generated block into the first block.
357 // We also wait to avoid invalidating various iterators.
358 const auto guard_block_id = this->TakeNextId();
359 AddBranch(guard_block_id, &new_blk_ptr);
360 new_blocks->push_back(std::move(new_blk_ptr));
361 // Start the next block.
dan sinclairc7da51a2018-07-12 15:14:43 -0400362 new_blk_ptr.reset(new BasicBlock(NewLabel(guard_block_id)));
David Netoefff5fa2017-08-31 15:47:31 -0400363 // Reset the mapping of the callee's entry block to point to
364 // the guard block. Do this so we can fix up phis later on to
365 // satisfy dominance.
366 callee2caller[cpi->result_id()] = guard_block_id;
367 }
368 // If callee has multiple returns, insert a header block for
David Neto2a1014b2017-08-09 14:59:04 -0400369 // single-trip loop that will encompass callee code. Start postheader
Greg Fischerbba812f2017-05-04 20:55:53 -0600370 // block.
David Netoefff5fa2017-08-31 15:47:31 -0400371 //
372 // Note: Consider the following combination:
373 // - the caller is a single block loop
374 // - the callee does not begin with a structure header
375 // - the callee has multiple returns.
376 // We still need to split the caller block and insert a guard block.
377 // But we only need to do it once. We haven't done it yet, but the
378 // single-trip loop header will serve the same purpose.
David Neto2a1014b2017-08-09 14:59:04 -0400379 if (multiReturn) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600380 singleTripLoopHeaderId = this->TakeNextId();
381 AddBranch(singleTripLoopHeaderId, &new_blk_ptr);
382 new_blocks->push_back(std::move(new_blk_ptr));
dan sinclairc7da51a2018-07-12 15:14:43 -0400383 new_blk_ptr.reset(new BasicBlock(NewLabel(singleTripLoopHeaderId)));
Greg Fischerbba812f2017-05-04 20:55:53 -0600384 returnLabelId = this->TakeNextId();
385 singleTripLoopContinueId = this->TakeNextId();
386 AddLoopMerge(returnLabelId, singleTripLoopContinueId, &new_blk_ptr);
387 uint32_t postHeaderId = this->TakeNextId();
388 AddBranch(postHeaderId, &new_blk_ptr);
389 new_blocks->push_back(std::move(new_blk_ptr));
dan sinclairc7da51a2018-07-12 15:14:43 -0400390 new_blk_ptr.reset(new BasicBlock(NewLabel(postHeaderId)));
Greg Fischerbba812f2017-05-04 20:55:53 -0600391 multiBlocks = true;
David Neto860c4192017-08-31 17:33:44 -0400392 // Reset the mapping of the callee's entry block to point to
393 // the post-header block. Do this so we can fix up phis later
394 // on to satisfy dominance.
395 callee2caller[cpi->result_id()] = postHeaderId;
Greg Fischerbba812f2017-05-04 20:55:53 -0600396 }
Greg Fischer04fcc662016-11-10 10:11:50 -0700397 } else {
398 multiBlocks = true;
399 }
400 } break;
401 case SpvOpReturnValue: {
402 // Store return value to return variable.
403 assert(returnVarId != 0);
404 uint32_t valId = cpi->GetInOperand(kSpvReturnValueId).words[0];
405 const auto mapItr = callee2caller.find(valId);
406 if (mapItr != callee2caller.end()) {
407 valId = mapItr->second;
408 }
409 AddStore(returnVarId, valId, &new_blk_ptr);
410
411 // Remember we saw a return; if followed by a label, will need to
412 // insert branch.
413 prevInstWasReturn = true;
414 } break;
415 case SpvOpReturn: {
416 // Remember we saw a return; if followed by a label, will need to
417 // insert branch.
418 prevInstWasReturn = true;
419 } break;
420 case SpvOpFunctionEnd: {
David Neto2a1014b2017-08-09 14:59:04 -0400421 // If there was an early return, we generated a return label id
422 // for it. Now we have to generate the return block with that Id.
Greg Fischer04fcc662016-11-10 10:11:50 -0700423 if (returnLabelId != 0) {
David Neto2a1014b2017-08-09 14:59:04 -0400424 // If previous instruction was return, insert branch instruction
425 // to return block.
Greg Fischer04fcc662016-11-10 10:11:50 -0700426 if (prevInstWasReturn) AddBranch(returnLabelId, &new_blk_ptr);
David Neto2a1014b2017-08-09 14:59:04 -0400427 if (multiReturn) {
428 // If we generated a loop header to for the single-trip loop
429 // to accommodate multiple returns, insert the continue
430 // target block now, with a false branch back to the loop header.
431 new_blocks->push_back(std::move(new_blk_ptr));
432 new_blk_ptr.reset(
dan sinclairc7da51a2018-07-12 15:14:43 -0400433 new BasicBlock(NewLabel(singleTripLoopContinueId)));
David Neto2a1014b2017-08-09 14:59:04 -0400434 AddBranchCond(GetFalseId(), singleTripLoopHeaderId, returnLabelId,
435 &new_blk_ptr);
436 }
437 // Generate the return block.
Greg Fischerbba812f2017-05-04 20:55:53 -0600438 new_blocks->push_back(std::move(new_blk_ptr));
dan sinclairc7da51a2018-07-12 15:14:43 -0400439 new_blk_ptr.reset(new BasicBlock(NewLabel(returnLabelId)));
Greg Fischer04fcc662016-11-10 10:11:50 -0700440 multiBlocks = true;
441 }
442 // Load return value into result id of call, if it exists.
443 if (returnVarId != 0) {
444 const uint32_t resId = call_inst_itr->result_id();
445 assert(resId != 0);
446 AddLoad(calleeTypeId, resId, returnVarId, &new_blk_ptr);
447 }
448 // Copy remaining instructions from caller block.
dan sinclairc7da51a2018-07-12 15:14:43 -0400449 for (Instruction* inst = call_inst_itr->NextNode(); inst;
Steven Perron51ecc732018-02-20 11:24:08 -0500450 inst = call_inst_itr->NextNode()) {
451 inst->RemoveFromList();
dan sinclairc7da51a2018-07-12 15:14:43 -0400452 std::unique_ptr<Instruction> cp_inst(inst);
Greg Fischer04fcc662016-11-10 10:11:50 -0700453 // If multiple blocks generated, regenerate any same-block
454 // instruction that has not been seen in this last block.
455 if (multiBlocks) {
456 CloneSameBlockOps(&cp_inst, &postCallSB, &preCallSB, &new_blk_ptr);
457 // Remember same-block ops in this block.
458 if (IsSameBlockOp(&*cp_inst)) {
459 const uint32_t rid = cp_inst->result_id();
460 postCallSB[rid] = rid;
461 }
462 }
463 new_blk_ptr->AddInstruction(std::move(cp_inst));
464 }
465 // Finalize inline code.
466 new_blocks->push_back(std::move(new_blk_ptr));
467 } break;
468 default: {
469 // Copy callee instruction and remap all input Ids.
dan sinclairc7da51a2018-07-12 15:14:43 -0400470 std::unique_ptr<Instruction> cp_inst(cpi->Clone(context()));
David Netoefff5fa2017-08-31 15:47:31 -0400471 cp_inst->ForEachInId([&callee2caller, &callee_result_ids,
472 this](uint32_t* iid) {
Greg Fischer04fcc662016-11-10 10:11:50 -0700473 const auto mapItr = callee2caller.find(*iid);
474 if (mapItr != callee2caller.end()) {
475 *iid = mapItr->second;
GregFa699d1a2017-08-29 18:35:05 -0600476 } else if (callee_result_ids.find(*iid) != callee_result_ids.end()) {
477 // Forward reference. Allocate a new id, map it,
478 // use it and check for it when remapping result ids
479 const uint32_t nid = this->TakeNextId();
480 callee2caller[*iid] = nid;
481 *iid = nid;
Greg Fischer04fcc662016-11-10 10:11:50 -0700482 }
483 });
GregFa699d1a2017-08-29 18:35:05 -0600484 // If result id is non-zero, remap it. If already mapped, use mapped
485 // value, else use next id.
Greg Fischer04fcc662016-11-10 10:11:50 -0700486 const uint32_t rid = cp_inst->result_id();
487 if (rid != 0) {
GregFa699d1a2017-08-29 18:35:05 -0600488 const auto mapItr = callee2caller.find(rid);
489 uint32_t nid;
490 if (mapItr != callee2caller.end()) {
491 nid = mapItr->second;
Diego Novillod2938e42017-11-08 12:40:02 -0500492 } else {
GregFa699d1a2017-08-29 18:35:05 -0600493 nid = this->TakeNextId();
494 callee2caller[rid] = nid;
495 }
Greg Fischer04fcc662016-11-10 10:11:50 -0700496 cp_inst->SetResultId(nid);
Pierre Moreau5bd55f12018-02-20 19:19:57 +0100497 get_decoration_mgr()->CloneDecorations(rid, nid);
Greg Fischer04fcc662016-11-10 10:11:50 -0700498 }
499 new_blk_ptr->AddInstruction(std::move(cp_inst));
500 } break;
501 }
502 });
David Netoefff5fa2017-08-31 15:47:31 -0400503
David Neto25ddfec2017-09-02 19:01:03 -0400504 if (caller_is_loop_header && (new_blocks->size() > 1)) {
David Netoefff5fa2017-08-31 15:47:31 -0400505 // Move the OpLoopMerge from the last block back to the first, where
David Neto25ddfec2017-09-02 19:01:03 -0400506 // it belongs.
David Netoefff5fa2017-08-31 15:47:31 -0400507 auto& first = new_blocks->front();
508 auto& last = new_blocks->back();
509 assert(first != last);
510
511 // Insert a modified copy of the loop merge into the first block.
512 auto loop_merge_itr = last->tail();
513 --loop_merge_itr;
514 assert(loop_merge_itr->opcode() == SpvOpLoopMerge);
dan sinclairc7da51a2018-07-12 15:14:43 -0400515 std::unique_ptr<Instruction> cp_inst(loop_merge_itr->Clone(context()));
David Neto25ddfec2017-09-02 19:01:03 -0400516 if (caller_is_single_block_loop) {
517 // Also, update its continue target to point to the last block.
518 cp_inst->SetInOperand(kSpvLoopMergeContinueTargetIdInIdx, {last->id()});
519 }
David Netoefff5fa2017-08-31 15:47:31 -0400520 first->tail().InsertBefore(std::move(cp_inst));
521
522 // Remove the loop merge from the last block.
Steven Perronbb7802b2017-10-13 14:25:21 -0400523 loop_merge_itr->RemoveFromList();
524 delete &*loop_merge_itr;
David Netoefff5fa2017-08-31 15:47:31 -0400525 }
526
Greg Fischer04fcc662016-11-10 10:11:50 -0700527 // Update block map given replacement blocks.
528 for (auto& blk : *new_blocks) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600529 id2block_[blk->id()] = &*blk;
Greg Fischer04fcc662016-11-10 10:11:50 -0700530 }
531}
532
dan sinclairc7da51a2018-07-12 15:14:43 -0400533bool InlinePass::IsInlinableFunctionCall(const Instruction* inst) {
David Netoceb1d4f2017-03-31 10:36:58 -0400534 if (inst->opcode() != SpvOp::SpvOpFunctionCall) return false;
GregFa107d342017-04-25 13:57:20 -0600535 const uint32_t calleeFnId =
536 inst->GetSingleWordOperand(kSpvFunctionCallFunctionId);
537 const auto ci = inlinable_.find(calleeFnId);
538 return ci != inlinable_.cend();
David Netoceb1d4f2017-03-31 10:36:58 -0400539}
540
GregFe28bd392017-08-01 17:20:13 -0600541void InlinePass::UpdateSucceedingPhis(
dan sinclairc7da51a2018-07-12 15:14:43 -0400542 std::vector<std::unique_ptr<BasicBlock>>& new_blocks) {
GregFe28bd392017-08-01 17:20:13 -0600543 const auto firstBlk = new_blocks.begin();
544 const auto lastBlk = new_blocks.end() - 1;
545 const uint32_t firstId = (*firstBlk)->id();
546 const uint32_t lastId = (*lastBlk)->id();
dan sinclairc7da51a2018-07-12 15:14:43 -0400547 const BasicBlock& const_last_block = *lastBlk->get();
David Neto87f9cfa2018-02-02 14:17:42 -0800548 const_last_block.ForEachSuccessorLabel(
549 [&firstId, &lastId, this](const uint32_t succ) {
dan sinclairc7da51a2018-07-12 15:14:43 -0400550 BasicBlock* sbp = this->id2block_[succ];
551 sbp->ForEachPhiInst([&firstId, &lastId](Instruction* phi) {
David Neto87f9cfa2018-02-02 14:17:42 -0800552 phi->ForEachInId([&firstId, &lastId](uint32_t* id) {
553 if (*id == firstId) *id = lastId;
554 });
555 });
GregFe28bd392017-08-01 17:20:13 -0600556 });
Greg Fischer04fcc662016-11-10 10:11:50 -0700557}
558
dan sinclairc7da51a2018-07-12 15:14:43 -0400559bool InlinePass::HasMultipleReturns(Function* func) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600560 bool seenReturn = false;
561 bool multipleReturns = false;
562 for (auto& blk : *func) {
563 auto terminal_ii = blk.cend();
564 --terminal_ii;
Diego Novillod2938e42017-11-08 12:40:02 -0500565 if (terminal_ii->opcode() == SpvOpReturn ||
Greg Fischerbba812f2017-05-04 20:55:53 -0600566 terminal_ii->opcode() == SpvOpReturnValue) {
567 if (seenReturn) {
568 multipleReturns = true;
569 break;
570 }
571 seenReturn = true;
572 }
573 }
574 return multipleReturns;
575}
576
dan sinclairc7da51a2018-07-12 15:14:43 -0400577void InlinePass::ComputeStructuredSuccessors(Function* func) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600578 // If header, make merge block first successor.
579 for (auto& blk : *func) {
Diego Novillofef669f2017-10-30 17:42:26 -0400580 uint32_t mbid = blk.MergeBlockIdIfAny();
581 if (mbid != 0) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600582 block2structured_succs_[&blk].push_back(id2block_[mbid]);
Diego Novillofef669f2017-10-30 17:42:26 -0400583 }
584
585 // Add true successors.
David Neto87f9cfa2018-02-02 14:17:42 -0800586 const auto& const_blk = blk;
587 const_blk.ForEachSuccessorLabel([&blk, this](const uint32_t sbid) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600588 block2structured_succs_[&blk].push_back(id2block_[sbid]);
589 });
590 }
591}
Diego Novillofef669f2017-10-30 17:42:26 -0400592
Greg Fischerbba812f2017-05-04 20:55:53 -0600593InlinePass::GetBlocksFunction InlinePass::StructuredSuccessorsFunction() {
dan sinclairc7da51a2018-07-12 15:14:43 -0400594 return [this](const BasicBlock* block) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600595 return &(block2structured_succs_[block]);
596 };
597}
598
dan sinclairc7da51a2018-07-12 15:14:43 -0400599bool InlinePass::HasNoReturnInLoop(Function* func) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600600 // If control not structured, do not do loop/return analysis
601 // TODO: Analyze returns in non-structured control flow
Steven Perron756b2772017-12-19 14:18:13 -0500602 if (!context()->get_feature_mgr()->HasCapability(SpvCapabilityShader))
603 return false;
Greg Fischerbba812f2017-05-04 20:55:53 -0600604 // Compute structured block order. This order has the property
605 // that dominators are before all blocks they dominate and merge blocks
606 // are after all blocks that are in the control constructs of their header.
607 ComputeStructuredSuccessors(func);
608 auto ignore_block = [](cbb_ptr) {};
609 auto ignore_edge = [](cbb_ptr, cbb_ptr) {};
dan sinclairc7da51a2018-07-12 15:14:43 -0400610 std::list<const BasicBlock*> structuredOrder;
611 CFA<BasicBlock>::DepthFirstTraversal(
Diego Novillod2938e42017-11-08 12:40:02 -0500612 &*func->begin(), StructuredSuccessorsFunction(), ignore_block,
613 [&](cbb_ptr b) { structuredOrder.push_front(b); }, ignore_edge);
Greg Fischerbba812f2017-05-04 20:55:53 -0600614 // Search for returns in loops. Only need to track outermost loop
615 bool return_in_loop = false;
616 uint32_t outerLoopMergeId = 0;
617 for (auto& blk : structuredOrder) {
618 // Exiting current outer loop
Diego Novillod2938e42017-11-08 12:40:02 -0500619 if (blk->id() == outerLoopMergeId) outerLoopMergeId = 0;
Greg Fischerbba812f2017-05-04 20:55:53 -0600620 // Return block
621 auto terminal_ii = blk->cend();
622 --terminal_ii;
Diego Novillod2938e42017-11-08 12:40:02 -0500623 if (terminal_ii->opcode() == SpvOpReturn ||
Greg Fischerbba812f2017-05-04 20:55:53 -0600624 terminal_ii->opcode() == SpvOpReturnValue) {
625 if (outerLoopMergeId != 0) {
626 return_in_loop = true;
627 break;
628 }
Diego Novillod2938e42017-11-08 12:40:02 -0500629 } else if (terminal_ii != blk->cbegin()) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600630 auto merge_ii = terminal_ii;
631 --merge_ii;
632 // Entering outermost loop
633 if (merge_ii->opcode() == SpvOpLoopMerge && outerLoopMergeId == 0)
Diego Novillod2938e42017-11-08 12:40:02 -0500634 outerLoopMergeId =
635 merge_ii->GetSingleWordOperand(kSpvLoopMergeMergeBlockId);
Greg Fischerbba812f2017-05-04 20:55:53 -0600636 }
637 }
638 return !return_in_loop;
639}
640
dan sinclairc7da51a2018-07-12 15:14:43 -0400641void InlinePass::AnalyzeReturns(Function* func) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600642 // Look for multiple returns
643 if (!HasMultipleReturns(func)) {
644 no_return_in_loop_.insert(func->result_id());
645 return;
646 }
David Neto2a1014b2017-08-09 14:59:04 -0400647 multi_return_funcs_.insert(func->result_id());
Greg Fischerbba812f2017-05-04 20:55:53 -0600648 // If multiple returns, see if any are in a loop
Diego Novillod2938e42017-11-08 12:40:02 -0500649 if (HasNoReturnInLoop(func)) no_return_in_loop_.insert(func->result_id());
Greg Fischerbba812f2017-05-04 20:55:53 -0600650}
651
dan sinclairc7da51a2018-07-12 15:14:43 -0400652bool InlinePass::IsInlinableFunction(Function* func) {
GregFa107d342017-04-25 13:57:20 -0600653 // We can only inline a function if it has blocks.
Diego Novillod2938e42017-11-08 12:40:02 -0500654 if (func->cbegin() == func->cend()) return false;
Greg Fischerbba812f2017-05-04 20:55:53 -0600655 // Do not inline functions with returns in loops. Currently early return
656 // functions are inlined by wrapping them in a one trip loop and implementing
657 // the returns as a branch to the loop's merge block. However, this can only
658 // done validly if the return was not in a loop in the original function.
659 // Also remember functions with multiple (early) returns.
660 AnalyzeReturns(func);
David Netoefff5fa2017-08-31 15:47:31 -0400661 return no_return_in_loop_.find(func->result_id()) !=
662 no_return_in_loop_.cend();
GregFa107d342017-04-25 13:57:20 -0600663}
664
dan sinclairf96b7f12018-07-12 09:08:45 -0400665void InlinePass::InitializeInline() {
Greg Fischerbba812f2017-05-04 20:55:53 -0600666 false_id_ = 0;
667
GregFe28bd392017-08-01 17:20:13 -0600668 // clear collections
Greg Fischer04fcc662016-11-10 10:11:50 -0700669 id2function_.clear();
670 id2block_.clear();
Greg Fischerbba812f2017-05-04 20:55:53 -0600671 block2structured_succs_.clear();
GregFa107d342017-04-25 13:57:20 -0600672 inlinable_.clear();
GregFe28bd392017-08-01 17:20:13 -0600673 no_return_in_loop_.clear();
David Neto2a1014b2017-08-09 14:59:04 -0400674 multi_return_funcs_.clear();
GregFe28bd392017-08-01 17:20:13 -0600675
Diego Novillo1040a952017-10-25 13:26:25 -0400676 for (auto& fn : *get_module()) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600677 // Initialize function and block maps.
Greg Fischer04fcc662016-11-10 10:11:50 -0700678 id2function_[fn.result_id()] = &fn;
679 for (auto& blk : fn) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600680 id2block_[blk.id()] = &blk;
Greg Fischer04fcc662016-11-10 10:11:50 -0700681 }
Greg Fischerbba812f2017-05-04 20:55:53 -0600682 // Compute inlinability
Diego Novillod2938e42017-11-08 12:40:02 -0500683 if (IsInlinableFunction(&fn)) inlinable_.insert(fn.result_id());
Greg Fischer04fcc662016-11-10 10:11:50 -0700684 }
Eleni Maria Stea045cc8f2018-03-21 11:15:56 +0200685}
Greg Fischer04fcc662016-11-10 10:11:50 -0700686
Diego Novillo1040a952017-10-25 13:26:25 -0400687InlinePass::InlinePass() {}
Greg Fischer04fcc662016-11-10 10:11:50 -0700688
Greg Fischer04fcc662016-11-10 10:11:50 -0700689} // namespace opt
690} // namespace spvtools