Coverage Report

Created: 2017-11-23 03:11

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