Coverage Report

Created: 2018-04-24 22:41

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/polly/lib/CodeGen/BlockGenerators.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- BlockGenerators.cpp - Generate code for statements -----*- C++ -*-===//
2
//
3
//                     The LLVM Compiler Infrastructure
4
//
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
7
//
8
//===----------------------------------------------------------------------===//
9
//
10
// This file implements the BlockGenerator and VectorBlockGenerator classes,
11
// which generate sequential code and vectorized code for a polyhedral
12
// statement, respectively.
13
//
14
//===----------------------------------------------------------------------===//
15
16
#include "polly/CodeGen/BlockGenerators.h"
17
#include "polly/CodeGen/CodeGeneration.h"
18
#include "polly/CodeGen/IslExprBuilder.h"
19
#include "polly/CodeGen/RuntimeDebugBuilder.h"
20
#include "polly/Options.h"
21
#include "polly/ScopInfo.h"
22
#include "polly/Support/GICHelper.h"
23
#include "polly/Support/SCEVValidator.h"
24
#include "polly/Support/ScopHelper.h"
25
#include "polly/Support/VirtualInstruction.h"
26
#include "llvm/Analysis/LoopInfo.h"
27
#include "llvm/Analysis/RegionInfo.h"
28
#include "llvm/Analysis/ScalarEvolution.h"
29
#include "llvm/Analysis/Utils/Local.h"
30
#include "llvm/IR/IntrinsicInst.h"
31
#include "llvm/IR/Module.h"
32
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
33
#include "isl/aff.h"
34
#include "isl/ast.h"
35
#include "isl/ast_build.h"
36
#include "isl/set.h"
37
#include <deque>
38
39
using namespace llvm;
40
using namespace polly;
41
42
static cl::opt<bool> Aligned("enable-polly-aligned",
43
                             cl::desc("Assumed aligned memory accesses."),
44
                             cl::Hidden, cl::init(false), cl::ZeroOrMore,
45
                             cl::cat(PollyCategory));
46
47
bool PollyDebugPrinting;
48
static cl::opt<bool, true> DebugPrintingX(
49
    "polly-codegen-add-debug-printing",
50
    cl::desc("Add printf calls that show the values loaded/stored."),
51
    cl::location(PollyDebugPrinting), cl::Hidden, cl::init(false),
52
    cl::ZeroOrMore, cl::cat(PollyCategory));
53
54
BlockGenerator::BlockGenerator(
55
    PollyIRBuilder &B, LoopInfo &LI, ScalarEvolution &SE, DominatorTree &DT,
56
    AllocaMapTy &ScalarMap, EscapeUsersAllocaMapTy &EscapeMap,
57
    ValueMapT &GlobalMap, IslExprBuilder *ExprBuilder, BasicBlock *StartBlock)
58
    : Builder(B), LI(LI), SE(SE), ExprBuilder(ExprBuilder), DT(DT),
59
      EntryBB(nullptr), ScalarMap(ScalarMap), EscapeMap(EscapeMap),
60
292
      GlobalMap(GlobalMap), StartBlock(StartBlock) {}
61
62
Value *BlockGenerator::trySynthesizeNewValue(ScopStmt &Stmt, Value *Old,
63
                                             ValueMapT &BBMap,
64
                                             LoopToScevMapT &LTS,
65
670
                                             Loop *L) const {
66
670
  if (!SE.isSCEVable(Old->getType()))
67
0
    return nullptr;
68
670
69
670
  const SCEV *Scev = SE.getSCEVAtScope(Old, L);
70
670
  if (!Scev)
71
0
    return nullptr;
72
670
73
670
  if (isa<SCEVCouldNotCompute>(Scev))
74
0
    return nullptr;
75
670
76
670
  const SCEV *NewScev = SCEVLoopAddRecRewriter::rewrite(Scev, LTS, SE);
77
670
  ValueMapT VTV;
78
670
  VTV.insert(BBMap.begin(), BBMap.end());
79
670
  VTV.insert(GlobalMap.begin(), GlobalMap.end());
80
670
81
670
  Scop &S = *Stmt.getParent();
82
670
  const DataLayout &DL = S.getFunction().getParent()->getDataLayout();
83
670
  auto IP = Builder.GetInsertPoint();
84
670
85
670
  assert(IP != Builder.GetInsertBlock()->end() &&
86
670
         "Only instructions can be insert points for SCEVExpander");
87
670
  Value *Expanded =
88
670
      expandCodeFor(S, SE, DL, "polly", NewScev, Old->getType(), &*IP, &VTV,
89
670
                    StartBlock->getSinglePredecessor());
90
670
91
670
  BBMap[Old] = Expanded;
92
670
  return Expanded;
93
670
}
94
95
Value *BlockGenerator::getNewValue(ScopStmt &Stmt, Value *Old, ValueMapT &BBMap,
96
2.19k
                                   LoopToScevMapT &LTS, Loop *L) const {
97
2.19k
98
2.19k
  auto lookupGlobally = [this](Value *Old) -> Value * {
99
1.19k
    Value *New = GlobalMap.lookup(Old);
100
1.19k
    if (!New)
101
1.14k
      return nullptr;
102
53
103
53
    // Required by:
104
53
    // * Isl/CodeGen/OpenMP/invariant_base_pointer_preloaded.ll
105
53
    // * Isl/CodeGen/OpenMP/invariant_base_pointer_preloaded_different_bb.ll
106
53
    // * Isl/CodeGen/OpenMP/invariant_base_pointer_preloaded_pass_only_needed.ll
107
53
    // * Isl/CodeGen/OpenMP/invariant_base_pointers_preloaded.ll
108
53
    // * Isl/CodeGen/OpenMP/loop-body-references-outer-values-3.ll
109
53
    // * Isl/CodeGen/OpenMP/single_loop_with_loop_invariant_baseptr.ll
110
53
    // GlobalMap should be a mapping from (value in original SCoP) to (copied
111
53
    // value in generated SCoP), without intermediate mappings, which might
112
53
    // easily require transitiveness as well.
113
53
    if (Value *NewRemapped = GlobalMap.lookup(New))
114
6
      New = NewRemapped;
115
53
116
53
    // No test case for this code.
117
53
    if (Old->getType()->getScalarSizeInBits() <
118
53
        New->getType()->getScalarSizeInBits())
119
0
      New = Builder.CreateTruncOrBitCast(New, Old->getType());
120
53
121
53
    return New;
122
53
  };
123
2.19k
124
2.19k
  Value *New = nullptr;
125
2.19k
  auto VUse = VirtualUse::create(&Stmt, L, Old, true);
126
2.19k
  switch (VUse.getKind()) {
127
2.19k
  case VirtualUse::Block:
128
143
    // BasicBlock are constants, but the BlockGenerator copies them.
129
143
    New = BBMap.lookup(Old);
130
143
    break;
131
2.19k
132
2.19k
  case VirtualUse::Constant:
133
382
    // Used by:
134
382
    // * Isl/CodeGen/OpenMP/reference-argument-from-non-affine-region.ll
135
382
    // Constants should not be redefined. In this case, the GlobalMap just
136
382
    // contains a mapping to the same constant, which is unnecessary, but
137
382
    // harmless.
138
382
    if ((New = lookupGlobally(Old)))
139
1
      break;
140
381
141
381
    assert(!BBMap.count(Old));
142
381
    New = Old;
143
381
    break;
144
381
145
381
  case VirtualUse::ReadOnly:
146
23
    assert(!GlobalMap.count(Old));
147
23
148
23
    // Required for:
149
23
    // * Isl/CodeGen/MemAccess/create_arrays.ll
150
23
    // * Isl/CodeGen/read-only-scalars.ll
151
23
    // * ScheduleOptimizer/pattern-matching-based-opts_10.ll
152
23
    // For some reason these reload a read-only value. The reloaded value ends
153
23
    // up in BBMap, buts its value should be identical.
154
23
    //
155
23
    // Required for:
156
23
    // * Isl/CodeGen/OpenMP/single_loop_with_param.ll
157
23
    // The parallel subfunctions need to reference the read-only value from the
158
23
    // parent function, this is done by reloading them locally.
159
23
    if ((New = BBMap.lookup(Old)))
160
22
      break;
161
1
162
1
    New = Old;
163
1
    break;
164
1
165
770
  case VirtualUse::Synthesizable:
166
770
    // Used by:
167
770
    // * Isl/CodeGen/OpenMP/loop-body-references-outer-values-3.ll
168
770
    // * Isl/CodeGen/OpenMP/recomputed-srem.ll
169
770
    // * Isl/CodeGen/OpenMP/reference-other-bb.ll
170
770
    // * Isl/CodeGen/OpenMP/two-parallel-loops-reference-outer-indvar.ll
171
770
    // For some reason synthesizable values end up in GlobalMap. Their values
172
770
    // are the same as trySynthesizeNewValue would return. The legacy
173
770
    // implementation prioritized GlobalMap, so this is what we do here as well.
174
770
    // Ideally, synthesizable values should not end up in GlobalMap.
175
770
    if ((New = lookupGlobally(Old)))
176
7
      break;
177
763
178
763
    // Required for:
179
763
    // * Isl/CodeGen/RuntimeDebugBuilder/combine_different_values.ll
180
763
    // * Isl/CodeGen/getNumberOfIterations.ll
181
763
    // * Isl/CodeGen/non_affine_float_compare.ll
182
763
    // * ScheduleOptimizer/pattern-matching-based-opts_10.ll
183
763
    // Ideally, synthesizable values are synthesized by trySynthesizeNewValue,
184
763
    // not precomputed (SCEVExpander has its own caching mechanism).
185
763
    // These tests fail without this, but I think trySynthesizeNewValue would
186
763
    // just re-synthesize the same instructions.
187
763
    if ((New = BBMap.lookup(Old)))
188
93
      break;
189
670
190
670
    New = trySynthesizeNewValue(Stmt, Old, BBMap, LTS, L);
191
670
    break;
192
670
193
670
  case VirtualUse::Hoisted:
194
45
    // TODO: Hoisted invariant loads should be found in GlobalMap only, but not
195
45
    // redefined locally (which will be ignored anyway). That is, the following
196
45
    // assertion should apply: assert(!BBMap.count(Old))
197
45
198
45
    New = lookupGlobally(Old);
199
45
    break;
200
670
201
835
  case VirtualUse::Intra:
202
835
  case VirtualUse::Inter:
203
835
    assert(!GlobalMap.count(Old) &&
204
835
           "Intra and inter-stmt values are never global");
205
835
    New = BBMap.lookup(Old);
206
835
    break;
207
2.19k
  }
208
2.19k
  assert(New && "Unexpected scalar dependence in region!");
209
2.19k
  return New;
210
2.19k
}
211
212
void BlockGenerator::copyInstScalar(ScopStmt &Stmt, Instruction *Inst,
213
560
                                    ValueMapT &BBMap, LoopToScevMapT &LTS) {
214
560
  // We do not generate debug intrinsics as we did not investigate how to
215
560
  // copy them correctly. At the current state, they just crash the code
216
560
  // generation as the meta-data operands are not correctly copied.
217
560
  if (isa<DbgInfoIntrinsic>(Inst))
218
0
    return;
219
560
220
560
  Instruction *NewInst = Inst->clone();
221
560
222
560
  // Replace old operands with the new ones.
223
1.05k
  for (Value *OldOperand : Inst->operands()) {
224
1.05k
    Value *NewOperand =
225
1.05k
        getNewValue(Stmt, OldOperand, BBMap, LTS, getLoopForStmt(Stmt));
226
1.05k
227
1.05k
    if (!NewOperand) {
228
0
      assert(!isa<StoreInst>(NewInst) &&
229
0
             "Store instructions are always needed!");
230
0
      NewInst->deleteValue();
231
0
      return;
232
0
    }
233
1.05k
234
1.05k
    NewInst->replaceUsesOfWith(OldOperand, NewOperand);
235
1.05k
  }
236
560
237
560
  Builder.Insert(NewInst);
238
560
  BBMap[Inst] = NewInst;
239
560
240
560
  // When copying the instruction onto the Module meant for the GPU,
241
560
  // debug metadata attached to an instruction causes all related
242
560
  // metadata to be pulled into the Module. This includes the DICompileUnit,
243
560
  // which will not be listed in llvm.dbg.cu of the Module since the Module
244
560
  // doesn't contain one. This fails the verification of the Module and the
245
560
  // subsequent generation of the ASM string.
246
560
  if (NewInst->getModule() != Inst->getModule())
247
0
    NewInst->setDebugLoc(llvm::DebugLoc());
248
560
249
560
  if (!NewInst->getType()->isVoidTy())
250
454
    NewInst->setName("p_" + Inst->getName());
251
560
}
252
253
Value *
254
BlockGenerator::generateLocationAccessed(ScopStmt &Stmt, MemAccInst Inst,
255
                                         ValueMapT &BBMap, LoopToScevMapT &LTS,
256
788
                                         isl_id_to_ast_expr *NewAccesses) {
257
788
  const MemoryAccess &MA = Stmt.getArrayAccessFor(Inst);
258
788
  return generateLocationAccessed(
259
788
      Stmt, getLoopForStmt(Stmt),
260
788
      Inst.isNull() ? 
nullptr0
: Inst.getPointerOperand(), BBMap, LTS,
261
788
      NewAccesses, MA.getId().release(), MA.getAccessValue()->getType());
262
788
}
263
264
Value *BlockGenerator::generateLocationAccessed(
265
    ScopStmt &Stmt, Loop *L, Value *Pointer, ValueMapT &BBMap,
266
    LoopToScevMapT &LTS, isl_id_to_ast_expr *NewAccesses, __isl_take isl_id *Id,
267
816
    Type *ExpectedType) {
268
816
  isl_ast_expr *AccessExpr = isl_id_to_ast_expr_get(NewAccesses, Id);
269
816
270
816
  if (AccessExpr) {
271
241
    AccessExpr = isl_ast_expr_address_of(AccessExpr);
272
241
    auto Address = ExprBuilder->create(AccessExpr);
273
241
274
241
    // Cast the address of this memory access to a pointer type that has the
275
241
    // same element type as the original access, but uses the address space of
276
241
    // the newly generated pointer.
277
241
    auto OldPtrTy = ExpectedType->getPointerTo();
278
241
    auto NewPtrTy = Address->getType();
279
241
    OldPtrTy = PointerType::get(OldPtrTy->getElementType(),
280
241
                                NewPtrTy->getPointerAddressSpace());
281
241
282
241
    if (OldPtrTy != NewPtrTy)
283
4
      Address = Builder.CreateBitOrPointerCast(Address, OldPtrTy);
284
241
    return Address;
285
241
  }
286
575
  assert(
287
575
      Pointer &&
288
575
      "If expression was not generated, must use the original pointer value");
289
575
  return getNewValue(Stmt, Pointer, BBMap, LTS, L);
290
575
}
291
292
Value *
293
BlockGenerator::getImplicitAddress(MemoryAccess &Access, Loop *L,
294
                                   LoopToScevMapT &LTS, ValueMapT &BBMap,
295
242
                                   __isl_keep isl_id_to_ast_expr *NewAccesses) {
296
242
  if (Access.isLatestArrayKind())
297
28
    return generateLocationAccessed(*Access.getStatement(), L, nullptr, BBMap,
298
28
                                    LTS, NewAccesses, Access.getId().release(),
299
28
                                    Access.getAccessValue()->getType());
300
214
301
214
  return getOrCreateAlloca(Access);
302
214
}
303
304
3.90k
Loop *BlockGenerator::getLoopForStmt(const ScopStmt &Stmt) const {
305
3.90k
  auto *StmtBB = Stmt.getEntryBlock();
306
3.90k
  return LI.getLoopFor(StmtBB);
307
3.90k
}
308
309
Value *BlockGenerator::generateArrayLoad(ScopStmt &Stmt, LoadInst *Load,
310
                                         ValueMapT &BBMap, LoopToScevMapT &LTS,
311
383
                                         isl_id_to_ast_expr *NewAccesses) {
312
383
  if (Value *PreloadLoad = GlobalMap.lookup(Load))
313
30
    return PreloadLoad;
314
353
315
353
  Value *NewPointer =
316
353
      generateLocationAccessed(Stmt, Load, BBMap, LTS, NewAccesses);
317
353
  Value *ScalarLoad = Builder.CreateAlignedLoad(
318
353
      NewPointer, Load->getAlignment(), Load->getName() + "_p_scalar_");
319
353
320
353
  if (PollyDebugPrinting)
321
5
    RuntimeDebugBuilder::createCPUPrinter(Builder, "Load from ", NewPointer,
322
5
                                          ": ", ScalarLoad, "\n");
323
353
324
353
  return ScalarLoad;
325
353
}
326
327
void BlockGenerator::generateArrayStore(ScopStmt &Stmt, StoreInst *Store,
328
                                        ValueMapT &BBMap, LoopToScevMapT &LTS,
329
382
                                        isl_id_to_ast_expr *NewAccesses) {
330
382
  MemoryAccess &MA = Stmt.getArrayAccessFor(Store);
331
382
  isl::set AccDom = MA.getAccessRelation().domain();
332
382
  std::string Subject = MA.getId().get_name();
333
382
334
382
  generateConditionalExecution(Stmt, AccDom, Subject.c_str(), [&, this]() {
335
381
    Value *NewPointer =
336
381
        generateLocationAccessed(Stmt, Store, BBMap, LTS, NewAccesses);
337
381
    Value *ValueOperand = getNewValue(Stmt, Store->getValueOperand(), BBMap,
338
381
                                      LTS, getLoopForStmt(Stmt));
339
381
340
381
    if (PollyDebugPrinting)
341
1
      RuntimeDebugBuilder::createCPUPrinter(Builder, "Store to  ", NewPointer,
342
1
                                            ": ", ValueOperand, "\n");
343
381
344
381
    Builder.CreateAlignedStore(ValueOperand, NewPointer, Store->getAlignment());
345
381
  });
346
382
}
347
348
1.40k
bool BlockGenerator::canSyntheziseInStmt(ScopStmt &Stmt, Instruction *Inst) {
349
1.40k
  Loop *L = getLoopForStmt(Stmt);
350
1.40k
  return (Stmt.isBlockStmt() || 
!Stmt.getRegion()->contains(L)169
) &&
351
1.40k
         
canSynthesize(Inst, *Stmt.getParent(), &SE, L)1.38k
;
352
1.40k
}
353
354
void BlockGenerator::copyInstruction(ScopStmt &Stmt, Instruction *Inst,
355
                                     ValueMapT &BBMap, LoopToScevMapT &LTS,
356
1.36k
                                     isl_id_to_ast_expr *NewAccesses) {
357
1.36k
  // Terminator instructions control the control flow. They are explicitly
358
1.36k
  // expressed in the clast and do not need to be copied.
359
1.36k
  if (Inst->isTerminator())
360
66
    return;
361
1.30k
362
1.30k
  // Synthesizable statements will be generated on-demand.
363
1.30k
  if (canSyntheziseInStmt(Stmt, Inst))
364
32
    return;
365
1.26k
366
1.26k
  if (auto *Load = dyn_cast<LoadInst>(Inst)) {
367
383
    Value *NewLoad = generateArrayLoad(Stmt, Load, BBMap, LTS, NewAccesses);
368
383
    // Compute NewLoad before its insertion in BBMap to make the insertion
369
383
    // deterministic.
370
383
    BBMap[Load] = NewLoad;
371
383
    return;
372
383
  }
373
885
374
885
  if (auto *Store = dyn_cast<StoreInst>(Inst)) {
375
382
    // Identified as redundant by -polly-simplify.
376
382
    if (!Stmt.getArrayAccessOrNULLFor(Store))
377
0
      return;
378
382
379
382
    generateArrayStore(Stmt, Store, BBMap, LTS, NewAccesses);
380
382
    return;
381
382
  }
382
503
383
503
  if (auto *PHI = dyn_cast<PHINode>(Inst)) {
384
44
    copyPHIInstruction(Stmt, PHI, BBMap, LTS);
385
44
    return;
386
44
  }
387
459
388
459
  // Skip some special intrinsics for which we do not adjust the semantics to
389
459
  // the new schedule. All others are handled like every other instruction.
390
459
  if (isIgnoredIntrinsic(Inst))
391
0
    return;
392
459
393
459
  copyInstScalar(Stmt, Inst, BBMap, LTS);
394
459
}
395
396
444
void BlockGenerator::removeDeadInstructions(BasicBlock *BB, ValueMapT &BBMap) {
397
444
  auto NewBB = Builder.GetInsertBlock();
398
4.10k
  for (auto I = NewBB->rbegin(); I != NewBB->rend(); 
I++3.65k
) {
399
3.65k
    Instruction *NewInst = &*I;
400
3.65k
401
3.65k
    if (!isInstructionTriviallyDead(NewInst))
402
3.61k
      continue;
403
40
404
40
    for (auto Pair : BBMap)
405
201
      if (Pair.second == NewInst) {
406
29
        BBMap.erase(Pair.first);
407
29
      }
408
40
409
40
    NewInst->eraseFromParent();
410
40
    I = NewBB->rbegin();
411
40
  }
412
444
}
413
414
void BlockGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
415
444
                              isl_id_to_ast_expr *NewAccesses) {
416
444
  assert(Stmt.isBlockStmt() &&
417
444
         "Only block statements can be copied by the block generator");
418
444
419
444
  ValueMapT BBMap;
420
444
421
444
  BasicBlock *BB = Stmt.getBasicBlock();
422
444
  copyBB(Stmt, BB, BBMap, LTS, NewAccesses);
423
444
  removeDeadInstructions(BB, BBMap);
424
444
}
425
426
545
BasicBlock *BlockGenerator::splitBB(BasicBlock *BB) {
427
545
  BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
428
545
                                  &*Builder.GetInsertPoint(), &DT, &LI);
429
545
  CopyBB->setName("polly.stmt." + BB->getName());
430
545
  return CopyBB;
431
545
}
432
433
BasicBlock *BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB,
434
                                   ValueMapT &BBMap, LoopToScevMapT &LTS,
435
444
                                   isl_id_to_ast_expr *NewAccesses) {
436
444
  BasicBlock *CopyBB = splitBB(BB);
437
444
  Builder.SetInsertPoint(&CopyBB->front());
438
444
  generateScalarLoads(Stmt, LTS, BBMap, NewAccesses);
439
444
440
444
  copyBB(Stmt, BB, CopyBB, BBMap, LTS, NewAccesses);
441
444
442
444
  // After a basic block was copied store all scalars that escape this block in
443
444
  // their alloca.
444
444
  generateScalarStores(Stmt, LTS, BBMap, NewAccesses);
445
444
  return CopyBB;
446
444
}
447
448
void BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB, BasicBlock *CopyBB,
449
                            ValueMapT &BBMap, LoopToScevMapT &LTS,
450
545
                            isl_id_to_ast_expr *NewAccesses) {
451
545
  EntryBB = &CopyBB->getParent()->getEntryBlock();
452
545
453
545
  // Block statements and the entry blocks of region statement are code
454
545
  // generated from instruction lists. This allow us to optimize the
455
545
  // instructions that belong to a certain scop statement. As the code
456
545
  // structure of region statements might be arbitrary complex, optimizing the
457
545
  // instruction list is not yet supported.
458
545
  if (Stmt.isBlockStmt() || 
(101
Stmt.isRegionStmt()101
&&
Stmt.getEntryBlock() == BB101
))
459
479
    for (Instruction *Inst : Stmt.getInstructions())
460
1.12k
      copyInstruction(Stmt, Inst, BBMap, LTS, NewAccesses);
461
66
  else
462
66
    for (Instruction &Inst : *BB)
463
169
      copyInstruction(Stmt, &Inst, BBMap, LTS, NewAccesses);
464
545
}
465
466
217
Value *BlockGenerator::getOrCreateAlloca(const MemoryAccess &Access) {
467
217
  assert(!Access.isLatestArrayKind() && "Trying to get alloca for array kind");
468
217
469
217
  return getOrCreateAlloca(Access.getLatestScopArrayInfo());
470
217
}
471
472
297
Value *BlockGenerator::getOrCreateAlloca(const ScopArrayInfo *Array) {
473
297
  assert(!Array->isArrayKind() && "Trying to get alloca for array kind");
474
297
475
297
  auto &Addr = ScalarMap[Array];
476
297
477
297
  if (Addr) {
478
168
    // Allow allocas to be (temporarily) redirected once by adding a new
479
168
    // old-alloca-addr to new-addr mapping to GlobalMap. This functionality
480
168
    // is used for example by the OpenMP code generation where a first use
481
168
    // of a scalar while still in the host code allocates a normal alloca with
482
168
    // getOrCreateAlloca. When the values of this scalar are accessed during
483
168
    // the generation of the parallel subfunction, these values are copied over
484
168
    // to the parallel subfunction and each request for a scalar alloca slot
485
168
    // must be forwarded to the temporary in-subfunction slot. This mapping is
486
168
    // removed when the subfunction has been generated and again normal host
487
168
    // code is generated. Due to the following reasons it is not possible to
488
168
    // perform the GlobalMap lookup right after creating the alloca below, but
489
168
    // instead we need to check GlobalMap at each call to getOrCreateAlloca:
490
168
    //
491
168
    //   1) GlobalMap may be changed multiple times (for each parallel loop),
492
168
    //   2) The temporary mapping is commonly only known after the initial
493
168
    //      alloca has already been generated, and
494
168
    //   3) The original alloca value must be restored after leaving the
495
168
    //      sub-function.
496
168
    if (Value *NewAddr = GlobalMap.lookup(&*Addr))
497
2
      return NewAddr;
498
166
    return Addr;
499
166
  }
500
129
501
129
  Type *Ty = Array->getElementType();
502
129
  Value *ScalarBase = Array->getBasePtr();
503
129
  std::string NameExt;
504
129
  if (Array->isPHIKind())
505
34
    NameExt = ".phiops";
506
95
  else
507
95
    NameExt = ".s2a";
508
129
509
129
  const DataLayout &DL = Builder.GetInsertBlock()->getModule()->getDataLayout();
510
129
511
129
  Addr = new AllocaInst(Ty, DL.getAllocaAddrSpace(),
512
129
                        ScalarBase->getName() + NameExt);
513
129
  EntryBB = &Builder.GetInsertBlock()->getParent()->getEntryBlock();
514
129
  Addr->insertBefore(&*EntryBB->getFirstInsertionPt());
515
129
516
129
  return Addr;
517
129
}
518
519
73
void BlockGenerator::handleOutsideUsers(const Scop &S, ScopArrayInfo *Array) {
520
73
  Instruction *Inst = cast<Instruction>(Array->getBasePtr());
521
73
522
73
  // If there are escape users we get the alloca for this instruction and put it
523
73
  // in the EscapeMap for later finalization. Lastly, if the instruction was
524
73
  // copied multiple times we already did this and can exit.
525
73
  if (EscapeMap.count(Inst))
526
6
    return;
527
67
528
67
  EscapeUserVectorTy EscapeUsers;
529
96
  for (User *U : Inst->users()) {
530
96
531
96
    // Non-instruction user will never escape.
532
96
    Instruction *UI = dyn_cast<Instruction>(U);
533
96
    if (!UI)
534
0
      continue;
535
96
536
96
    if (S.contains(UI))
537
59
      continue;
538
37
539
37
    EscapeUsers.push_back(UI);
540
37
  }
541
67
542
67
  // Exit if no escape uses were found.
543
67
  if (EscapeUsers.empty())
544
35
    return;
545
32
546
32
  // Get or create an escape alloca for this instruction.
547
32
  auto *ScalarAddr = getOrCreateAlloca(Array);
548
32
549
32
  // Remember that this instruction has escape uses and the escape alloca.
550
32
  EscapeMap[Inst] = std::make_pair(ScalarAddr, std::move(EscapeUsers));
551
32
}
552
553
void BlockGenerator::generateScalarLoads(
554
    ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
555
479
    __isl_keep isl_id_to_ast_expr *NewAccesses) {
556
958
  for (MemoryAccess *MA : Stmt) {
557
958
    if (MA->isOriginalArrayKind() || 
MA->isWrite()243
)
558
867
      continue;
559
91
560
#ifndef NDEBUG
561
    auto StmtDom =
562
        Stmt.getDomain().intersect_params(Stmt.getParent()->getContext());
563
    auto AccDom = MA->getAccessRelation().domain();
564
    assert(!StmtDom.is_subset(AccDom).is_false() &&
565
           "Scalar must be loaded in all statement instances");
566
#endif
567
568
91
    auto *Address =
569
91
        getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, BBMap, NewAccesses);
570
91
    assert((!isa<Instruction>(Address) ||
571
91
            DT.dominates(cast<Instruction>(Address)->getParent(),
572
91
                         Builder.GetInsertBlock())) &&
573
91
           "Domination violation");
574
91
    BBMap[MA->getAccessValue()] =
575
91
        Builder.CreateLoad(Address, Address->getName() + ".reload");
576
91
  }
577
479
}
578
579
Value *BlockGenerator::buildContainsCondition(ScopStmt &Stmt,
580
10
                                              const isl::set &Subdomain) {
581
10
  isl::ast_build AstBuild = Stmt.getAstBuild();
582
10
  isl::set Domain = Stmt.getDomain();
583
10
584
10
  isl::union_map USchedule = AstBuild.get_schedule();
585
10
  USchedule = USchedule.intersect_domain(Domain);
586
10
587
10
  assert(!USchedule.is_empty());
588
10
  isl::map Schedule = isl::map::from_union_map(USchedule);
589
10
590
10
  isl::set ScheduledDomain = Schedule.range();
591
10
  isl::set ScheduledSet = Subdomain.apply(Schedule);
592
10
593
10
  isl::ast_build RestrictedBuild = AstBuild.restrict(ScheduledDomain);
594
10
595
10
  isl::ast_expr IsInSet = RestrictedBuild.expr_from(ScheduledSet);
596
10
  Value *IsInSetExpr = ExprBuilder->create(IsInSet.copy());
597
10
  IsInSetExpr = Builder.CreateICmpNE(
598
10
      IsInSetExpr, ConstantInt::get(IsInSetExpr->getType(), 0));
599
10
600
10
  return IsInSetExpr;
601
10
}
602
603
void BlockGenerator::generateConditionalExecution(
604
    ScopStmt &Stmt, const isl::set &Subdomain, StringRef Subject,
605
534
    const std::function<void()> &GenThenFunc) {
606
534
  isl::set StmtDom = Stmt.getDomain();
607
534
608
534
  // If the condition is a tautology, don't generate a condition around the
609
534
  // code.
610
534
  bool IsPartialWrite =
611
534
      !StmtDom.intersect_params(Stmt.getParent()->getContext())
612
534
           .is_subset(Subdomain);
613
534
  if (!IsPartialWrite) {
614
524
    GenThenFunc();
615
524
    return;
616
524
  }
617
10
618
10
  // Generate the condition.
619
10
  Value *Cond = buildContainsCondition(Stmt, Subdomain);
620
10
621
10
  // Don't call GenThenFunc if it is never executed. An ast index expression
622
10
  // might not be defined in this case.
623
10
  if (auto *Const = dyn_cast<ConstantInt>(Cond))
624
2
    if (Const->isZero())
625
2
      return;
626
8
627
8
  BasicBlock *HeadBlock = Builder.GetInsertBlock();
628
8
  StringRef BlockName = HeadBlock->getName();
629
8
630
8
  // Generate the conditional block.
631
8
  SplitBlockAndInsertIfThen(Cond, &*Builder.GetInsertPoint(), false, nullptr,
632
8
                            &DT, &LI);
633
8
  BranchInst *Branch = cast<BranchInst>(HeadBlock->getTerminator());
634
8
  BasicBlock *ThenBlock = Branch->getSuccessor(0);
635
8
  BasicBlock *TailBlock = Branch->getSuccessor(1);
636
8
637
8
  // Assign descriptive names.
638
8
  if (auto *CondInst = dyn_cast<Instruction>(Cond))
639
8
    CondInst->setName("polly." + Subject + ".cond");
640
8
  ThenBlock->setName(BlockName + "." + Subject + ".partial");
641
8
  TailBlock->setName(BlockName + ".cont");
642
8
643
8
  // Put the client code into the conditional block and continue in the merge
644
8
  // block afterwards.
645
8
  Builder.SetInsertPoint(ThenBlock, ThenBlock->getFirstInsertionPt());
646
8
  GenThenFunc();
647
8
  Builder.SetInsertPoint(TailBlock, TailBlock->getFirstInsertionPt());
648
8
}
649
650
void BlockGenerator::generateScalarStores(
651
    ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
652
444
    __isl_keep isl_id_to_ast_expr *NewAccesses) {
653
444
  Loop *L = LI.getLoopFor(Stmt.getBasicBlock());
654
444
655
444
  assert(Stmt.isBlockStmt() &&
656
444
         "Region statements need to use the generateScalarStores() function in "
657
444
         "the RegionGenerator");
658
444
659
862
  for (MemoryAccess *MA : Stmt) {
660
862
    if (MA->isOriginalArrayKind() || 
MA->isRead()214
)
661
729
      continue;
662
133
663
133
    isl::set AccDom = MA->getAccessRelation().domain();
664
133
    std::string Subject = MA->getId().get_name();
665
133
666
133
    generateConditionalExecution(
667
133
        Stmt, AccDom, Subject.c_str(), [&, this, MA]() {
668
132
          Value *Val = MA->getAccessValue();
669
132
          if (MA->isAnyPHIKind()) {
670
69
            assert(MA->getIncoming().size() >= 1 &&
671
69
                   "Block statements have exactly one exiting block, or "
672
69
                   "multiple but "
673
69
                   "with same incoming block and value");
674
69
            assert(std::all_of(MA->getIncoming().begin(),
675
69
                               MA->getIncoming().end(),
676
69
                               [&](std::pair<BasicBlock *, Value *> p) -> bool {
677
69
                                 return p.first == Stmt.getBasicBlock();
678
69
                               }) &&
679
69
                   "Incoming block must be statement's block");
680
69
            Val = MA->getIncoming()[0].second;
681
69
          }
682
132
          auto Address = getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS,
683
132
                                            BBMap, NewAccesses);
684
132
685
132
          Val = getNewValue(Stmt, Val, BBMap, LTS, L);
686
132
          assert((!isa<Instruction>(Val) ||
687
132
                  DT.dominates(cast<Instruction>(Val)->getParent(),
688
132
                               Builder.GetInsertBlock())) &&
689
132
                 "Domination violation");
690
132
          assert((!isa<Instruction>(Address) ||
691
132
                  DT.dominates(cast<Instruction>(Address)->getParent(),
692
132
                               Builder.GetInsertBlock())) &&
693
132
                 "Domination violation");
694
132
695
132
          // The new Val might have a different type than the old Val due to
696
132
          // ScalarEvolution looking through bitcasts.
697
132
          if (Val->getType() != Address->getType()->getPointerElementType())
698
1
            Address = Builder.CreateBitOrPointerCast(
699
1
                Address, Val->getType()->getPointerTo());
700
132
701
132
          Builder.CreateStore(Val, Address);
702
132
        });
703
133
  }
704
444
}
705
706
288
void BlockGenerator::createScalarInitialization(Scop &S) {
707
288
  BasicBlock *ExitBB = S.getExit();
708
288
  BasicBlock *PreEntryBB = S.getEnteringBlock();
709
288
710
288
  Builder.SetInsertPoint(&*StartBlock->begin());
711
288
712
620
  for (auto &Array : S.arrays()) {
713
620
    if (Array->getNumberOfDimensions() != 0)
714
473
      continue;
715
147
    if (Array->isPHIKind()) {
716
38
      // For PHI nodes, the only values we need to store are the ones that
717
38
      // reach the PHI node from outside the region. In general there should
718
38
      // only be one such incoming edge and this edge should enter through
719
38
      // 'PreEntryBB'.
720
38
      auto PHI = cast<PHINode>(Array->getBasePtr());
721
38
722
113
      for (auto BI = PHI->block_begin(), BE = PHI->block_end(); BI != BE; 
BI++75
)
723
75
        if (!S.contains(*BI) && 
*BI != PreEntryBB13
)
724
75
          
llvm_unreachable0
("Incoming edges from outside the scop should always "
725
38
                           "come from PreEntryBB");
726
38
727
38
      int Idx = PHI->getBasicBlockIndex(PreEntryBB);
728
38
      if (Idx < 0)
729
25
        continue;
730
13
731
13
      Value *ScalarValue = PHI->getIncomingValue(Idx);
732
13
733
13
      Builder.CreateStore(ScalarValue, getOrCreateAlloca(Array));
734
13
      continue;
735
13
    }
736
109
737
109
    auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
738
109
739
109
    if (Inst && 
S.contains(Inst)98
)
740
73
      continue;
741
36
742
36
    // PHI nodes that are not marked as such in their SAI object are either exit
743
36
    // PHI nodes we model as common scalars but without initialization, or
744
36
    // incoming phi nodes that need to be initialized. Check if the first is the
745
36
    // case for Inst and do not create and initialize memory if so.
746
36
    if (auto *PHI = dyn_cast_or_null<PHINode>(Inst))
747
24
      if (!S.hasSingleExitEdge() && 
PHI->getBasicBlockIndex(ExitBB) >= 023
)
748
23
        continue;
749
13
750
13
    Builder.CreateStore(Array->getBasePtr(), getOrCreateAlloca(Array));
751
13
  }
752
288
}
753
754
288
void BlockGenerator::createScalarFinalization(Scop &S) {
755
288
  // The exit block of the __unoptimized__ region.
756
288
  BasicBlock *ExitBB = S.getExitingBlock();
757
288
  // The merge block __just after__ the region and the optimized region.
758
288
  BasicBlock *MergeBB = S.getExit();
759
288
760
288
  // The exit block of the __optimized__ region.
761
288
  BasicBlock *OptExitBB = *(pred_begin(MergeBB));
762
288
  if (OptExitBB == ExitBB)
763
0
    OptExitBB = *(++pred_begin(MergeBB));
764
288
765
288
  Builder.SetInsertPoint(OptExitBB->getTerminator());
766
288
  for (const auto &EscapeMapping : EscapeMap) {
767
38
    // Extract the escaping instruction and the escaping users as well as the
768
38
    // alloca the instruction was demoted to.
769
38
    Instruction *EscapeInst = EscapeMapping.first;
770
38
    const auto &EscapeMappingValue = EscapeMapping.second;
771
38
    const EscapeUserVectorTy &EscapeUsers = EscapeMappingValue.second;
772
38
    Value *ScalarAddr = EscapeMappingValue.first;
773
38
774
38
    // Reload the demoted instruction in the optimized version of the SCoP.
775
38
    Value *EscapeInstReload =
776
38
        Builder.CreateLoad(ScalarAddr, EscapeInst->getName() + ".final_reload");
777
38
    EscapeInstReload =
778
38
        Builder.CreateBitOrPointerCast(EscapeInstReload, EscapeInst->getType());
779
38
780
38
    // Create the merge PHI that merges the optimized and unoptimized version.
781
38
    PHINode *MergePHI = PHINode::Create(EscapeInst->getType(), 2,
782
38
                                        EscapeInst->getName() + ".merge");
783
38
    MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
784
38
785
38
    // Add the respective values to the merge PHI.
786
38
    MergePHI->addIncoming(EscapeInstReload, OptExitBB);
787
38
    MergePHI->addIncoming(EscapeInst, ExitBB);
788
38
789
38
    // The information of scalar evolution about the escaping instruction needs
790
38
    // to be revoked so the new merged instruction will be used.
791
38
    if (SE.isSCEVable(EscapeInst->getType()))
792
31
      SE.forgetValue(EscapeInst);
793
38
794
38
    // Replace all uses of the demoted instruction with the merge PHI.
795
38
    for (Instruction *EUser : EscapeUsers)
796
44
      EUser->replaceUsesOfWith(EscapeInst, MergePHI);
797
38
  }
798
288
}
799
800
288
void BlockGenerator::findOutsideUsers(Scop &S) {
801
620
  for (auto &Array : S.arrays()) {
802
620
803
620
    if (Array->getNumberOfDimensions() != 0)
804
473
      continue;
805
147
806
147
    if (Array->isPHIKind())
807
38
      continue;
808
109
809
109
    auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
810
109
811
109
    if (!Inst)
812
11
      continue;
813
98
814
98
    // Scop invariant hoisting moves some of the base pointers out of the scop.
815
98
    // We can ignore these, as the invariant load hoisting already registers the
816
98
    // relevant outside users.
817
98
    if (!S.contains(Inst))
818
25
      continue;
819
73
820
73
    handleOutsideUsers(S, Array);
821
73
  }
822
288
}
823
824
288
void BlockGenerator::createExitPHINodeMerges(Scop &S) {
825
288
  if (S.hasSingleExitEdge())
826
230
    return;
827
58
828
58
  auto *ExitBB = S.getExitingBlock();
829
58
  auto *MergeBB = S.getExit();
830
58
  auto *AfterMergeBB = MergeBB->getSingleSuccessor();
831
58
  BasicBlock *OptExitBB = *(pred_begin(MergeBB));
832
58
  if (OptExitBB == ExitBB)
833
0
    OptExitBB = *(++pred_begin(MergeBB));
834
58
835
58
  Builder.SetInsertPoint(OptExitBB->getTerminator());
836
58
837
115
  for (auto &SAI : S.arrays()) {
838
115
    auto *Val = SAI->getBasePtr();
839
115
840
115
    // Only Value-like scalars need a merge PHI. Exit block PHIs receive either
841
115
    // the original PHI's value or the reloaded incoming values from the
842
115
    // generated code. An llvm::Value is merged between the original code's
843
115
    // value or the generated one.
844
115
    if (!SAI->isExitPHIKind())
845
93
      continue;
846
22
847
22
    PHINode *PHI = dyn_cast<PHINode>(Val);
848
22
    if (!PHI)
849
0
      continue;
850
22
851
22
    if (PHI->getParent() != AfterMergeBB)
852
0
      continue;
853
22
854
22
    std::string Name = PHI->getName();
855
22
    Value *ScalarAddr = getOrCreateAlloca(SAI);
856
22
    Value *Reload = Builder.CreateLoad(ScalarAddr, Name + ".ph.final_reload");
857
22
    Reload = Builder.CreateBitOrPointerCast(Reload, PHI->getType());
858
22
    Value *OriginalValue = PHI->getIncomingValueForBlock(MergeBB);
859
22
    assert((!isa<Instruction>(OriginalValue) ||
860
22
            cast<Instruction>(OriginalValue)->getParent() != MergeBB) &&
861
22
           "Original value must no be one we just generated.");
862
22
    auto *MergePHI = PHINode::Create(PHI->getType(), 2, Name + ".ph.merge");
863
22
    MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
864
22
    MergePHI->addIncoming(Reload, OptExitBB);
865
22
    MergePHI->addIncoming(OriginalValue, ExitBB);
866
22
    int Idx = PHI->getBasicBlockIndex(MergeBB);
867
22
    PHI->setIncomingValue(Idx, MergePHI);
868
22
  }
869
58
}
870
871
288
void BlockGenerator::invalidateScalarEvolution(Scop &S) {
872
288
  for (auto &Stmt : S)
873
446
    if (Stmt.isCopyStmt())
874
4
      continue;
875
442
    else if (Stmt.isBlockStmt())
876
408
      for (auto &Inst : *Stmt.getBasicBlock())
877
3.22k
        SE.forgetValue(&Inst);
878
34
    else if (Stmt.isRegionStmt())
879
34
      for (auto *BB : Stmt.getRegion()->blocks())
880
98
        for (auto &Inst : *BB)
881
295
          SE.forgetValue(&Inst);
882
34
    else
883
34
      
llvm_unreachable0
("Unexpected statement type found");
884
288
885
288
  // Invalidate SCEV of loops surrounding the EscapeUsers.
886
288
  for (const auto &EscapeMapping : EscapeMap) {
887
38
    const EscapeUserVectorTy &EscapeUsers = EscapeMapping.second.second;
888
44
    for (Instruction *EUser : EscapeUsers) {
889
44
      if (Loop *L = LI.getLoopFor(EUser->getParent()))
890
32
        
while (16
L) {
891
16
          SE.forgetLoop(L);
892
16
          L = L->getParentLoop();
893
16
        }
894
44
    }
895
38
  }
896
288
}
897
898
288
void BlockGenerator::finalizeSCoP(Scop &S) {
899
288
  findOutsideUsers(S);
900
288
  createScalarInitialization(S);
901
288
  createExitPHINodeMerges(S);
902
288
  createScalarFinalization(S);
903
288
  invalidateScalarEvolution(S);
904
288
}
905
906
VectorBlockGenerator::VectorBlockGenerator(BlockGenerator &BlockGen,
907
                                           std::vector<LoopToScevMapT> &VLTS,
908
                                           isl_map *Schedule)
909
20
    : BlockGenerator(BlockGen), VLTS(VLTS), Schedule(Schedule) {
910
20
  assert(Schedule && "No statement domain provided");
911
20
}
912
913
Value *VectorBlockGenerator::getVectorValue(ScopStmt &Stmt, Value *Old,
914
                                            ValueMapT &VectorMap,
915
                                            VectorValueMapT &ScalarMaps,
916
32
                                            Loop *L) {
917
32
  if (Value *NewValue = VectorMap.lookup(Old))
918
29
    return NewValue;
919
3
920
3
  int Width = getVectorWidth();
921
3
922
3
  Value *Vector = UndefValue::get(VectorType::get(Old->getType(), Width));
923
3
924
15
  for (int Lane = 0; Lane < Width; 
Lane++12
)
925
12
    Vector = Builder.CreateInsertElement(
926
12
        Vector, getNewValue(Stmt, Old, ScalarMaps[Lane], VLTS[Lane], L),
927
12
        Builder.getInt32(Lane));
928
3
929
3
  VectorMap[Old] = Vector;
930
3
931
3
  return Vector;
932
3
}
933
934
27
Type *VectorBlockGenerator::getVectorPtrTy(const Value *Val, int Width) {
935
27
  PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
936
27
  assert(PointerTy && "PointerType expected");
937
27
938
27
  Type *ScalarType = PointerTy->getElementType();
939
27
  VectorType *VectorType = VectorType::get(ScalarType, Width);
940
27
941
27
  return PointerType::getUnqual(VectorType);
942
27
}
943
944
Value *VectorBlockGenerator::generateStrideOneLoad(
945
    ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
946
8
    __isl_keep isl_id_to_ast_expr *NewAccesses, bool NegativeStride = false) {
947
8
  unsigned VectorWidth = getVectorWidth();
948
8
  auto *Pointer = Load->getPointerOperand();
949
8
  Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
950
8
  unsigned Offset = NegativeStride ? 
VectorWidth - 11
:
07
;
951
8
952
8
  Value *NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[Offset],
953
8
                                               VLTS[Offset], NewAccesses);
954
8
  Value *VectorPtr =
955
8
      Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
956
8
  LoadInst *VecLoad =
957
8
      Builder.CreateLoad(VectorPtr, Load->getName() + "_p_vec_full");
958
8
  if (!Aligned)
959
8
    VecLoad->setAlignment(8);
960
8
961
8
  if (NegativeStride) {
962
1
    SmallVector<Constant *, 16> Indices;
963
5
    for (int i = VectorWidth - 1; i >= 0; 
i--4
)
964
4
      Indices.push_back(ConstantInt::get(Builder.getInt32Ty(), i));
965
1
    Constant *SV = llvm::ConstantVector::get(Indices);
966
1
    Value *RevVecLoad = Builder.CreateShuffleVector(
967
1
        VecLoad, VecLoad, SV, Load->getName() + "_reverse");
968
1
    return RevVecLoad;
969
1
  }
970
7
971
7
  return VecLoad;
972
7
}
973
974
Value *VectorBlockGenerator::generateStrideZeroLoad(
975
    ScopStmt &Stmt, LoadInst *Load, ValueMapT &BBMap,
976
3
    __isl_keep isl_id_to_ast_expr *NewAccesses) {
977
3
  auto *Pointer = Load->getPointerOperand();
978
3
  Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
979
3
  Value *NewPointer =
980
3
      generateLocationAccessed(Stmt, Load, BBMap, VLTS[0], NewAccesses);
981
3
  Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
982
3
                                           Load->getName() + "_p_vec_p");
983
3
  LoadInst *ScalarLoad =
984
3
      Builder.CreateLoad(VectorPtr, Load->getName() + "_p_splat_one");
985
3
986
3
  if (!Aligned)
987
3
    ScalarLoad->setAlignment(8);
988
3
989
3
  Constant *SplatVector = Constant::getNullValue(
990
3
      VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
991
3
992
3
  Value *VectorLoad = Builder.CreateShuffleVector(
993
3
      ScalarLoad, ScalarLoad, SplatVector, Load->getName() + "_p_splat");
994
3
  return VectorLoad;
995
3
}
996
997
Value *VectorBlockGenerator::generateUnknownStrideLoad(
998
    ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
999
3
    __isl_keep isl_id_to_ast_expr *NewAccesses) {
1000
3
  int VectorWidth = getVectorWidth();
1001
3
  auto *Pointer = Load->getPointerOperand();
1002
3
  VectorType *VectorType = VectorType::get(
1003
3
      dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth);
1004
3
1005
3
  Value *Vector = UndefValue::get(VectorType);
1006
3
1007
23
  for (int i = 0; i < VectorWidth; 
i++20
) {
1008
20
    Value *NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[i],
1009
20
                                                 VLTS[i], NewAccesses);
1010
20
    Value *ScalarLoad =
1011
20
        Builder.CreateLoad(NewPointer, Load->getName() + "_p_scalar_");
1012
20
    Vector = Builder.CreateInsertElement(
1013
20
        Vector, ScalarLoad, Builder.getInt32(i), Load->getName() + "_p_vec_");
1014
20
  }
1015
3
1016
3
  return Vector;
1017
3
}
1018
1019
void VectorBlockGenerator::generateLoad(
1020
    ScopStmt &Stmt, LoadInst *Load, ValueMapT &VectorMap,
1021
20
    VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
1022
20
  if (Value *PreloadLoad = GlobalMap.lookup(Load)) {
1023
6
    VectorMap[Load] = Builder.CreateVectorSplat(getVectorWidth(), PreloadLoad,
1024
6
                                                Load->getName() + "_p");
1025
6
    return;
1026
6
  }
1027
14
1028
14
  if (!VectorType::isValidElementType(Load->getType())) {
1029
0
    for (int i = 0; i < getVectorWidth(); i++)
1030
0
      ScalarMaps[i][Load] =
1031
0
          generateArrayLoad(Stmt, Load, ScalarMaps[i], VLTS[i], NewAccesses);
1032
0
    return;
1033
0
  }
1034
14
1035
14
  const MemoryAccess &Access = Stmt.getArrayAccessFor(Load);
1036
14
1037
14
  // Make sure we have scalar values available to access the pointer to
1038
14
  // the data location.
1039
14
  extractScalarValues(Load, VectorMap, ScalarMaps);
1040
14
1041
14
  Value *NewLoad;
1042
14
  if (Access.isStrideZero(isl::manage_copy(Schedule)))
1043
3
    NewLoad = generateStrideZeroLoad(Stmt, Load, ScalarMaps[0], NewAccesses);
1044
11
  else if (Access.isStrideOne(isl::manage_copy(Schedule)))
1045
7
    NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses);
1046
4
  else if (Access.isStrideX(isl::manage_copy(Schedule), -1))
1047
1
    NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses, true);
1048
3
  else
1049
3
    NewLoad = generateUnknownStrideLoad(Stmt, Load, ScalarMaps, NewAccesses);
1050
14
1051
14
  VectorMap[Load] = NewLoad;
1052
14
}
1053
1054
void VectorBlockGenerator::copyUnaryInst(ScopStmt &Stmt, UnaryInstruction *Inst,
1055
                                         ValueMapT &VectorMap,
1056
1
                                         VectorValueMapT &ScalarMaps) {
1057
1
  int VectorWidth = getVectorWidth();
1058
1
  Value *NewOperand = getVectorValue(Stmt, Inst->getOperand(0), VectorMap,
1059
1
                                     ScalarMaps, getLoopForStmt(Stmt));
1060
1
1061
1
  assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
1062
1
1063
1
  const CastInst *Cast = dyn_cast<CastInst>(Inst);
1064
1
  VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
1065
1
  VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
1066
1
}
1067
1068
void VectorBlockGenerator::copyBinaryInst(ScopStmt &Stmt, BinaryOperator *Inst,
1069
                                          ValueMapT &VectorMap,
1070
7
                                          VectorValueMapT &ScalarMaps) {
1071
7
  Loop *L = getLoopForStmt(Stmt);
1072
7
  Value *OpZero = Inst->getOperand(0);
1073
7
  Value *OpOne = Inst->getOperand(1);
1074
7
1075
7
  Value *NewOpZero, *NewOpOne;
1076
7
  NewOpZero = getVectorValue(Stmt, OpZero, VectorMap, ScalarMaps, L);
1077
7
  NewOpOne = getVectorValue(Stmt, OpOne, VectorMap, ScalarMaps, L);
1078
7
1079
7
  Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero, NewOpOne,
1080
7
                                       Inst->getName() + "p_vec");
1081
7
  VectorMap[Inst] = NewInst;
1082
7
}
1083
1084
void VectorBlockGenerator::copyStore(
1085
    ScopStmt &Stmt, StoreInst *Store, ValueMapT &VectorMap,
1086
17
    VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
1087
17
  const MemoryAccess &Access = Stmt.getArrayAccessFor(Store);
1088
17
1089
17
  auto *Pointer = Store->getPointerOperand();
1090
17
  Value *Vector = getVectorValue(Stmt, Store->getValueOperand(), VectorMap,
1091
17
                                 ScalarMaps, getLoopForStmt(Stmt));
1092
17
1093
17
  // Make sure we have scalar values available to access the pointer to
1094
17
  // the data location.
1095
17
  extractScalarValues(Store, VectorMap, ScalarMaps);
1096
17
1097
17
  if (Access.isStrideOne(isl::manage_copy(Schedule))) {
1098
15
    Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth());
1099
15
    Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[0],
1100
15
                                                 VLTS[0], NewAccesses);
1101
15
1102
15
    Value *VectorPtr =
1103
15
        Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
1104
15
    StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
1105
15
1106
15
    if (!Aligned)
1107
15
      Store->setAlignment(8);
1108
15
  } else {
1109
10
    for (unsigned i = 0; i < ScalarMaps.size(); 
i++8
) {
1110
8
      Value *Scalar = Builder.CreateExtractElement(Vector, Builder.getInt32(i));
1111
8
      Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[i],
1112
8
                                                   VLTS[i], NewAccesses);
1113
8
      Builder.CreateStore(Scalar, NewPointer);
1114
8
    }
1115
2
  }
1116
17
}
1117
1118
bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst,
1119
40
                                             ValueMapT &VectorMap) {
1120
40
  for (Value *Operand : Inst->operands())
1121
51
    if (VectorMap.count(Operand))
1122
28
      return true;
1123
40
  
return false12
;
1124
40
}
1125
1126
bool VectorBlockGenerator::extractScalarValues(const Instruction *Inst,
1127
                                               ValueMapT &VectorMap,
1128
46
                                               VectorValueMapT &ScalarMaps) {
1129
46
  bool HasVectorOperand = false;
1130
46
  int VectorWidth = getVectorWidth();
1131
46
1132
77
  for (Value *Operand : Inst->operands()) {
1133
77
    ValueMapT::iterator VecOp = VectorMap.find(Operand);
1134
77
1135
77
    if (VecOp == VectorMap.end())
1136
57
      continue;
1137
20
1138
20
    HasVectorOperand = true;
1139
20
    Value *NewVector = VecOp->second;
1140
20
1141
115
    for (int i = 0; i < VectorWidth; 
++i95
) {
1142
98
      ValueMapT &SM = ScalarMaps[i];
1143
98
1144
98
      // If there is one scalar extracted, all scalar elements should have
1145
98
      // already been extracted by the code here. So no need to check for the
1146
98
      // existence of all of them.
1147
98
      if (SM.count(Operand))
1148
3
        break;
1149
95
1150
95
      SM[Operand] =
1151
95
          Builder.CreateExtractElement(NewVector, Builder.getInt32(i));
1152
95
    }
1153
20
  }
1154
46
1155
46
  return HasVectorOperand;
1156
46
}
1157
1158
void VectorBlockGenerator::copyInstScalarized(
1159
    ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
1160
15
    VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
1161
15
  bool HasVectorOperand;
1162
15
  int VectorWidth = getVectorWidth();
1163
15
1164
15
  HasVectorOperand = extractScalarValues(Inst, VectorMap, ScalarMaps);
1165
15
1166
91
  for (int VectorLane = 0; VectorLane < getVectorWidth(); 
VectorLane++76
)
1167
76
    BlockGenerator::copyInstruction(Stmt, Inst, ScalarMaps[VectorLane],
1168
76
                                    VLTS[VectorLane], NewAccesses);
1169
15
1170
15
  if (!VectorType::isValidElementType(Inst->getType()) || 
!HasVectorOperand12
)
1171
12
    return;
1172
3
1173
3
  // Make the result available as vector value.
1174
3
  VectorType *VectorType = VectorType::get(Inst->getType(), VectorWidth);
1175
3
  Value *Vector = UndefValue::get(VectorType);
1176
3
1177
15
  for (int i = 0; i < VectorWidth; 
i++12
)
1178
12
    Vector = Builder.CreateInsertElement(Vector, ScalarMaps[i][Inst],
1179
12
                                         Builder.getInt32(i));
1180
3
1181
3
  VectorMap[Inst] = Vector;
1182
3
}
1183
1184
212
int VectorBlockGenerator::getVectorWidth() { return VLTS.size(); }
1185
1186
void VectorBlockGenerator::copyInstruction(
1187
    ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
1188
122
    VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
1189
122
  // Terminator instructions control the control flow. They are explicitly
1190
122
  // expressed in the clast and do not need to be copied.
1191
122
  if (Inst->isTerminator())
1192
20
    return;
1193
102
1194
102
  if (canSyntheziseInStmt(Stmt, Inst))
1195
42
    return;
1196
60
1197
60
  if (auto *Load = dyn_cast<LoadInst>(Inst)) {
1198
20
    generateLoad(Stmt, Load, VectorMap, ScalarMaps, NewAccesses);
1199
20
    return;
1200
20
  }
1201
40
1202
40
  if (hasVectorOperands(Inst, VectorMap)) {
1203
28
    if (auto *Store = dyn_cast<StoreInst>(Inst)) {
1204
17
      // Identified as redundant by -polly-simplify.
1205
17
      if (!Stmt.getArrayAccessOrNULLFor(Store))
1206
0
        return;
1207
17
1208
17
      copyStore(Stmt, Store, VectorMap, ScalarMaps, NewAccesses);
1209
17
      return;
1210
17
    }
1211
11
1212
11
    if (auto *Unary = dyn_cast<UnaryInstruction>(Inst)) {
1213
1
      copyUnaryInst(Stmt, Unary, VectorMap, ScalarMaps);
1214
1
      return;
1215
1
    }
1216
10
1217
10
    if (auto *Binary = dyn_cast<BinaryOperator>(Inst)) {
1218
7
      copyBinaryInst(Stmt, Binary, VectorMap, ScalarMaps);
1219
7
      return;
1220
7
    }
1221
15
1222
15
    // Fallthrough: We generate scalar instructions, if we don't know how to
1223
15
    // generate vector code.
1224
15
  }
1225
15
1226
15
  copyInstScalarized(Stmt, Inst, VectorMap, ScalarMaps, NewAccesses);
1227
15
}
1228
1229
void VectorBlockGenerator::generateScalarVectorLoads(
1230
20
    ScopStmt &Stmt, ValueMapT &VectorBlockMap) {
1231
35
  for (MemoryAccess *MA : Stmt) {
1232
35
    if (MA->isArrayKind() || 
MA->isWrite()1
)
1233
34
      continue;
1234
1
1235
1
    auto *Address = getOrCreateAlloca(*MA);
1236
1
    Type *VectorPtrType = getVectorPtrTy(Address, 1);
1237
1
    Value *VectorPtr = Builder.CreateBitCast(Address, VectorPtrType,
1238
1
                                             Address->getName() + "_p_vec_p");
1239
1
    auto *Val = Builder.CreateLoad(VectorPtr, Address->getName() + ".reload");
1240
1
    Constant *SplatVector = Constant::getNullValue(
1241
1
        VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
1242
1
1243
1
    Value *VectorVal = Builder.CreateShuffleVector(
1244
1
        Val, Val, SplatVector, Address->getName() + "_p_splat");
1245
1
    VectorBlockMap[MA->getAccessValue()] = VectorVal;
1246
1
  }
1247
20
}
1248
1249
20
void VectorBlockGenerator::verifyNoScalarStores(ScopStmt &Stmt) {
1250
35
  for (MemoryAccess *MA : Stmt) {
1251
35
    if (MA->isArrayKind() || 
MA->isRead()1
)
1252
35
      continue;
1253
0
1254
0
    llvm_unreachable("Scalar stores not expected in vector loop");
1255
0
  }
1256
20
}
1257
1258
void VectorBlockGenerator::copyStmt(
1259
20
    ScopStmt &Stmt, __isl_keep isl_id_to_ast_expr *NewAccesses) {
1260
20
  assert(Stmt.isBlockStmt() &&
1261
20
         "TODO: Only block statements can be copied by the vector block "
1262
20
         "generator");
1263
20
1264
20
  BasicBlock *BB = Stmt.getBasicBlock();
1265
20
  BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
1266
20
                                  &*Builder.GetInsertPoint(), &DT, &LI);
1267
20
  CopyBB->setName("polly.stmt." + BB->getName());
1268
20
  Builder.SetInsertPoint(&CopyBB->front());
1269
20
1270
20
  // Create two maps that store the mapping from the original instructions of
1271
20
  // the old basic block to their copies in the new basic block. Those maps
1272
20
  // are basic block local.
1273
20
  //
1274
20
  // As vector code generation is supported there is one map for scalar values
1275
20
  // and one for vector values.
1276
20
  //
1277
20
  // In case we just do scalar code generation, the vectorMap is not used and
1278
20
  // the scalarMap has just one dimension, which contains the mapping.
1279
20
  //
1280
20
  // In case vector code generation is done, an instruction may either appear
1281
20
  // in the vector map once (as it is calculating >vectorwidth< values at a
1282
20
  // time. Or (if the values are calculated using scalar operations), it
1283
20
  // appears once in every dimension of the scalarMap.
1284
20
  VectorValueMapT ScalarBlockMap(getVectorWidth());
1285
20
  ValueMapT VectorBlockMap;
1286
20
1287
20
  generateScalarVectorLoads(Stmt, VectorBlockMap);
1288
20
1289
20
  for (Instruction &Inst : *BB)
1290
122
    copyInstruction(Stmt, &Inst, VectorBlockMap, ScalarBlockMap, NewAccesses);
1291
20
1292
20
  verifyNoScalarStores(Stmt);
1293
20
}
1294
1295
BasicBlock *RegionGenerator::repairDominance(BasicBlock *BB,
1296
101
                                             BasicBlock *BBCopy) {
1297
101
1298
101
  BasicBlock *BBIDom = DT.getNode(BB)->getIDom()->getBlock();
1299
101
  BasicBlock *BBCopyIDom = EndBlockMap.lookup(BBIDom);
1300
101
1301
101
  if (BBCopyIDom)
1302
100
    DT.changeImmediateDominator(BBCopy, BBCopyIDom);
1303
101
1304
101
  return StartBlockMap.lookup(BBIDom);
1305
101
}
1306
1307
// This is to determine whether an llvm::Value (defined in @p BB) is usable when
1308
// leaving a subregion. The straight-forward DT.dominates(BB, R->getExitBlock())
1309
// does not work in cases where the exit block has edges from outside the
1310
// region. In that case the llvm::Value would never be usable in in the exit
1311
// block. The RegionGenerator however creates an new exit block ('ExitBBCopy')
1312
// for the subregion's exiting edges only. We need to determine whether an
1313
// llvm::Value is usable in there. We do this by checking whether it dominates
1314
// all exiting blocks individually.
1315
static bool isDominatingSubregionExit(const DominatorTree &DT, Region *R,
1316
101
                                      BasicBlock *BB) {
1317
188
  for (auto ExitingBB : predecessors(R->getExit())) {
1318
188
    // Check for non-subregion incoming edges.
1319
188
    if (!R->contains(ExitingBB))
1320
27
      continue;
1321
161
1322
161
    if (!DT.dominates(BB, ExitingBB))
1323
58
      return false;
1324
161
  }
1325
101
1326
101
  
return true43
;
1327
101
}
1328
1329
// Find the direct dominator of the subregion's exit block if the subregion was
1330
// simplified.
1331
35
static BasicBlock *findExitDominator(DominatorTree &DT, Region *R) {
1332
35
  BasicBlock *Common = nullptr;
1333
72
  for (auto ExitingBB : predecessors(R->getExit())) {
1334
72
    // Check for non-subregion incoming edges.
1335
72
    if (!R->contains(ExitingBB))
1336
9
      continue;
1337
63
1338
63
    // First exiting edge.
1339
63
    if (!Common) {
1340
35
      Common = ExitingBB;
1341
35
      continue;
1342
35
    }
1343
28
1344
28
    Common = DT.findNearestCommonDominator(Common, ExitingBB);
1345
28
  }
1346
35
1347
35
  assert(Common && R->contains(Common));
1348
35
  return Common;
1349
35
}
1350
1351
void RegionGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
1352
35
                               isl_id_to_ast_expr *IdToAstExp) {
1353
35
  assert(Stmt.isRegionStmt() &&
1354
35
         "Only region statements can be copied by the region generator");
1355
35
1356
35
  // Forget all old mappings.
1357
35
  StartBlockMap.clear();
1358
35
  EndBlockMap.clear();
1359
35
  RegionMaps.clear();
1360
35
  IncompletePHINodeMap.clear();
1361
35
1362
35
  // Collection of all values related to this subregion.
1363
35
  ValueMapT ValueMap;
1364
35
1365
35
  // The region represented by the statement.
1366
35
  Region *R = Stmt.getRegion();
1367
35
1368
35
  // Create a dedicated entry for the region where we can reload all demoted
1369
35
  // inputs.
1370
35
  BasicBlock *EntryBB = R->getEntry();
1371
35
  BasicBlock *EntryBBCopy = SplitBlock(Builder.GetInsertBlock(),
1372
35
                                       &*Builder.GetInsertPoint(), &DT, &LI);
1373
35
  EntryBBCopy->setName("polly.stmt." + EntryBB->getName() + ".entry");
1374
35
  Builder.SetInsertPoint(&EntryBBCopy->front());
1375
35
1376
35
  ValueMapT &EntryBBMap = RegionMaps[EntryBBCopy];
1377
35
  generateScalarLoads(Stmt, LTS, EntryBBMap, IdToAstExp);
1378
35
1379
85
  for (auto PI = pred_begin(EntryBB), PE = pred_end(EntryBB); PI != PE; 
++PI50
)
1380
50
    if (!R->contains(*PI)) {
1381
48
      StartBlockMap[*PI] = EntryBBCopy;
1382
48
      EndBlockMap[*PI] = EntryBBCopy;
1383
48
    }
1384
35
1385
35
  // Iterate over all blocks in the region in a breadth-first search.
1386
35
  std::deque<BasicBlock *> Blocks;
1387
35
  SmallSetVector<BasicBlock *, 8> SeenBlocks;
1388
35
  Blocks.push_back(EntryBB);
1389
35
  SeenBlocks.insert(EntryBB);
1390
35
1391
136
  while (!Blocks.empty()) {
1392
101
    BasicBlock *BB = Blocks.front();
1393
101
    Blocks.pop_front();
1394
101
1395
101
    // First split the block and update dominance information.
1396
101
    BasicBlock *BBCopy = splitBB(BB);
1397
101
    BasicBlock *BBCopyIDom = repairDominance(BB, BBCopy);
1398
101
1399
101
    // Get the mapping for this block and initialize it with either the scalar
1400
101
    // loads from the generated entering block (which dominates all blocks of
1401
101
    // this subregion) or the maps of the immediate dominator, if part of the
1402
101
    // subregion. The latter necessarily includes the former.
1403
101
    ValueMapT *InitBBMap;
1404
101
    if (BBCopyIDom) {
1405
100
      assert(RegionMaps.count(BBCopyIDom));
1406
100
      InitBBMap = &RegionMaps[BBCopyIDom];
1407
100
    } else
1408
1
      InitBBMap = &EntryBBMap;
1409
101
    auto Inserted = RegionMaps.insert(std::make_pair(BBCopy, *InitBBMap));
1410
101
    ValueMapT &RegionMap = Inserted.first->second;
1411
101
1412
101
    // Copy the block with the BlockGenerator.
1413
101
    Builder.SetInsertPoint(&BBCopy->front());
1414
101
    copyBB(Stmt, BB, BBCopy, RegionMap, LTS, IdToAstExp);
1415
101
1416
101
    // In order to remap PHI nodes we store also basic block mappings.
1417
101
    StartBlockMap[BB] = BBCopy;
1418
101
    EndBlockMap[BB] = Builder.GetInsertBlock();
1419
101
1420
101
    // Add values to incomplete PHI nodes waiting for this block to be copied.
1421
101
    for (const PHINodePairTy &PHINodePair : IncompletePHINodeMap[BB])
1422
3
      addOperandToPHI(Stmt, PHINodePair.first, PHINodePair.second, BB, LTS);
1423
101
    IncompletePHINodeMap[BB].clear();
1424
101
1425
101
    // And continue with new successors inside the region.
1426
244
    for (auto SI = succ_begin(BB), SE = succ_end(BB); SI != SE; 
SI++143
)
1427
143
      if (R->contains(*SI) && 
SeenBlocks.insert(*SI)80
)
1428
66
        Blocks.push_back(*SI);
1429
101
1430
101
    // Remember value in case it is visible after this subregion.
1431
101
    if (isDominatingSubregionExit(DT, R, BB))
1432
43
      ValueMap.insert(RegionMap.begin(), RegionMap.end());
1433
101
  }
1434
35
1435
35
  // Now create a new dedicated region exit block and add it to the region map.
1436
35
  BasicBlock *ExitBBCopy = SplitBlock(Builder.GetInsertBlock(),
1437
35
                                      &*Builder.GetInsertPoint(), &DT, &LI);
1438
35
  ExitBBCopy->setName("polly.stmt." + R->getExit()->getName() + ".exit");
1439
35
  StartBlockMap[R->getExit()] = ExitBBCopy;
1440
35
  EndBlockMap[R->getExit()] = ExitBBCopy;
1441
35
1442
35
  BasicBlock *ExitDomBBCopy = EndBlockMap.lookup(findExitDominator(DT, R));
1443
35
  assert(ExitDomBBCopy &&
1444
35
         "Common exit dominator must be within region; at least the entry node "
1445
35
         "must match");
1446
35
  DT.changeImmediateDominator(ExitBBCopy, ExitDomBBCopy);
1447
35
1448
35
  // As the block generator doesn't handle control flow we need to add the
1449
35
  // region control flow by hand after all blocks have been copied.
1450
101
  for (BasicBlock *BB : SeenBlocks) {
1451
101
1452
101
    BasicBlock *BBCopyStart = StartBlockMap[BB];
1453
101
    BasicBlock *BBCopyEnd = EndBlockMap[BB];
1454
101
    TerminatorInst *TI = BB->getTerminator();
1455
101
    if (isa<UnreachableInst>(TI)) {
1456
0
      while (!BBCopyEnd->empty())
1457
0
        BBCopyEnd->begin()->eraseFromParent();
1458
0
      new UnreachableInst(BBCopyEnd->getContext(), BBCopyEnd);
1459
0
      continue;
1460
0
    }
1461
101
1462
101
    Instruction *BICopy = BBCopyEnd->getTerminator();
1463
101
1464
101
    ValueMapT &RegionMap = RegionMaps[BBCopyStart];
1465
101
    RegionMap.insert(StartBlockMap.begin(), StartBlockMap.end());
1466
101
1467
101
    Builder.SetInsertPoint(BICopy);
1468
101
    copyInstScalar(Stmt, TI, RegionMap, LTS);
1469
101
    BICopy->eraseFromParent();
1470
101
  }
1471
35
1472
35
  // Add counting PHI nodes to all loops in the region that can be used as
1473
35
  // replacement for SCEVs referring to the old loop.
1474
101
  for (BasicBlock *BB : SeenBlocks) {
1475
101
    Loop *L = LI.getLoopFor(BB);
1476
101
    if (L == nullptr || 
L->getHeader() != BB75
||
!R->contains(L)12
)
1477
99
      continue;
1478
2
1479
2
    BasicBlock *BBCopy = StartBlockMap[BB];
1480
2
    Value *NullVal = Builder.getInt32(0);
1481
2
    PHINode *LoopPHI =
1482
2
        PHINode::Create(Builder.getInt32Ty(), 2, "polly.subregion.iv");
1483
2
    Instruction *LoopPHIInc = BinaryOperator::CreateAdd(
1484
2
        LoopPHI, Builder.getInt32(1), "polly.subregion.iv.inc");
1485
2
    LoopPHI->insertBefore(&BBCopy->front());
1486
2
    LoopPHIInc->insertBefore(BBCopy->getTerminator());
1487
2
1488
4
    for (auto *PredBB : make_range(pred_begin(BB), pred_end(BB))) {
1489
4
      if (!R->contains(PredBB))
1490
2
        continue;
1491
2
      if (L->contains(PredBB))
1492
2
        LoopPHI->addIncoming(LoopPHIInc, EndBlockMap[PredBB]);
1493
0
      else
1494
0
        LoopPHI->addIncoming(NullVal, EndBlockMap[PredBB]);
1495
2
    }
1496
2
1497
2
    for (auto *PredBBCopy : make_range(pred_begin(BBCopy), pred_end(BBCopy)))
1498
4
      if (LoopPHI->getBasicBlockIndex(PredBBCopy) < 0)
1499
2
        LoopPHI->addIncoming(NullVal, PredBBCopy);
1500
2
1501
2
    LTS[L] = SE.getUnknown(LoopPHI);
1502
2
  }
1503
35
1504
35
  // Continue generating code in the exit block.
1505
35
  Builder.SetInsertPoint(&*ExitBBCopy->getFirstInsertionPt());
1506
35
1507
35
  // Write values visible to other statements.
1508
35
  generateScalarStores(Stmt, LTS, ValueMap, IdToAstExp);
1509
35
  StartBlockMap.clear();
1510
35
  EndBlockMap.clear();
1511
35
  RegionMaps.clear();
1512
35
  IncompletePHINodeMap.clear();
1513
35
}
1514
1515
PHINode *RegionGenerator::buildExitPHI(MemoryAccess *MA, LoopToScevMapT &LTS,
1516
12
                                       ValueMapT &BBMap, Loop *L) {
1517
12
  ScopStmt *Stmt = MA->getStatement();
1518
12
  Region *SubR = Stmt->getRegion();
1519
12
  auto Incoming = MA->getIncoming();
1520
12
1521
12
  PollyIRBuilder::InsertPointGuard IPGuard(Builder);
1522
12
  PHINode *OrigPHI = cast<PHINode>(MA->getAccessInstruction());
1523
12
  BasicBlock *NewSubregionExit = Builder.GetInsertBlock();
1524
12
1525
12
  // This can happen if the subregion is simplified after the ScopStmts
1526
12
  // have been created; simplification happens as part of CodeGeneration.
1527
12
  if (OrigPHI->getParent() != SubR->getExit()) {
1528
6
    BasicBlock *FormerExit = SubR->getExitingBlock();
1529
6
    if (FormerExit)
1530
4
      NewSubregionExit = StartBlockMap.lookup(FormerExit);
1531
6
  }
1532
12
1533
12
  PHINode *NewPHI = PHINode::Create(OrigPHI->getType(), Incoming.size(),
1534
12
                                    "polly." + OrigPHI->getName(),
1535
12
                                    NewSubregionExit->getFirstNonPHI());
1536
12
1537
12
  // Add the incoming values to the PHI.
1538
26
  for (auto &Pair : Incoming) {
1539
26
    BasicBlock *OrigIncomingBlock = Pair.first;
1540
26
    BasicBlock *NewIncomingBlockStart = StartBlockMap.lookup(OrigIncomingBlock);
1541
26
    BasicBlock *NewIncomingBlockEnd = EndBlockMap.lookup(OrigIncomingBlock);
1542
26
    Builder.SetInsertPoint(NewIncomingBlockEnd->getTerminator());
1543
26
    assert(RegionMaps.count(NewIncomingBlockStart));
1544
26
    assert(RegionMaps.count(NewIncomingBlockEnd));
1545
26
    ValueMapT *LocalBBMap = &RegionMaps[NewIncomingBlockStart];
1546
26
1547
26
    Value *OrigIncomingValue = Pair.second;
1548
26
    Value *NewIncomingValue =
1549
26
        getNewValue(*Stmt, OrigIncomingValue, *LocalBBMap, LTS, L);
1550
26
    NewPHI->addIncoming(NewIncomingValue, NewIncomingBlockEnd);
1551
26
  }
1552
12
1553
12
  return NewPHI;
1554
12
}
1555
1556
Value *RegionGenerator::getExitScalar(MemoryAccess *MA, LoopToScevMapT &LTS,
1557
19
                                      ValueMapT &BBMap) {
1558
19
  ScopStmt *Stmt = MA->getStatement();
1559
19
1560
19
  // TODO: Add some test cases that ensure this is really the right choice.
1561
19
  Loop *L = LI.getLoopFor(Stmt->getRegion()->getExit());
1562
19
1563
19
  if (MA->isAnyPHIKind()) {
1564
12
    auto Incoming = MA->getIncoming();
1565
12
    assert(!Incoming.empty() &&
1566
12
           "PHI WRITEs must have originate from at least one incoming block");
1567
12
1568
12
    // If there is only one incoming value, we do not need to create a PHI.
1569
12
    if (Incoming.size() == 1) {
1570
0
      Value *OldVal = Incoming[0].second;
1571
0
      return getNewValue(*Stmt, OldVal, BBMap, LTS, L);
1572
0
    }
1573
12
1574
12
    return buildExitPHI(MA, LTS, BBMap, L);
1575
12
  }
1576
7
1577
7
  // MemoryKind::Value accesses leaving the subregion must dominate the exit
1578
7
  // block; just pass the copied value.
1579
7
  Value *OldVal = MA->getAccessValue();
1580
7
  return getNewValue(*Stmt, OldVal, BBMap, LTS, L);
1581
7
}
1582
1583
void RegionGenerator::generateScalarStores(
1584
    ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
1585
35
    __isl_keep isl_id_to_ast_expr *NewAccesses) {
1586
35
  assert(Stmt.getRegion() &&
1587
35
         "Block statements need to use the generateScalarStores() "
1588
35
         "function in the BlockGenerator");
1589
35
1590
96
  for (MemoryAccess *MA : Stmt) {
1591
96
    if (MA->isOriginalArrayKind() || 
MA->isRead()29
)
1592
77
      continue;
1593
19
1594
19
    isl::set AccDom = MA->getAccessRelation().domain();
1595
19
    std::string Subject = MA->getId().get_name();
1596
19
    generateConditionalExecution(
1597
19
        Stmt, AccDom, Subject.c_str(), [&, this, MA]() {
1598
19
          Value *NewVal = getExitScalar(MA, LTS, BBMap);
1599
19
          Value *Address = getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS,
1600
19
                                              BBMap, NewAccesses);
1601
19
          assert((!isa<Instruction>(NewVal) ||
1602
19
                  DT.dominates(cast<Instruction>(NewVal)->getParent(),
1603
19
                               Builder.GetInsertBlock())) &&
1604
19
                 "Domination violation");
1605
19
          assert((!isa<Instruction>(Address) ||
1606
19
                  DT.dominates(cast<Instruction>(Address)->getParent(),
1607
19
                               Builder.GetInsertBlock())) &&
1608
19
                 "Domination violation");
1609
19
          Builder.CreateStore(NewVal, Address);
1610
19
        });
1611
19
  }
1612
35
}
1613
1614
void RegionGenerator::addOperandToPHI(ScopStmt &Stmt, PHINode *PHI,
1615
                                      PHINode *PHICopy, BasicBlock *IncomingBB,
1616
15
                                      LoopToScevMapT &LTS) {
1617
15
  // If the incoming block was not yet copied mark this PHI as incomplete.
1618
15
  // Once the block will be copied the incoming value will be added.
1619
15
  BasicBlock *BBCopyStart = StartBlockMap[IncomingBB];
1620
15
  BasicBlock *BBCopyEnd = EndBlockMap[IncomingBB];
1621
15
  if (!BBCopyStart) {
1622
3
    assert(!BBCopyEnd);
1623
3
    assert(Stmt.represents(IncomingBB) &&
1624
3
           "Bad incoming block for PHI in non-affine region");
1625
3
    IncompletePHINodeMap[IncomingBB].push_back(std::make_pair(PHI, PHICopy));
1626
3
    return;
1627
3
  }
1628
12
1629
12
  assert(RegionMaps.count(BBCopyStart) &&
1630
12
         "Incoming PHI block did not have a BBMap");
1631
12
  ValueMapT &BBCopyMap = RegionMaps[BBCopyStart];
1632
12
1633
12
  Value *OpCopy = nullptr;
1634
12
1635
12
  if (Stmt.represents(IncomingBB)) {
1636
6
    Value *Op = PHI->getIncomingValueForBlock(IncomingBB);
1637
6
1638
6
    // If the current insert block is different from the PHIs incoming block
1639
6
    // change it, otherwise do not.
1640
6
    auto IP = Builder.GetInsertPoint();
1641
6
    if (IP->getParent() != BBCopyEnd)
1642
3
      Builder.SetInsertPoint(BBCopyEnd->getTerminator());
1643
6
    OpCopy = getNewValue(Stmt, Op, BBCopyMap, LTS, getLoopForStmt(Stmt));
1644
6
    if (IP->getParent() != BBCopyEnd)
1645
3
      Builder.SetInsertPoint(&*IP);
1646
6
  } else {
1647
6
    // All edges from outside the non-affine region become a single edge
1648
6
    // in the new copy of the non-affine region. Make sure to only add the
1649
6
    // corresponding edge the first time we encounter a basic block from
1650
6
    // outside the non-affine region.
1651
6
    if (PHICopy->getBasicBlockIndex(BBCopyEnd) >= 0)
1652
1
      return;
1653
5
1654
5
    // Get the reloaded value.
1655
5
    OpCopy = getNewValue(Stmt, PHI, BBCopyMap, LTS, getLoopForStmt(Stmt));
1656
5
  }
1657
12
1658
12
  assert(OpCopy && "Incoming PHI value was not copied properly");
1659
11
  PHICopy->addIncoming(OpCopy, BBCopyEnd);
1660
11
}
1661
1662
void RegionGenerator::copyPHIInstruction(ScopStmt &Stmt, PHINode *PHI,
1663
                                         ValueMapT &BBMap,
1664
7
                                         LoopToScevMapT &LTS) {
1665
7
  unsigned NumIncoming = PHI->getNumIncomingValues();
1666
7
  PHINode *PHICopy =
1667
7
      Builder.CreatePHI(PHI->getType(), NumIncoming, "polly." + PHI->getName());
1668
7
  PHICopy->moveBefore(PHICopy->getParent()->getFirstNonPHI());
1669
7
  BBMap[PHI] = PHICopy;
1670
7
1671
7
  for (BasicBlock *IncomingBB : PHI->blocks())
1672
12
    addOperandToPHI(Stmt, PHI, PHICopy, IncomingBB, LTS);
1673
7
}