loop_stmt_handler.cpp 25.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
/*******************************************************************************
 * Copyright (c) 2018-, UT-Battelle, LLC.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the BSD 3-Clause License 
 * which accompanies this distribution. 
 *
 * Contributors:
 *   Alexander J. McCaskey - initial API and implementation
 *   Thien Nguyen - implementation
 *******************************************************************************/
11
12
#include "expression_handler.hpp"
#include "exprtk.hpp"
13
14
#include "mlir/Dialect/SCF/SCF.h"
#include "mlir/IR/BlockAndValueMapping.h"
15
#include "qasm3_visitor.hpp"
16

17
18
19
20
using symbol_table_t = exprtk::symbol_table<double>;
using expression_t = exprtk::expression<double>;
using parser_t = exprtk::parser<double>;

Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
21
22
23
24
namespace {
/// Creates a single affine "for" loop, iterating from lbs to ubs with
/// the given step.
/// to construct the body of the loop and is passed the induction variable.
25
26
27
28
mlir::AffineForOp
affineLoopBuilder(mlir::Value lbs_val, mlir::Value ubs_val, int64_t step,
                  std::function<void(mlir::Value)> bodyBuilderFn,
                  mlir::OpBuilder &builder, mlir::Location &loc) {
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
29
30
31
32
33
34
35
36
  if (!ubs_val.getType().isa<mlir::IndexType>()) {
    ubs_val =
        builder.create<mlir::IndexCastOp>(loc, builder.getIndexType(), ubs_val);
  }
  if (!lbs_val.getType().isa<mlir::IndexType>()) {
    lbs_val =
        builder.create<mlir::IndexCastOp>(loc, builder.getIndexType(), lbs_val);
  }
37
38
39
40
41
42
43
44
  // Note: Affine for loop only accepts **positive** step:
  // The stride, represented by step, is a positive constant integer which
  // defaults to “1” if not present.
  assert(step != 0);
  if (step > 0) {
    mlir::ValueRange lbs(lbs_val);
    mlir::ValueRange ubs(ubs_val);
    // Create the actual loop
45
    return builder.create<mlir::AffineForOp>(
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
        loc, lbs, builder.getMultiDimIdentityMap(lbs.size()), ubs,
        builder.getMultiDimIdentityMap(ubs.size()), step, llvm::None,
        [&](mlir::OpBuilder &nestedBuilder, mlir::Location nestedLoc,
            mlir::Value iv, mlir::ValueRange itrArgs) {
          mlir::OpBuilder::InsertionGuard guard(nestedBuilder);
          bodyBuilderFn(iv);
          nestedBuilder.create<mlir::AffineYieldOp>(nestedLoc);
        });
  } else {
    // Negative step:
    // a -> b step c (minus)
    // -a -> -b step c (plus) and minus the loop var
    mlir::Value minus_one = builder.create<mlir::ConstantOp>(
        loc, mlir::IntegerAttr::get(lbs_val.getType(), -1));
    lbs_val = builder.create<mlir::MulIOp>(loc, lbs_val, minus_one).result();
    ubs_val = builder.create<mlir::MulIOp>(loc, ubs_val, minus_one).result();
    mlir::ValueRange lbs(lbs_val);
    mlir::ValueRange ubs(ubs_val);
64
    return builder.create<mlir::AffineForOp>(
65
66
67
68
69
70
71
72
73
74
75
76
77
        loc, lbs, builder.getMultiDimIdentityMap(lbs.size()), ubs,
        builder.getMultiDimIdentityMap(ubs.size()), -step, llvm::None,
        [&](mlir::OpBuilder &nestedBuilder, mlir::Location nestedLoc,
            mlir::Value iv, mlir::ValueRange itrArgs) {
          mlir::OpBuilder::InsertionGuard guard(nestedBuilder);
          mlir::Value minus_one_idx = nestedBuilder.create<mlir::ConstantOp>(
              nestedLoc, mlir::IntegerAttr::get(iv.getType(), -1));
          bodyBuilderFn(
              nestedBuilder.create<mlir::MulIOp>(nestedLoc, iv, minus_one_idx)
                  .result());
          nestedBuilder.create<mlir::AffineYieldOp>(nestedLoc);
        });
  }
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
78
79
}
} // namespace
80
namespace qcor {
81
82
antlrcpp::Any
qasm3_visitor::visitLoopStatement(qasm3Parser::LoopStatementContext *context) {
83
  if (auto membership_test = context->loopSignature()->membershipTest()) {
84
85
86
    // this is a for loop
    auto set_declaration = membership_test->setDeclaration();
    if (set_declaration->LBRACE()) {
87
88
      // Set-based for loop:
      // e.g., for i in {1,3,5,6}
89
      createSetBasedForLoop(context);
90
91
92
    } else if (set_declaration->rangeDefinition()) {
      // Range-based for loop
      // e.g., for i in [0:10]
93
94
95
96
97
98
      createRangeBasedForLoop(context);
    } else {
      printErrorMessage(
          "For loops must be of form 'for i in {SET}' or 'for i in [RANGE]'.");
    }
  } else {
99
    // While loop:
100
101
    createWhileLoop(context);
  }
102

103
104
  return 0;
}
105

106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
void qasm3_visitor::handleReturnInLoop(mlir::Location &location) {
  if (region_early_return_vars.has_value()) {
    auto parentOp = builder.getBlock()->getParent()->getParentOp();
    // Make it out to the Function scope:
    if (parentOp && mlir::dyn_cast_or_null<mlir::FuncOp>(parentOp)) {
      auto &[boolVar, returnVar] = region_early_return_vars.value();
      mlir::Value returnedValue;
      if (returnVar.has_value()) {
        assert(returnVar.value().getType().isa<mlir::MemRefType>());
        returnedValue =
            builder.create<mlir::LoadOp>(location, returnVar.value());
      }
      conditionalReturn(location,
                        builder.create<mlir::LoadOp>(location, boolVar),
                        returnedValue);
      region_early_return_vars.reset();
      assert(symbol_table.get_last_created_block());
    } else if (!loop_control_directive_bool_vars.empty()) {
      // The outer loop needs to set-up as a breakable loop as well.
      auto &[boolVar, returnVar] = region_early_return_vars.value();
      auto returnIfOp = builder.create<mlir::scf::IfOp>(
          location, mlir::TypeRange(),
          builder.create<mlir::LoadOp>(location, boolVar), false);
      // Break the outer loop if the return flag has been set
      auto opBuilder = returnIfOp.getThenBodyBuilder();
      insertLoopBreak(location, &opBuilder);
      // Treating the remaining code in the outer loop after the nested loop
      // as conditional (i.e., could be bypassed if the continue condition set).
      insertLoopContinue(location);
    } else {
      printErrorMessage("Internal error: Unable to handle return statement in a loop.");
    }
  }
}

141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
void qasm3_visitor::createRangeBasedForLoop(
    qasm3Parser::LoopStatementContext *context) {
  auto location = get_location(builder, file_name, context);
  auto loop_signature = context->loopSignature();
  auto program_block = context->programBlock();
  auto membership_test = loop_signature->membershipTest();
  assert(membership_test);
  auto set_declaration = membership_test->setDeclaration();
  assert(set_declaration);
  auto range = set_declaration->rangeDefinition();
  assert(range);
  auto idx_var_name = membership_test->Identifier()->getText();
  // Create Affine loop:
  auto range_str = range->getText().substr(1, range->getText().length() - 2);
  auto range_elements = split(range_str, ':');
  auto n_expr = range->expression().size();
  int a, b, c;

159
160
  // For loop variables will be index type (casting will be done if needed)
  mlir::Type index_type = builder.getIndexType();
161

162
163
  c = 1;
  mlir::Value a_value, b_value,
164
165
      c_value = get_or_create_constant_index_value(c, location, 64,
                                                   symbol_table, builder);
166

167
168
169
170
171
  const auto const_eval_a_val =
      symbol_table.try_evaluate_constant_integer_expression(
          range->expression(0)->getText());
  if (const_eval_a_val.has_value()) {
    // std::cout << "A val = " << const_eval_a_val.value() << "\n";
172
173
    a_value = get_or_create_constant_index_value(
        const_eval_a_val.value(), location, 64, symbol_table, builder);
174
175
176
177
178
179
180
181
  } else {
    qasm3_expression_generator exp_generator(builder, symbol_table, file_name);
    exp_generator.visit(range->expression(0));
    a_value = exp_generator.current_value;
    if (a_value.getType().isa<mlir::MemRefType>()) {
      a_value = builder.create<mlir::LoadOp>(location, a_value);
    }
  }
182

183
184
185
186
187
188
  if (n_expr == 3) {
    const auto const_eval_b_val =
        symbol_table.try_evaluate_constant_integer_expression(
            range->expression(2)->getText());
    if (const_eval_b_val.has_value()) {
      // std::cout << "B val = " << const_eval_b_val.value() << "\n";
189
190
      b_value = get_or_create_constant_index_value(
          const_eval_b_val.value(), location, 64, symbol_table, builder);
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
    } else {
      qasm3_expression_generator exp_generator(builder, symbol_table,
                                               file_name);
      exp_generator.visit(range->expression(2));
      b_value = exp_generator.current_value;
      if (b_value.getType().isa<mlir::MemRefType>()) {
        b_value = builder.create<mlir::LoadOp>(location, b_value);
      }
    }
    if (symbol_table.has_symbol(range->expression(1)->getText())) {
      printErrorMessage("You must provide loop step as a constant value.",
                        context);
      // c_value = symbol_table.get_symbol(range->expression(1)->getText());
      // c_value = builder.create<mlir::LoadOp>(location, c_value);
      // if (c_value.getType() != int_type) {
      //   printErrorMessage("For loop a, b, and c types are not equal.",
      //                     context, {a_value, c_value});
      // }
    } else {
      c = symbol_table.evaluate_constant_integer_expression(
          range->expression(1)->getText());
212
213
      c_value = get_or_create_constant_index_value(
          c, location, 64, symbol_table, builder);
214
    }
215

216
217
218
219
220
221
  } else {
    const auto const_eval_b_val =
        symbol_table.try_evaluate_constant_integer_expression(
            range->expression(1)->getText());
    if (const_eval_b_val.has_value()) {
      // std::cout << "B val = " << const_eval_b_val.value() << "\n";
222
223
      b_value = get_or_create_constant_index_value(
          const_eval_b_val.value(), location, 64, symbol_table, builder);
224
225
226
227
228
229
230
231
232
233
    } else {
      qasm3_expression_generator exp_generator(builder, symbol_table,
                                               file_name);
      exp_generator.visit(range->expression(1));
      b_value = exp_generator.current_value;
      if (b_value.getType().isa<mlir::MemRefType>()) {
        b_value = builder.create<mlir::LoadOp>(location, b_value);
      }
    }
  }
234

235
  // Check if the loop is break-able (contains control directive node)
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
  // The loop contains an early return.
  const bool loopEarlyReturn =
      hasChildNodeOfType<qasm3Parser::ReturnStatementContext>(*context) ||
      hasChildNodeOfType<qasm3Parser::Qcor_test_statementContext>(*context);
  // Top-level only
  if (loopEarlyReturn && !region_early_return_vars.has_value()) {
    mlir::OpBuilder::InsertionGuard g(builder);
    mlir::Value shouldReturn = builder.create<mlir::AllocaOp>(
        location,
        mlir::MemRefType::get(llvm::ArrayRef<int64_t>{}, builder.getI1Type()));
    // Store false:
    builder.create<mlir::StoreOp>(
        location,
        get_or_create_constant_integer_value(0, location, builder.getI1Type(),
                                             symbol_table, builder),
        shouldReturn);

    // Note: we don't know what the return value is yet
    if (current_function_return_type) {
      llvm::ArrayRef<int64_t> shaperef{};
      mlir::Value return_var_memref = builder.create<mlir::AllocaOp>(
          location,
          mlir::MemRefType::get(shaperef, current_function_return_type));
      region_early_return_vars =
          std::make_pair(shouldReturn, return_var_memref);
    } else {
      llvm::ArrayRef<int64_t> shaperef{};
      mlir::Value return_var_memref = builder.create<mlir::AllocaOp>(
          location, mlir::MemRefType::get(shaperef, builder.getI32Type()));
      region_early_return_vars =
          std::make_pair(shouldReturn, return_var_memref);
    }
  }

  // Loop has control directives (break/continue)
  // A loop has return statement must be breakable
272
  const bool isLoopBreakable =
273
      loopEarlyReturn ||
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
      hasChildNodeOfType<qasm3Parser::ControlDirectiveContext>(*context);
  auto cachedBuilder = builder;
  if (isLoopBreakable) {
    // Add the two loop control bool vars:
    mlir::OpBuilder::InsertionGuard g(builder);
    // Top-level if control (skipping the whole loop if false)
    mlir::Value executeWholeLoop = builder.create<mlir::AllocaOp>(
        location,
        mlir::MemRefType::get(llvm::ArrayRef<int64_t>{}, builder.getI1Type()));
    // Loop body control: skipping portions of the the body if
    // false: e.g., handle 'continue'-like directive.
    mlir::Value executeThisBlock = builder.create<mlir::AllocaOp>(
        location,
        mlir::MemRefType::get(llvm::ArrayRef<int64_t>{}, builder.getI1Type()));
    // store true
    builder.create<mlir::StoreOp>(
        location,
        get_or_create_constant_integer_value(1, location, builder.getI1Type(),
                                             symbol_table, builder),
        executeWholeLoop);
    builder.create<mlir::StoreOp>(
        location,
        get_or_create_constant_integer_value(1, location, builder.getI1Type(),
                                             symbol_table, builder),
        executeThisBlock);
299
    loop_control_directive_bool_vars.push(
300
301
302
303
304
305
306
307
308
309
310
        std::make_pair(executeWholeLoop, executeThisBlock));
  }
  // Can use Affine for loop....
  auto forLoop = affineLoopBuilder(
      a_value, b_value, c,
      [&](mlir::Value loop_var) {
        // Create a new scope for the for loop
        symbol_table.enter_new_scope();
        auto loop_var_cast = builder.create<mlir::IndexCastOp>(
            location, builder.getI64Type(), loop_var);
        symbol_table.add_symbol(idx_var_name, loop_var_cast, {}, true);
311

312
        if (isLoopBreakable) {
313
          auto [cond1, cond2] = loop_control_directive_bool_vars.top();
314
315
316
317
318
319
320
321
322
323
324
325
          // Wrap/Outline the loop body in an IfOp:
          auto scfIfOp = builder.create<mlir::scf::IfOp>(
              location, mlir::TypeRange(),
              builder.create<mlir::LoadOp>(location, cond1), false);
          auto thenBodyBuilder = scfIfOp.getThenBodyBuilder();
          auto cached_builder = builder;
          builder = thenBodyBuilder;
          visitChildren(program_block);
          builder = cached_builder;
        } else {
          visitChildren(program_block);
        }
326

327
        symbol_table.exit_scope();
328

329
        if (isLoopBreakable) {
330
          loop_control_directive_bool_vars.pop();
331
332
333
334
        }
      },
      builder, location);
  builder = cachedBuilder;
335
  handleReturnInLoop(location);
336
}
337

338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
void qasm3_visitor::createSetBasedForLoop(
    qasm3Parser::LoopStatementContext *context) {
  auto location = get_location(builder, file_name, context);
  auto loop_signature = context->loopSignature();
  auto program_block = context->programBlock();
  auto membership_test = loop_signature->membershipTest();
  assert(membership_test);
  auto set_declaration = membership_test->setDeclaration();
  assert(set_declaration);
  // Must be a set-based for loop
  assert(set_declaration->LBRACE());
  auto idx_var_name = membership_test->Identifier()->getText();
  auto exp_list = set_declaration->expressionList();
  auto n_expr = exp_list->expression().size();

  auto allocation = allocate_1d_memory(location, n_expr, builder.getI64Type());

  // Using Affine For loop:
  // the body builder needs to load the element at the loop index.
  // allocate i64 memref of size n_expr
  // for i in {1,2,3} -> affine.for i : 0 to 3 { element = load(memref, i) }
  int counter = 0;
  for (auto exp : exp_list->expression()) {
    qasm3_expression_generator exp_generator(builder, symbol_table, file_name);
    exp_generator.visit(exp);
    auto value = exp_generator.current_value;
    mlir::Value pos = get_or_create_constant_index_value(counter, location, 64,
                                                         symbol_table, builder);
    builder.create<mlir::StoreOp>(
        location, value, allocation,
        llvm::makeArrayRef(std::vector<mlir::Value>{pos}));
    counter++;
  }
  auto tmp = get_or_create_constant_index_value(0, location, 64, symbol_table,
                                                builder);
  auto tmp2 = get_or_create_constant_index_value(0, location, 64, symbol_table,
                                                 builder);
  llvm::ArrayRef<mlir::Value> zero_index(tmp2);
  // Loop var must also be an Index type
  // since we'll store the loop index values to this variable.
  auto loop_var_memref = allocate_1d_memory_and_initialize(
      location, 1, builder.getIndexType(), std::vector<mlir::Value>{tmp},
      llvm::makeArrayRef(std::vector<mlir::Value>{tmp}));
381

382
383
  auto a_val = get_or_create_constant_index_value(0, location, 64, symbol_table,
                                                  builder);
384
385
  auto b_val = get_or_create_constant_index_value(n_expr, location, 64,
                                                  symbol_table, builder);
386

387
  // Check if the loop is break-able (contains control directive node)
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
  // The loop contains an early return.
  const bool loopEarlyReturn =
      hasChildNodeOfType<qasm3Parser::ReturnStatementContext>(*context) ||
      hasChildNodeOfType<qasm3Parser::Qcor_test_statementContext>(*context);
  // Top-level only
  if (loopEarlyReturn && !region_early_return_vars.has_value()) {
    mlir::OpBuilder::InsertionGuard g(builder);
    mlir::Value shouldReturn = builder.create<mlir::AllocaOp>(
        location,
        mlir::MemRefType::get(llvm::ArrayRef<int64_t>{}, builder.getI1Type()));
    // Store false:
    builder.create<mlir::StoreOp>(
        location,
        get_or_create_constant_integer_value(0, location, builder.getI1Type(),
                                             symbol_table, builder),
        shouldReturn);

    // Note: we don't know what the return value is yet
    if (current_function_return_type) {
      llvm::ArrayRef<int64_t> shaperef{};
      mlir::Value return_var_memref = builder.create<mlir::AllocaOp>(
          location,
          mlir::MemRefType::get(shaperef, current_function_return_type));
      region_early_return_vars =
          std::make_pair(shouldReturn, return_var_memref);
    } else {
      llvm::ArrayRef<int64_t> shaperef{};
      mlir::Value return_var_memref = builder.create<mlir::AllocaOp>(
          location, mlir::MemRefType::get(shaperef, builder.getI32Type()));
      region_early_return_vars =
          std::make_pair(shouldReturn, return_var_memref);
    }
  }

  // Loop has control directives (break/continue)
  // A loop has return statement must be breakable
424
  const bool isLoopBreakable =
425
      loopEarlyReturn ||
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
      hasChildNodeOfType<qasm3Parser::ControlDirectiveContext>(*context);
  auto cachedBuilder = builder;
  if (isLoopBreakable) {
    // Add the two loop control bool vars:
    mlir::OpBuilder::InsertionGuard g(builder);
    // Top-level if control (skipping the whole loop if false)
    mlir::Value executeWholeLoop = builder.create<mlir::AllocaOp>(
        location,
        mlir::MemRefType::get(llvm::ArrayRef<int64_t>{}, builder.getI1Type()));
    // Loop body control: skipping portions of the the body if
    // false: e.g., handle 'continue'-like directive.
    mlir::Value executeThisBlock = builder.create<mlir::AllocaOp>(
        location,
        mlir::MemRefType::get(llvm::ArrayRef<int64_t>{}, builder.getI1Type()));
    // store true
    builder.create<mlir::StoreOp>(
        location,
        get_or_create_constant_integer_value(1, location, builder.getI1Type(),
                                             symbol_table, builder),
        executeWholeLoop);
    builder.create<mlir::StoreOp>(
        location,
        get_or_create_constant_integer_value(1, location, builder.getI1Type(),
                                             symbol_table, builder),
        executeThisBlock);
451
    loop_control_directive_bool_vars.push(
452
453
        std::make_pair(executeWholeLoop, executeThisBlock));
  }
454

455
456
457
458
459
460
461
462
463
464
465
466
  // Can use Affine for loop....
  auto forLoop = affineLoopBuilder(
      a_val, b_val, 1,
      [&](mlir::Value loop_index_var) {
        // Create a new scope for the for loop
        symbol_table.enter_new_scope();
        // Load the value at the index from the set
        auto loop_var =
            builder.create<mlir::LoadOp>(location, allocation, loop_index_var)
                .result();
        // Save the loaded value as the loop variable name
        symbol_table.add_symbol(idx_var_name, loop_var, {}, true);
467

468
        if (isLoopBreakable) {
469
          auto [cond1, cond2] = loop_control_directive_bool_vars.top();
470
471
472
473
474
475
476
477
478
479
480
481
482
          // Wrap/Outline the loop body in an IfOp:
          auto scfIfOp = builder.create<mlir::scf::IfOp>(
              location, mlir::TypeRange(),
              builder.create<mlir::LoadOp>(location, cond1), false);
          auto thenBodyBuilder = scfIfOp.getThenBodyBuilder();
          auto cached_builder = builder;
          builder = thenBodyBuilder;
          visitChildren(program_block);
          builder = cached_builder;
        } else {
          visitChildren(program_block);
        }
        symbol_table.exit_scope();
483

484
        if (isLoopBreakable) {
485
          loop_control_directive_bool_vars.pop();
486
487
488
489
        }
      },
      builder, location);
  builder = cachedBuilder;
490
  handleReturnInLoop(location);
491
}
492

493
494
495
496
497
498
void qasm3_visitor::createWhileLoop(
    qasm3Parser::LoopStatementContext *context) {
  auto location = get_location(builder, file_name, context);
  auto loop_signature = context->loopSignature();
  auto program_block = context->programBlock();
  assert(loop_signature->booleanExpression());
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
499
  auto cachedBuilder = builder;
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
  
  // Check if the loop is break-able (contains control directive node)
  // The loop contains an early return.
  const bool loopEarlyReturn =
      hasChildNodeOfType<qasm3Parser::ReturnStatementContext>(*context) ||
      hasChildNodeOfType<qasm3Parser::Qcor_test_statementContext>(*context);
  // Top-level only
  if (loopEarlyReturn && !region_early_return_vars.has_value()) {
    mlir::OpBuilder::InsertionGuard g(builder);
    mlir::Value shouldReturn = builder.create<mlir::AllocaOp>(
        location,
        mlir::MemRefType::get(llvm::ArrayRef<int64_t>{}, builder.getI1Type()));
    // Store false:
    builder.create<mlir::StoreOp>(
        location,
        get_or_create_constant_integer_value(0, location, builder.getI1Type(),
                                             symbol_table, builder),
        shouldReturn);

    // Note: we don't know what the return value is yet
    if (current_function_return_type) {
      llvm::ArrayRef<int64_t> shaperef{};
      mlir::Value return_var_memref = builder.create<mlir::AllocaOp>(
          location,
          mlir::MemRefType::get(shaperef, current_function_return_type));
      region_early_return_vars =
          std::make_pair(shouldReturn, return_var_memref);
    } else {
      llvm::ArrayRef<int64_t> shaperef{};
      mlir::Value return_var_memref = builder.create<mlir::AllocaOp>(
          location, mlir::MemRefType::get(shaperef, builder.getI32Type()));
      region_early_return_vars =
          std::make_pair(shouldReturn, return_var_memref);
    }
  }

  // Loop has control directives (break/continue)
  // A loop has return statement must be breakable
538
  const bool isLoopBreakable =
539
      loopEarlyReturn ||
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
      hasChildNodeOfType<qasm3Parser::ControlDirectiveContext>(*context);

  if (isLoopBreakable) {
    // Add the two loop control bool vars:
    mlir::OpBuilder::InsertionGuard g(builder);
    // Top-level if control (skipping the whole loop if false)
    mlir::Value executeWholeLoop = builder.create<mlir::AllocaOp>(
        location,
        mlir::MemRefType::get(llvm::ArrayRef<int64_t>{}, builder.getI1Type()));
    // Loop body control: skipping portions of the the body if
    // false: e.g., handle 'continue'-like directive.
    mlir::Value executeThisBlock = builder.create<mlir::AllocaOp>(
        location,
        mlir::MemRefType::get(llvm::ArrayRef<int64_t>{}, builder.getI1Type()));
    // store true
    builder.create<mlir::StoreOp>(
        location,
        get_or_create_constant_integer_value(1, location, builder.getI1Type(),
                                             symbol_table, builder),
        executeWholeLoop);
    builder.create<mlir::StoreOp>(
        location,
        get_or_create_constant_integer_value(1, location, builder.getI1Type(),
                                             symbol_table, builder),
        executeThisBlock);
    loop_control_directive_bool_vars.push(
        std::make_pair(executeWholeLoop, executeThisBlock));
  }

Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
569
570
571
  mlir::scf::WhileOp whileOp = builder.create<mlir::scf::WhileOp>(
      location, mlir::TypeRange() /*resultTypes*/,
      mlir::ValueRange() /*operands*/);
572

Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
573
574
  mlir::Block *before = builder.createBlock(&whileOp.before(), {}, {});
  mlir::Block *after = builder.createBlock(&whileOp.after(), {}, {});
575

Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
576
577
578
  // Build the "before" region:
  // In a "while" loop, this region computes the condition. 
  builder.setInsertionPointToStart(&whileOp.before().front());
579
  qasm3_expression_generator exp_generator(builder, symbol_table, file_name);
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
580
581
  exp_generator.visit(loop_signature->booleanExpression());
  mlir::Value cond = exp_generator.current_value;
582
583
584
585
586
587
588
589
590
591
592
593

  if (isLoopBreakable) {
    auto [cond1, cond2] = loop_control_directive_bool_vars.top();
    // Do a logical AND (&&) with the while condition.
    mlir::Value extended_cond = builder.create<mlir::AndOp>(
        location, builder.create<mlir::LoadOp>(location, cond1), cond);
    builder.create<mlir::scf::ConditionOp>(location, extended_cond,
                                           before->getArguments());
  } else {
    builder.create<mlir::scf::ConditionOp>(location, cond,
                                           before->getArguments());
  }
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
594
595
596
597
598
599
600
601

  // Build the "after" region:
  // In a "while" loop, this region is the loop body.
  builder.setInsertionPointToStart(&whileOp.after().front());
  {
    symbol_table.enter_new_scope();
    visitChildren(program_block);
    symbol_table.exit_scope();
602
603
604
605
  }

  if (isLoopBreakable) {
    loop_control_directive_bool_vars.pop();
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
606
  }
607

Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
608
  builder = cachedBuilder;
609
610
611
612
613
614
615
  // 'After' block must end with a yield op.
  {
    mlir::OpBuilder::InsertionGuard g(builder);
    mlir::Operation &lastOp = whileOp.after().front().getOperations().back();
    builder.setInsertionPointAfter(&lastOp);
    builder.create<mlir::scf::YieldOp>(location);
  }
616
617
618

  // Handle potential return statement in the loop.
  handleReturnInLoop(location);
619
}
620
} // namespace qcor