blob: a9b6928ad435e18f70aa957dc3a13b86245041b7 [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"
24#include "llvm/IR/DerivedTypes.h"
25#include "llvm/IR/Function.h"
26#include "llvm/IR/Instructions.h"
27#include "llvm/IR/Module.h"
28#include "llvm/Pass.h"
29#include "llvm/Support/raw_ostream.h"
David Netoab03f432017-11-03 17:00:44 -040030
David Neto482550a2018-03-24 05:21:07 -070031#include "clspv/Option.h"
32
David Netoab03f432017-11-03 17:00:44 -040033using namespace llvm;
34using std::string;
35
David Neto8e39bd12017-11-14 21:08:12 -050036#define DEBUG_TYPE "rewriteinserts"
David Netoab03f432017-11-03 17:00:44 -040037
David Netoab03f432017-11-03 17:00:44 -040038namespace {
39
40const char* kCompositeConstructFunctionPrefix = "clspv.composite_construct.";
41
42class RewriteInsertsPass : public ModulePass {
43 public:
44 static char ID;
45 RewriteInsertsPass() : ModulePass(ID) {}
46
47 bool runOnModule(Module &M) override;
48
49 private:
50 using InsertionVector = SmallVector<InsertValueInst *, 4>;
51
David Neto8e39bd12017-11-14 21:08:12 -050052 // Replaces chains of insertions that cover the entire value.
53 // Such a change always reduces the number of instructions, so
54 // we always perform these. Returns true if the module was modified.
55 bool ReplaceCompleteInsertionChains(Module &M);
56
57 // Replaces all InsertValue instructions, even if they aren't part
58 // of a complete insetion chain. Returns true if the module was modified.
59 bool ReplacePartialInsertions(Module &M);
60
61 // Load |values| and |chain| with the members of the struct value produced
62 // by a chain of InsertValue instructions ending with |iv|, and following
63 // the aggregate operand. Return the start of the chain: the aggregate
64 // value which is not an InsertValue instruction, or an InsertValue
65 // instruction which inserts a component that is replaced later in the
66 // chain. The |values| vector will match the order of struct members and
67 // is initialized to all nullptr members. The |chain| vector will list
68 // the chain of InsertValue instructions, listed in the order we discover
69 // them, e.g. begining with |iv|.
70 Value *LoadValuesEndingWithInsertion(InsertValueInst *iv,
71 std::vector<Value *> *values,
72 InsertionVector *chain) {
73 auto *structTy = dyn_cast<StructType>(iv->getType());
74 assert(structTy);
75 const auto numElems = structTy->getNumElements();
76
77 // Walk backward from the tail to an instruction we don't want to
78 // replace.
79 Value *frontier = iv;
80 while (auto *insertion = dyn_cast<InsertValueInst>(frontier)) {
81 chain->push_back(insertion);
82 // Only handle single-index insertions.
83 if (insertion->getNumIndices() == 1) {
84 // Try to replace this one.
85
86 unsigned index = insertion->getIndices()[0];
87 assert(index < numElems);
88 if ((*values)[index] != nullptr) {
89 // We already have a value for this slot. Stop now.
90 break;
91 }
92 (*values)[index] = insertion->getInsertedValueOperand();
93 frontier = insertion->getAggregateOperand();
94 } else {
95 break;
96 }
97 }
98 return frontier;
99 }
100
David Netoab03f432017-11-03 17:00:44 -0400101 // If this is the tail of a chain of InsertValueInst instructions
102 // that covers the entire composite, then return a small vector
103 // containing the insertion instructions, in member order.
104 // Otherwise returns nullptr. Only handle insertions into structs,
105 // not into arrays.
106 InsertionVector *CompleteInsertionChain(InsertValueInst *iv) {
107 if (iv->getNumIndices() == 1) {
Alan Bakerf8661412018-08-29 10:18:16 -0400108 auto numElems = GetNumElements(iv->getType());
109 if (numElems != 0) {
David Netoab03f432017-11-03 17:00:44 -0400110 // Only handle single-index insertions.
111 unsigned index = iv->getIndices()[0];
112 if (index + 1u != numElems) {
113 // Not the last in the chain.
114 return nullptr;
115 }
116 InsertionVector candidates(numElems, nullptr);
117 for (unsigned i = index;
118 iv->getNumIndices() == 1 && i == iv->getIndices()[0]; --i) {
119 // iv inserts the i'th member
120 candidates[i] = iv;
121
122 if (i == 0) {
123 // We're done!
124 return new InsertionVector(candidates);
125 }
126
127 if (InsertValueInst *agg =
128 dyn_cast<InsertValueInst>(iv->getAggregateOperand())) {
129 iv = agg;
130 } else {
131 // The chain is broken.
132 break;
133 }
134 }
135 }
136 }
137 return nullptr;
138 }
139
David Neto8e39bd12017-11-14 21:08:12 -0500140
David Netoab03f432017-11-03 17:00:44 -0400141 // Return the name for the wrap function for the given type.
142 string &WrapFunctionNameForType(Type *type) {
143 auto where = function_for_type_.find(type);
144 if (where == function_for_type_.end()) {
145 // Insert it.
146 auto &result = function_for_type_[type] =
147 string(kCompositeConstructFunctionPrefix) +
148 std::to_string(function_for_type_.size());
149 return result;
150 } else {
151 return where->second;
152 }
153 }
154
David Neto8e39bd12017-11-14 21:08:12 -0500155 // Get or create the composite construct function definition.
Alan Bakerf8661412018-08-29 10:18:16 -0400156 Function *GetConstructFunction(Module &M, CompositeType *constructed_type,
157 unsigned num_elements) {
David Neto8e39bd12017-11-14 21:08:12 -0500158 // Get or create the composite construct function definition.
159 const string &fn_name = WrapFunctionNameForType(constructed_type);
160 Function *fn = M.getFunction(fn_name);
161 if (!fn) {
162 // Make the function.
Alan Bakerf8661412018-08-29 10:18:16 -0400163 SmallVector<Type*, 16> elements;
164 for (unsigned i = 0; i != num_elements; ++i)
165 elements.push_back(constructed_type->getTypeAtIndex(i));
David Neto8e39bd12017-11-14 21:08:12 -0500166 FunctionType *fnTy = FunctionType::get(
Alan Bakerf8661412018-08-29 10:18:16 -0400167 constructed_type, elements, false);
David Neto8e39bd12017-11-14 21:08:12 -0500168 auto fn_constant = M.getOrInsertFunction(fn_name, fnTy);
169 fn = cast<Function>(fn_constant);
170 fn->addFnAttr(Attribute::ReadOnly);
David Neto8e39bd12017-11-14 21:08:12 -0500171 }
172 return fn;
173 }
174
Alan Bakerf8661412018-08-29 10:18:16 -0400175 // Returns the number of elements in the struct or array.
176 unsigned GetNumElements(Type *type) {
177 // CompositeType doesn't implement getNumElements(), but its inheritors
178 // do.
179 if (auto *struct_ty = dyn_cast<StructType>(type)) {
180 return struct_ty->getNumElements();
181 } else if (auto *array_ty = dyn_cast<ArrayType>(type)) {
182 return array_ty->getNumElements();
183 }
184 return 0;
185 }
186
David Netoab03f432017-11-03 17:00:44 -0400187 // Maps a loaded type to the name of the wrap function for that type.
188 DenseMap<Type *, string> function_for_type_;
189};
190} // namespace
191
192char RewriteInsertsPass::ID = 0;
193static RegisterPass<RewriteInsertsPass>
194 X("RewriteInserts",
195 "Rewrite chains of insertvalue to as composite-construction");
196
197namespace clspv {
198llvm::ModulePass *createRewriteInsertsPass() {
199 return new RewriteInsertsPass();
200}
201} // namespace clspv
202
203bool RewriteInsertsPass::runOnModule(Module &M) {
David Neto8e39bd12017-11-14 21:08:12 -0500204 bool Changed = ReplaceCompleteInsertionChains(M);
205
David Neto482550a2018-03-24 05:21:07 -0700206 if (clspv::Option::HackInserts()) {
David Neto8e39bd12017-11-14 21:08:12 -0500207 Changed |= ReplacePartialInsertions(M);
208 }
209
210 return Changed;
211}
212
213bool RewriteInsertsPass::ReplaceCompleteInsertionChains(Module &M) {
David Netoab03f432017-11-03 17:00:44 -0400214 bool Changed = false;
215
216 SmallVector<InsertionVector *, 16> WorkList;
217 for (Function &F : M) {
218 for (BasicBlock &BB : F) {
219 for (Instruction &I : BB) {
220 if (InsertValueInst *iv = dyn_cast<InsertValueInst>(&I)) {
221 if (InsertionVector *insertions = CompleteInsertionChain(iv)) {
222 WorkList.push_back(insertions);
223 }
224 }
225 }
226 }
227 }
228
229 if (WorkList.size() == 0) {
230 return Changed;
231 }
232
233 for (InsertionVector *insertions : WorkList) {
234 Changed = true;
235
236 // Gather the member values and types.
237 SmallVector<Value*, 4> values;
238 SmallVector<Type*, 4> types;
239 for (InsertValueInst* insert : *insertions) {
240 Value* value = insert->getInsertedValueOperand();
241 values.push_back(value);
242 types.push_back(value->getType());
243 }
244
Alan Bakerf8661412018-08-29 10:18:16 -0400245 CompositeType *resultTy = cast<CompositeType>(insertions->back()->getType());
246 unsigned numElems = GetNumElements(resultTy);
247 Function *fn = GetConstructFunction(M, resultTy, numElems);
David Netoab03f432017-11-03 17:00:44 -0400248
249 // Replace the chain.
250 auto call = CallInst::Create(fn, values);
251 call->insertAfter(insertions->back());
252 insertions->back()->replaceAllUsesWith(call);
253
254 // Remove the insertions if we can. Go from the tail back to
255 // the head, since the tail uses the previous insertion, etc.
256 for (auto iter = insertions->rbegin(), end = insertions->rend();
257 iter != end; ++iter) {
258 InsertValueInst *insertion = *iter;
259 if (!insertion->hasNUsesOrMore(1)) {
260 insertion->eraseFromParent();
261 }
262 }
263
264 delete insertions;
265 }
266
267 return Changed;
268}
David Neto8e39bd12017-11-14 21:08:12 -0500269
270bool RewriteInsertsPass::ReplacePartialInsertions(Module &M) {
271 bool Changed = false;
272
273 // First find candidates. Collect all InsertValue instructions
274 // into struct type, but track their interdependencies. To minimize
275 // the number of new instructions, generate a construction for each
276 // tail of an insertion chain.
277
278 UniqueVector<InsertValueInst *> insertions;
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 (iv->getType()->isStructTy()) {
284 insertions.insert(iv);
285 }
286 }
287 }
288 }
289 }
290
291 // Now count how many times each InsertValue is used by another InsertValue.
292 // The |num_uses| vector is indexed by the unique id that |insertions|
293 // assigns to it.
294 std::vector<unsigned> num_uses(insertions.size() + 1);
295 // Count from the user's perspective.
296 for (InsertValueInst *insertion : insertions) {
297 if (auto *agg =
298 dyn_cast<InsertValueInst>(insertion->getAggregateOperand())) {
299 ++(num_uses[insertions.idFor(agg)]);
300 }
301 }
302
303 // Proceed in rounds. Each round rewrites any chains ending with an
304 // insertion that is not used by another insertion.
305
306 // Get the first list of insertion tails.
307 InsertionVector WorkList;
308 for (InsertValueInst *insertion : insertions) {
309 if (num_uses[insertions.idFor(insertion)] == 0) {
310 WorkList.push_back(insertion);
311 }
312 }
313
314 // This records insertions in the order they should be removed.
315 // In this list, an insertion preceds any insertions it uses.
316 // (This is post-dominance order.)
317 InsertionVector ordered_candidates_for_removal;
318
319 // Proceed in rounds.
320 while (WorkList.size()) {
321 Changed = true;
322
323 // Record the list of tails for the next round.
324 InsertionVector NextRoundWorkList;
325
326 for (InsertValueInst *insertion : WorkList) {
327 // Rewrite |insertion|.
328
329 StructType *resultTy = cast<StructType>(insertion->getType());
330
331 const unsigned num_members = resultTy->getNumElements();
332 std::vector<Value*> members(num_members, nullptr);
333 InsertionVector chain;
334 // Gather the member values. Walk backward from the insertion.
335 Value *base = LoadValuesEndingWithInsertion(insertion, &members, &chain);
336
337 // Populate remaining entries in |values| by extracting elements
338 // from |base|. Only make a new extractvalue instruction if we can't
339 // make a constant or undef. New instructions are inserted before
340 // the insertion we plan to remove.
341 for (unsigned i = 0; i < num_members; ++i) {
342 if (!members[i]) {
343 Type *memberTy = resultTy->getTypeAtIndex(i);
344 if (isa<UndefValue>(base)) {
345 members[i] = UndefValue::get(memberTy);
346 } else if (const auto *caz = dyn_cast<ConstantAggregateZero>(base)) {
347 members[i] = caz->getElementValue(i);
348 } else if (const auto *ca = dyn_cast<ConstantAggregate>(base)) {
349 members[i] = ca->getOperand(i);
350 } else {
351 members[i] = ExtractValueInst::Create(base, {i}, "", insertion);
352 }
353 }
354 }
355
356 // Create the call. It's dominated by any extractions we've just
357 // created.
Alan Bakerf8661412018-08-29 10:18:16 -0400358 Function *construct_fn =
359 GetConstructFunction(M, resultTy, resultTy->getNumElements());
David Neto8e39bd12017-11-14 21:08:12 -0500360 auto *call = CallInst::Create(construct_fn, members, "", insertion);
361
362 // Disconnect this insertion. We'll remove it later.
363 insertion->replaceAllUsesWith(call);
364
365 // Trace backward through the chain, removing uses and deleting where
366 // we can. Stop at the first element that has a remaining use.
367 for (auto* chainElem : chain) {
368 if (chainElem->hasNUsesOrMore(1)) {
369 unsigned &use_count = num_uses[insertions.idFor(chainElem)];
370 assert(use_count > 0);
371 --use_count;
372 if (use_count == 0) {
373 NextRoundWorkList.push_back(chainElem);
374 }
375 break;
376 } else {
377 chainElem->eraseFromParent();
378 }
379 }
380 }
381 WorkList = std::move(NextRoundWorkList);
382 }
383
384 return Changed;
385}