blob: 7e3bc9ae9db42c1bbdf9930f7d17300588ce0e71 [file] [log] [blame]
David Netoab03f432017-11-03 17:00:44 -04001// Copyright 2017 The Clspv Authors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#include <string>
David Neto8e39bd12017-11-14 21:08:12 -050016#include <utility>
David Netoab03f432017-11-03 17:00:44 -040017
David Neto118188e2018-08-24 11:27:54 -040018#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/UniqueVector.h"
21#include "llvm/IR/Attributes.h"
22#include "llvm/IR/Constants.h"
23#include "llvm/IR/DerivedTypes.h"
David Neto118188e2018-08-24 11:27:54 -040024#include "llvm/IR/Function.h"
25#include "llvm/IR/Instructions.h"
26#include "llvm/IR/Module.h"
27#include "llvm/Pass.h"
28#include "llvm/Support/raw_ostream.h"
David Netoab03f432017-11-03 17:00:44 -040029
David Neto482550a2018-03-24 05:21:07 -070030#include "clspv/Option.h"
31
Diego Novilloa4c44fa2019-04-11 10:56:15 -040032#include "Passes.h"
33
David Netoab03f432017-11-03 17:00:44 -040034using namespace llvm;
35using std::string;
36
David Neto8e39bd12017-11-14 21:08:12 -050037#define DEBUG_TYPE "rewriteinserts"
David Netoab03f432017-11-03 17:00:44 -040038
David Netoab03f432017-11-03 17:00:44 -040039namespace {
40
Diego Novillo3cc8d7a2019-04-10 13:30:34 -040041const char *kCompositeConstructFunctionPrefix = "clspv.composite_construct.";
David Netoab03f432017-11-03 17:00:44 -040042
43class RewriteInsertsPass : public ModulePass {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -040044public:
David Netoab03f432017-11-03 17:00:44 -040045 static char ID;
46 RewriteInsertsPass() : ModulePass(ID) {}
47
48 bool runOnModule(Module &M) override;
49
Diego Novillo3cc8d7a2019-04-10 13:30:34 -040050private:
51 using InsertionVector = SmallVector<Instruction *, 4>;
David Netoab03f432017-11-03 17:00:44 -040052
Diego Novillo3cc8d7a2019-04-10 13:30:34 -040053 // Replaces chains of insertions that cover the entire value.
54 // Such a change always reduces the number of instructions, so
55 // we always perform these. Returns true if the module was modified.
56 bool ReplaceCompleteInsertionChains(Module &M);
David Neto8e39bd12017-11-14 21:08:12 -050057
Diego Novillo3cc8d7a2019-04-10 13:30:34 -040058 // Replaces all InsertValue instructions, even if they aren't part
59 // of a complete insetion chain. Returns true if the module was modified.
60 bool ReplacePartialInsertions(Module &M);
David Neto8e39bd12017-11-14 21:08:12 -050061
Diego Novillo3cc8d7a2019-04-10 13:30:34 -040062 // Load |values| and |chain| with the members of the struct value produced
63 // by a chain of InsertValue instructions ending with |iv|, and following
64 // the aggregate operand. Return the start of the chain: the aggregate
65 // value which is not an InsertValue instruction, or an InsertValue
66 // instruction which inserts a component that is replaced later in the
67 // chain. The |values| vector will match the order of struct members and
68 // is initialized to all nullptr members. The |chain| vector will list
69 // the chain of InsertValue instructions, listed in the order we discover
70 // them, e.g. begining with |iv|.
71 Value *LoadValuesEndingWithInsertion(InsertValueInst *iv,
72 std::vector<Value *> *values,
73 InsertionVector *chain) {
74 auto *structTy = dyn_cast<StructType>(iv->getType());
75 assert(structTy);
alan-baker4a757f62020-04-22 08:17:49 -040076 if (!structTy)
77 return nullptr;
David Neto8e39bd12017-11-14 21:08:12 -050078
Diego Novillo3cc8d7a2019-04-10 13:30:34 -040079 // Walk backward from the tail to an instruction we don't want to
80 // replace.
81 Value *frontier = iv;
82 while (auto *insertion = dyn_cast<InsertValueInst>(frontier)) {
83 chain->push_back(insertion);
84 // Only handle single-index insertions.
85 if (insertion->getNumIndices() == 1) {
86 // Try to replace this one.
David Neto8e39bd12017-11-14 21:08:12 -050087
Diego Novillo3cc8d7a2019-04-10 13:30:34 -040088 unsigned index = insertion->getIndices()[0];
alan-baker4a757f62020-04-22 08:17:49 -040089 assert(index < structTy->getNumElements());
Diego Novillo3cc8d7a2019-04-10 13:30:34 -040090 if ((*values)[index] != nullptr) {
91 // We already have a value for this slot. Stop now.
92 break;
93 }
94 (*values)[index] = insertion->getInsertedValueOperand();
95 frontier = insertion->getAggregateOperand();
96 } else {
97 break;
98 }
99 }
100 return frontier;
101 }
David Neto8e39bd12017-11-14 21:08:12 -0500102
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400103 // Returns the number of elements in the struct or array.
104 unsigned GetNumElements(Type *type) {
105 // CompositeType doesn't implement getNumElements(), but its inheritors
106 // do.
107 if (auto *struct_ty = dyn_cast<StructType>(type)) {
108 return struct_ty->getNumElements();
alan-baker8eb435a2020-04-08 00:42:06 -0400109 } else if (auto *array_ty = dyn_cast<ArrayType>(type)) {
110 return array_ty->getNumElements();
111 } else if (auto *vec_ty = dyn_cast<VectorType>(type)) {
112 return vec_ty->getNumElements();
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400113 }
114 return 0;
115 }
Alan Bakerabc935e2018-09-06 11:33:53 -0400116
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400117 // If this is the tail of a chain of InsertValueInst instructions
118 // that covers the entire composite, then return a small vector
119 // containing the insertion instructions, in member order.
120 // Otherwise returns nullptr.
121 InsertionVector *CompleteInsertionChain(InsertValueInst *iv) {
122 if (iv->getNumIndices() == 1) {
123 auto numElems = GetNumElements(iv->getType());
124 if (numElems != 0) {
125 // Only handle single-index insertions.
126 unsigned index = iv->getIndices()[0];
127 if (index + 1u != numElems) {
128 // Not the last in the chain.
129 return nullptr;
130 }
131 InsertionVector candidates(numElems, nullptr);
132 for (unsigned i = index;
133 iv->getNumIndices() == 1 && i == iv->getIndices()[0]; --i) {
134 // iv inserts the i'th member
135 candidates[i] = iv;
Alan Bakerabc935e2018-09-06 11:33:53 -0400136
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400137 if (i == 0) {
138 // We're done!
139 return new InsertionVector(candidates);
140 }
David Netoab03f432017-11-03 17:00:44 -0400141
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400142 if (InsertValueInst *agg =
143 dyn_cast<InsertValueInst>(iv->getAggregateOperand())) {
144 iv = agg;
145 } else {
146 // The chain is broken.
147 break;
148 }
149 }
150 }
151 }
152 return nullptr;
153 }
David Netoab03f432017-11-03 17:00:44 -0400154
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400155 // If this is the tail of a chain of InsertElementInst instructions
156 // that covers the entire vector, then return a small vector
157 // containing the insertion instructions, in member order.
158 // Otherwise returns nullptr. Only handle insertions into vectors.
159 InsertionVector *CompleteInsertionChain(InsertElementInst *ie) {
160 // Don't handle i8 vectors. Only <4 x i8> is supported and it is
161 // translated as i32. Only handle single-index insertions.
162 if (auto vec_ty = dyn_cast<VectorType>(ie->getType())) {
James Pricecf53df42020-04-20 14:41:24 -0400163 if (vec_ty->getElementType() == Type::getInt8Ty(ie->getContext())) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400164 return nullptr;
165 }
166 }
David Netoab03f432017-11-03 17:00:44 -0400167
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400168 // Only handle single-index insertions.
169 if (ie->getNumOperands() == 3) {
170 auto numElems = GetNumElements(ie->getType());
171 if (numElems != 0) {
172 if (auto *const_value = dyn_cast<ConstantInt>(ie->getOperand(2))) {
173 uint64_t index = const_value->getZExtValue();
174 if (index + 1u != numElems) {
175 // Not the last in the chain.
176 return nullptr;
177 }
178 InsertionVector candidates(numElems, nullptr);
179 Value *value = ie;
180 uint64_t i = index;
181 while (auto *insert = dyn_cast<InsertElementInst>(value)) {
182 if (insert->getNumOperands() != 3)
183 break;
184 if (auto *index_const =
185 dyn_cast<ConstantInt>(insert->getOperand(2))) {
186 if (i != index_const->getZExtValue())
187 break;
Alan Bakerabc935e2018-09-06 11:33:53 -0400188
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400189 candidates[i] = insert;
190 if (i == 0) {
191 // We're done!
192 return new InsertionVector(candidates);
193 }
Alan Bakerabc935e2018-09-06 11:33:53 -0400194
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400195 value = insert->getOperand(0);
196 --i;
197 } else {
198 break;
199 }
200 }
201 } else {
202 return nullptr;
203 }
204 }
205 }
206 return nullptr;
207 }
Alan Bakerabc935e2018-09-06 11:33:53 -0400208
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400209 // Return the name for the wrap function for the given type.
210 string &WrapFunctionNameForType(Type *type) {
211 auto where = function_for_type_.find(type);
212 if (where == function_for_type_.end()) {
213 // Insert it.
214 auto &result = function_for_type_[type] =
215 string(kCompositeConstructFunctionPrefix) +
216 std::to_string(function_for_type_.size());
217 return result;
218 } else {
219 return where->second;
220 }
221 }
David Neto8e39bd12017-11-14 21:08:12 -0500222
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400223 // Get or create the composite construct function definition.
alan-baker077517b2020-03-19 13:52:12 -0400224 Function *GetConstructFunction(Module &M, Type *constructed_type) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400225 // Get or create the composite construct function definition.
226 const string &fn_name = WrapFunctionNameForType(constructed_type);
227 Function *fn = M.getFunction(fn_name);
228 if (!fn) {
229 // Make the function.
230 SmallVector<Type *, 16> elements;
231 unsigned num_elements = GetNumElements(constructed_type);
alan-baker077517b2020-03-19 13:52:12 -0400232 if (auto struct_ty = dyn_cast<StructType>(constructed_type)) {
233 for (unsigned i = 0; i != num_elements; ++i)
234 elements.push_back(struct_ty->getTypeAtIndex(i));
alan-baker8eb435a2020-04-08 00:42:06 -0400235 } else if (isa<ArrayType>(constructed_type)) {
236 elements.resize(num_elements, constructed_type->getArrayElementType());
237 } else if (isa<VectorType>(constructed_type)) {
James Pricecf53df42020-04-20 14:41:24 -0400238 elements.resize(num_elements,
239 cast<VectorType>(constructed_type)->getElementType());
alan-baker077517b2020-03-19 13:52:12 -0400240 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400241 FunctionType *fnTy = FunctionType::get(constructed_type, elements, false);
242 auto fn_constant = M.getOrInsertFunction(fn_name, fnTy);
243 fn = cast<Function>(fn_constant.getCallee());
244 fn->addFnAttr(Attribute::ReadOnly);
245 }
246 return fn;
247 }
David Netoab03f432017-11-03 17:00:44 -0400248
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400249 // Maps a loaded type to the name of the wrap function for that type.
250 DenseMap<Type *, string> function_for_type_;
David Netoab03f432017-11-03 17:00:44 -0400251};
252} // namespace
253
254char RewriteInsertsPass::ID = 0;
Diego Novilloa4c44fa2019-04-11 10:56:15 -0400255INITIALIZE_PASS(RewriteInsertsPass, "RewriteInserts",
256 "Rewrite chains of insertvalue to as composite-construction",
257 false, false)
David Netoab03f432017-11-03 17:00:44 -0400258
259namespace clspv {
260llvm::ModulePass *createRewriteInsertsPass() {
261 return new RewriteInsertsPass();
262}
263} // namespace clspv
264
265bool RewriteInsertsPass::runOnModule(Module &M) {
David Neto8e39bd12017-11-14 21:08:12 -0500266 bool Changed = ReplaceCompleteInsertionChains(M);
267
David Neto482550a2018-03-24 05:21:07 -0700268 if (clspv::Option::HackInserts()) {
David Neto8e39bd12017-11-14 21:08:12 -0500269 Changed |= ReplacePartialInsertions(M);
270 }
271
272 return Changed;
273}
274
275bool RewriteInsertsPass::ReplaceCompleteInsertionChains(Module &M) {
David Netoab03f432017-11-03 17:00:44 -0400276 bool Changed = false;
277
278 SmallVector<InsertionVector *, 16> WorkList;
279 for (Function &F : M) {
280 for (BasicBlock &BB : F) {
281 for (Instruction &I : BB) {
282 if (InsertValueInst *iv = dyn_cast<InsertValueInst>(&I)) {
283 if (InsertionVector *insertions = CompleteInsertionChain(iv)) {
284 WorkList.push_back(insertions);
285 }
Alan Bakerabc935e2018-09-06 11:33:53 -0400286 } else if (InsertElementInst *ie = dyn_cast<InsertElementInst>(&I)) {
287 if (InsertionVector *insertions = CompleteInsertionChain(ie)) {
288 WorkList.push_back(insertions);
289 }
David Netoab03f432017-11-03 17:00:44 -0400290 }
291 }
292 }
293 }
294
295 if (WorkList.size() == 0) {
296 return Changed;
297 }
298
299 for (InsertionVector *insertions : WorkList) {
300 Changed = true;
301
302 // Gather the member values and types.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400303 SmallVector<Value *, 4> values;
304 for (Instruction *inst : *insertions) {
Alan Bakerabc935e2018-09-06 11:33:53 -0400305 if (auto *insert_value = dyn_cast<InsertValueInst>(inst)) {
306 values.push_back(insert_value->getInsertedValueOperand());
307 } else if (auto *insert_element = dyn_cast<InsertElementInst>(inst)) {
308 values.push_back(insert_element->getOperand(1));
309 } else {
310 llvm_unreachable("Unhandled insertion instruction");
311 }
David Netoab03f432017-11-03 17:00:44 -0400312 }
313
alan-baker077517b2020-03-19 13:52:12 -0400314 auto *resultTy = insertions->back()->getType();
Alan Bakerabc935e2018-09-06 11:33:53 -0400315 Function *fn = GetConstructFunction(M, resultTy);
David Netoab03f432017-11-03 17:00:44 -0400316
317 // Replace the chain.
318 auto call = CallInst::Create(fn, values);
319 call->insertAfter(insertions->back());
320 insertions->back()->replaceAllUsesWith(call);
321
322 // Remove the insertions if we can. Go from the tail back to
323 // the head, since the tail uses the previous insertion, etc.
324 for (auto iter = insertions->rbegin(), end = insertions->rend();
325 iter != end; ++iter) {
Alan Bakerabc935e2018-09-06 11:33:53 -0400326 Instruction *insertion = *iter;
David Netoab03f432017-11-03 17:00:44 -0400327 if (!insertion->hasNUsesOrMore(1)) {
328 insertion->eraseFromParent();
329 }
330 }
331
332 delete insertions;
333 }
334
335 return Changed;
336}
David Neto8e39bd12017-11-14 21:08:12 -0500337
338bool RewriteInsertsPass::ReplacePartialInsertions(Module &M) {
339 bool Changed = false;
340
341 // First find candidates. Collect all InsertValue instructions
342 // into struct type, but track their interdependencies. To minimize
343 // the number of new instructions, generate a construction for each
344 // tail of an insertion chain.
345
346 UniqueVector<InsertValueInst *> insertions;
347 for (Function &F : M) {
348 for (BasicBlock &BB : F) {
349 for (Instruction &I : BB) {
350 if (InsertValueInst *iv = dyn_cast<InsertValueInst>(&I)) {
351 if (iv->getType()->isStructTy()) {
352 insertions.insert(iv);
353 }
354 }
355 }
356 }
357 }
358
359 // Now count how many times each InsertValue is used by another InsertValue.
360 // The |num_uses| vector is indexed by the unique id that |insertions|
361 // assigns to it.
362 std::vector<unsigned> num_uses(insertions.size() + 1);
363 // Count from the user's perspective.
364 for (InsertValueInst *insertion : insertions) {
365 if (auto *agg =
366 dyn_cast<InsertValueInst>(insertion->getAggregateOperand())) {
367 ++(num_uses[insertions.idFor(agg)]);
368 }
369 }
370
371 // Proceed in rounds. Each round rewrites any chains ending with an
372 // insertion that is not used by another insertion.
373
374 // Get the first list of insertion tails.
375 InsertionVector WorkList;
376 for (InsertValueInst *insertion : insertions) {
377 if (num_uses[insertions.idFor(insertion)] == 0) {
378 WorkList.push_back(insertion);
379 }
380 }
381
382 // This records insertions in the order they should be removed.
383 // In this list, an insertion preceds any insertions it uses.
384 // (This is post-dominance order.)
385 InsertionVector ordered_candidates_for_removal;
386
387 // Proceed in rounds.
388 while (WorkList.size()) {
389 Changed = true;
390
391 // Record the list of tails for the next round.
392 InsertionVector NextRoundWorkList;
393
Alan Bakerabc935e2018-09-06 11:33:53 -0400394 for (Instruction *inst : WorkList) {
395 InsertValueInst *insertion = cast<InsertValueInst>(inst);
David Neto8e39bd12017-11-14 21:08:12 -0500396 // Rewrite |insertion|.
397
398 StructType *resultTy = cast<StructType>(insertion->getType());
399
400 const unsigned num_members = resultTy->getNumElements();
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400401 std::vector<Value *> members(num_members, nullptr);
David Neto8e39bd12017-11-14 21:08:12 -0500402 InsertionVector chain;
403 // Gather the member values. Walk backward from the insertion.
404 Value *base = LoadValuesEndingWithInsertion(insertion, &members, &chain);
405
406 // Populate remaining entries in |values| by extracting elements
407 // from |base|. Only make a new extractvalue instruction if we can't
408 // make a constant or undef. New instructions are inserted before
409 // the insertion we plan to remove.
410 for (unsigned i = 0; i < num_members; ++i) {
411 if (!members[i]) {
412 Type *memberTy = resultTy->getTypeAtIndex(i);
413 if (isa<UndefValue>(base)) {
414 members[i] = UndefValue::get(memberTy);
415 } else if (const auto *caz = dyn_cast<ConstantAggregateZero>(base)) {
416 members[i] = caz->getElementValue(i);
417 } else if (const auto *ca = dyn_cast<ConstantAggregate>(base)) {
418 members[i] = ca->getOperand(i);
419 } else {
420 members[i] = ExtractValueInst::Create(base, {i}, "", insertion);
421 }
422 }
423 }
424
425 // Create the call. It's dominated by any extractions we've just
426 // created.
Alan Bakerabc935e2018-09-06 11:33:53 -0400427 Function *construct_fn = GetConstructFunction(M, resultTy);
David Neto8e39bd12017-11-14 21:08:12 -0500428 auto *call = CallInst::Create(construct_fn, members, "", insertion);
429
430 // Disconnect this insertion. We'll remove it later.
431 insertion->replaceAllUsesWith(call);
432
433 // Trace backward through the chain, removing uses and deleting where
434 // we can. Stop at the first element that has a remaining use.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400435 for (auto *chainElem : chain) {
David Neto8e39bd12017-11-14 21:08:12 -0500436 if (chainElem->hasNUsesOrMore(1)) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400437 unsigned &use_count =
438 num_uses[insertions.idFor(cast<InsertValueInst>(chainElem))];
David Neto8e39bd12017-11-14 21:08:12 -0500439 assert(use_count > 0);
440 --use_count;
441 if (use_count == 0) {
442 NextRoundWorkList.push_back(chainElem);
443 }
444 break;
445 } else {
446 chainElem->eraseFromParent();
447 }
448 }
449 }
450 WorkList = std::move(NextRoundWorkList);
451 }
452
453 return Changed;
454}