blob: 2ec1260bb4320e646993582bc450f82eb0b1bdaf [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);
76 const auto numElems = structTy->getNumElements();
David Neto8e39bd12017-11-14 21:08:12 -050077
Diego Novillo3cc8d7a2019-04-10 13:30:34 -040078 // Walk backward from the tail to an instruction we don't want to
79 // replace.
80 Value *frontier = iv;
81 while (auto *insertion = dyn_cast<InsertValueInst>(frontier)) {
82 chain->push_back(insertion);
83 // Only handle single-index insertions.
84 if (insertion->getNumIndices() == 1) {
85 // Try to replace this one.
David Neto8e39bd12017-11-14 21:08:12 -050086
Diego Novillo3cc8d7a2019-04-10 13:30:34 -040087 unsigned index = insertion->getIndices()[0];
88 assert(index < numElems);
89 if ((*values)[index] != nullptr) {
90 // We already have a value for this slot. Stop now.
91 break;
92 }
93 (*values)[index] = insertion->getInsertedValueOperand();
94 frontier = insertion->getAggregateOperand();
95 } else {
96 break;
97 }
98 }
99 return frontier;
100 }
David Neto8e39bd12017-11-14 21:08:12 -0500101
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400102 // Returns the number of elements in the struct or array.
103 unsigned GetNumElements(Type *type) {
104 // CompositeType doesn't implement getNumElements(), but its inheritors
105 // do.
106 if (auto *struct_ty = dyn_cast<StructType>(type)) {
107 return struct_ty->getNumElements();
alan-baker8eb435a2020-04-08 00:42:06 -0400108 } else if (auto *array_ty = dyn_cast<ArrayType>(type)) {
109 return array_ty->getNumElements();
110 } else if (auto *vec_ty = dyn_cast<VectorType>(type)) {
111 return vec_ty->getNumElements();
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400112 }
113 return 0;
114 }
Alan Bakerabc935e2018-09-06 11:33:53 -0400115
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400116 // If this is the tail of a chain of InsertValueInst instructions
117 // that covers the entire composite, then return a small vector
118 // containing the insertion instructions, in member order.
119 // Otherwise returns nullptr.
120 InsertionVector *CompleteInsertionChain(InsertValueInst *iv) {
121 if (iv->getNumIndices() == 1) {
122 auto numElems = GetNumElements(iv->getType());
123 if (numElems != 0) {
124 // Only handle single-index insertions.
125 unsigned index = iv->getIndices()[0];
126 if (index + 1u != numElems) {
127 // Not the last in the chain.
128 return nullptr;
129 }
130 InsertionVector candidates(numElems, nullptr);
131 for (unsigned i = index;
132 iv->getNumIndices() == 1 && i == iv->getIndices()[0]; --i) {
133 // iv inserts the i'th member
134 candidates[i] = iv;
Alan Bakerabc935e2018-09-06 11:33:53 -0400135
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400136 if (i == 0) {
137 // We're done!
138 return new InsertionVector(candidates);
139 }
David Netoab03f432017-11-03 17:00:44 -0400140
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400141 if (InsertValueInst *agg =
142 dyn_cast<InsertValueInst>(iv->getAggregateOperand())) {
143 iv = agg;
144 } else {
145 // The chain is broken.
146 break;
147 }
148 }
149 }
150 }
151 return nullptr;
152 }
David Netoab03f432017-11-03 17:00:44 -0400153
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400154 // If this is the tail of a chain of InsertElementInst instructions
155 // that covers the entire vector, then return a small vector
156 // containing the insertion instructions, in member order.
157 // Otherwise returns nullptr. Only handle insertions into vectors.
158 InsertionVector *CompleteInsertionChain(InsertElementInst *ie) {
159 // Don't handle i8 vectors. Only <4 x i8> is supported and it is
160 // translated as i32. Only handle single-index insertions.
161 if (auto vec_ty = dyn_cast<VectorType>(ie->getType())) {
162 if (vec_ty->getVectorElementType() == Type::getInt8Ty(ie->getContext())) {
163 return nullptr;
164 }
165 }
David Netoab03f432017-11-03 17:00:44 -0400166
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400167 // Only handle single-index insertions.
168 if (ie->getNumOperands() == 3) {
169 auto numElems = GetNumElements(ie->getType());
170 if (numElems != 0) {
171 if (auto *const_value = dyn_cast<ConstantInt>(ie->getOperand(2))) {
172 uint64_t index = const_value->getZExtValue();
173 if (index + 1u != numElems) {
174 // Not the last in the chain.
175 return nullptr;
176 }
177 InsertionVector candidates(numElems, nullptr);
178 Value *value = ie;
179 uint64_t i = index;
180 while (auto *insert = dyn_cast<InsertElementInst>(value)) {
181 if (insert->getNumOperands() != 3)
182 break;
183 if (auto *index_const =
184 dyn_cast<ConstantInt>(insert->getOperand(2))) {
185 if (i != index_const->getZExtValue())
186 break;
Alan Bakerabc935e2018-09-06 11:33:53 -0400187
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400188 candidates[i] = insert;
189 if (i == 0) {
190 // We're done!
191 return new InsertionVector(candidates);
192 }
Alan Bakerabc935e2018-09-06 11:33:53 -0400193
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400194 value = insert->getOperand(0);
195 --i;
196 } else {
197 break;
198 }
199 }
200 } else {
201 return nullptr;
202 }
203 }
204 }
205 return nullptr;
206 }
Alan Bakerabc935e2018-09-06 11:33:53 -0400207
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400208 // Return the name for the wrap function for the given type.
209 string &WrapFunctionNameForType(Type *type) {
210 auto where = function_for_type_.find(type);
211 if (where == function_for_type_.end()) {
212 // Insert it.
213 auto &result = function_for_type_[type] =
214 string(kCompositeConstructFunctionPrefix) +
215 std::to_string(function_for_type_.size());
216 return result;
217 } else {
218 return where->second;
219 }
220 }
David Neto8e39bd12017-11-14 21:08:12 -0500221
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400222 // Get or create the composite construct function definition.
alan-baker077517b2020-03-19 13:52:12 -0400223 Function *GetConstructFunction(Module &M, Type *constructed_type) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400224 // Get or create the composite construct function definition.
225 const string &fn_name = WrapFunctionNameForType(constructed_type);
226 Function *fn = M.getFunction(fn_name);
227 if (!fn) {
228 // Make the function.
229 SmallVector<Type *, 16> elements;
230 unsigned num_elements = GetNumElements(constructed_type);
alan-baker077517b2020-03-19 13:52:12 -0400231 if (auto struct_ty = dyn_cast<StructType>(constructed_type)) {
232 for (unsigned i = 0; i != num_elements; ++i)
233 elements.push_back(struct_ty->getTypeAtIndex(i));
alan-baker8eb435a2020-04-08 00:42:06 -0400234 } else if (isa<ArrayType>(constructed_type)) {
235 elements.resize(num_elements, constructed_type->getArrayElementType());
236 } else if (isa<VectorType>(constructed_type)) {
237 elements.resize(num_elements, constructed_type->getVectorElementType());
alan-baker077517b2020-03-19 13:52:12 -0400238 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400239 FunctionType *fnTy = FunctionType::get(constructed_type, elements, false);
240 auto fn_constant = M.getOrInsertFunction(fn_name, fnTy);
241 fn = cast<Function>(fn_constant.getCallee());
242 fn->addFnAttr(Attribute::ReadOnly);
243 }
244 return fn;
245 }
David Netoab03f432017-11-03 17:00:44 -0400246
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400247 // Maps a loaded type to the name of the wrap function for that type.
248 DenseMap<Type *, string> function_for_type_;
David Netoab03f432017-11-03 17:00:44 -0400249};
250} // namespace
251
252char RewriteInsertsPass::ID = 0;
Diego Novilloa4c44fa2019-04-11 10:56:15 -0400253INITIALIZE_PASS(RewriteInsertsPass, "RewriteInserts",
254 "Rewrite chains of insertvalue to as composite-construction",
255 false, false)
David Netoab03f432017-11-03 17:00:44 -0400256
257namespace clspv {
258llvm::ModulePass *createRewriteInsertsPass() {
259 return new RewriteInsertsPass();
260}
261} // namespace clspv
262
263bool RewriteInsertsPass::runOnModule(Module &M) {
David Neto8e39bd12017-11-14 21:08:12 -0500264 bool Changed = ReplaceCompleteInsertionChains(M);
265
David Neto482550a2018-03-24 05:21:07 -0700266 if (clspv::Option::HackInserts()) {
David Neto8e39bd12017-11-14 21:08:12 -0500267 Changed |= ReplacePartialInsertions(M);
268 }
269
270 return Changed;
271}
272
273bool RewriteInsertsPass::ReplaceCompleteInsertionChains(Module &M) {
David Netoab03f432017-11-03 17:00:44 -0400274 bool Changed = false;
275
276 SmallVector<InsertionVector *, 16> WorkList;
277 for (Function &F : M) {
278 for (BasicBlock &BB : F) {
279 for (Instruction &I : BB) {
280 if (InsertValueInst *iv = dyn_cast<InsertValueInst>(&I)) {
281 if (InsertionVector *insertions = CompleteInsertionChain(iv)) {
282 WorkList.push_back(insertions);
283 }
Alan Bakerabc935e2018-09-06 11:33:53 -0400284 } else if (InsertElementInst *ie = dyn_cast<InsertElementInst>(&I)) {
285 if (InsertionVector *insertions = CompleteInsertionChain(ie)) {
286 WorkList.push_back(insertions);
287 }
David Netoab03f432017-11-03 17:00:44 -0400288 }
289 }
290 }
291 }
292
293 if (WorkList.size() == 0) {
294 return Changed;
295 }
296
297 for (InsertionVector *insertions : WorkList) {
298 Changed = true;
299
300 // Gather the member values and types.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400301 SmallVector<Value *, 4> values;
302 for (Instruction *inst : *insertions) {
Alan Bakerabc935e2018-09-06 11:33:53 -0400303 if (auto *insert_value = dyn_cast<InsertValueInst>(inst)) {
304 values.push_back(insert_value->getInsertedValueOperand());
305 } else if (auto *insert_element = dyn_cast<InsertElementInst>(inst)) {
306 values.push_back(insert_element->getOperand(1));
307 } else {
308 llvm_unreachable("Unhandled insertion instruction");
309 }
David Netoab03f432017-11-03 17:00:44 -0400310 }
311
alan-baker077517b2020-03-19 13:52:12 -0400312 auto *resultTy = insertions->back()->getType();
Alan Bakerabc935e2018-09-06 11:33:53 -0400313 Function *fn = GetConstructFunction(M, resultTy);
David Netoab03f432017-11-03 17:00:44 -0400314
315 // Replace the chain.
316 auto call = CallInst::Create(fn, values);
317 call->insertAfter(insertions->back());
318 insertions->back()->replaceAllUsesWith(call);
319
320 // Remove the insertions if we can. Go from the tail back to
321 // the head, since the tail uses the previous insertion, etc.
322 for (auto iter = insertions->rbegin(), end = insertions->rend();
323 iter != end; ++iter) {
Alan Bakerabc935e2018-09-06 11:33:53 -0400324 Instruction *insertion = *iter;
David Netoab03f432017-11-03 17:00:44 -0400325 if (!insertion->hasNUsesOrMore(1)) {
326 insertion->eraseFromParent();
327 }
328 }
329
330 delete insertions;
331 }
332
333 return Changed;
334}
David Neto8e39bd12017-11-14 21:08:12 -0500335
336bool RewriteInsertsPass::ReplacePartialInsertions(Module &M) {
337 bool Changed = false;
338
339 // First find candidates. Collect all InsertValue instructions
340 // into struct type, but track their interdependencies. To minimize
341 // the number of new instructions, generate a construction for each
342 // tail of an insertion chain.
343
344 UniqueVector<InsertValueInst *> insertions;
345 for (Function &F : M) {
346 for (BasicBlock &BB : F) {
347 for (Instruction &I : BB) {
348 if (InsertValueInst *iv = dyn_cast<InsertValueInst>(&I)) {
349 if (iv->getType()->isStructTy()) {
350 insertions.insert(iv);
351 }
352 }
353 }
354 }
355 }
356
357 // Now count how many times each InsertValue is used by another InsertValue.
358 // The |num_uses| vector is indexed by the unique id that |insertions|
359 // assigns to it.
360 std::vector<unsigned> num_uses(insertions.size() + 1);
361 // Count from the user's perspective.
362 for (InsertValueInst *insertion : insertions) {
363 if (auto *agg =
364 dyn_cast<InsertValueInst>(insertion->getAggregateOperand())) {
365 ++(num_uses[insertions.idFor(agg)]);
366 }
367 }
368
369 // Proceed in rounds. Each round rewrites any chains ending with an
370 // insertion that is not used by another insertion.
371
372 // Get the first list of insertion tails.
373 InsertionVector WorkList;
374 for (InsertValueInst *insertion : insertions) {
375 if (num_uses[insertions.idFor(insertion)] == 0) {
376 WorkList.push_back(insertion);
377 }
378 }
379
380 // This records insertions in the order they should be removed.
381 // In this list, an insertion preceds any insertions it uses.
382 // (This is post-dominance order.)
383 InsertionVector ordered_candidates_for_removal;
384
385 // Proceed in rounds.
386 while (WorkList.size()) {
387 Changed = true;
388
389 // Record the list of tails for the next round.
390 InsertionVector NextRoundWorkList;
391
Alan Bakerabc935e2018-09-06 11:33:53 -0400392 for (Instruction *inst : WorkList) {
393 InsertValueInst *insertion = cast<InsertValueInst>(inst);
David Neto8e39bd12017-11-14 21:08:12 -0500394 // Rewrite |insertion|.
395
396 StructType *resultTy = cast<StructType>(insertion->getType());
397
398 const unsigned num_members = resultTy->getNumElements();
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400399 std::vector<Value *> members(num_members, nullptr);
David Neto8e39bd12017-11-14 21:08:12 -0500400 InsertionVector chain;
401 // Gather the member values. Walk backward from the insertion.
402 Value *base = LoadValuesEndingWithInsertion(insertion, &members, &chain);
403
404 // Populate remaining entries in |values| by extracting elements
405 // from |base|. Only make a new extractvalue instruction if we can't
406 // make a constant or undef. New instructions are inserted before
407 // the insertion we plan to remove.
408 for (unsigned i = 0; i < num_members; ++i) {
409 if (!members[i]) {
410 Type *memberTy = resultTy->getTypeAtIndex(i);
411 if (isa<UndefValue>(base)) {
412 members[i] = UndefValue::get(memberTy);
413 } else if (const auto *caz = dyn_cast<ConstantAggregateZero>(base)) {
414 members[i] = caz->getElementValue(i);
415 } else if (const auto *ca = dyn_cast<ConstantAggregate>(base)) {
416 members[i] = ca->getOperand(i);
417 } else {
418 members[i] = ExtractValueInst::Create(base, {i}, "", insertion);
419 }
420 }
421 }
422
423 // Create the call. It's dominated by any extractions we've just
424 // created.
Alan Bakerabc935e2018-09-06 11:33:53 -0400425 Function *construct_fn = GetConstructFunction(M, resultTy);
David Neto8e39bd12017-11-14 21:08:12 -0500426 auto *call = CallInst::Create(construct_fn, members, "", insertion);
427
428 // Disconnect this insertion. We'll remove it later.
429 insertion->replaceAllUsesWith(call);
430
431 // Trace backward through the chain, removing uses and deleting where
432 // we can. Stop at the first element that has a remaining use.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400433 for (auto *chainElem : chain) {
David Neto8e39bd12017-11-14 21:08:12 -0500434 if (chainElem->hasNUsesOrMore(1)) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400435 unsigned &use_count =
436 num_uses[insertions.idFor(cast<InsertValueInst>(chainElem))];
David Neto8e39bd12017-11-14 21:08:12 -0500437 assert(use_count > 0);
438 --use_count;
439 if (use_count == 0) {
440 NextRoundWorkList.push_back(chainElem);
441 }
442 break;
443 } else {
444 chainElem->eraseFromParent();
445 }
446 }
447 }
448 WorkList = std::move(NextRoundWorkList);
449 }
450
451 return Changed;
452}