-
-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathMLIRGenFunctions.cpp
More file actions
1516 lines (1272 loc) · 62.6 KB
/
Copy pathMLIRGenFunctions.cpp
File metadata and controls
1516 lines (1272 loc) · 62.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
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
272
273
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
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
381
382
383
384
385
386
387
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
424
425
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
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
538
539
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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Function declaration/prototype/body/capture code generation methods of MLIRGenImpl (see MLIRGenImpl.h).
#include "MLIRGenImpl.h"
namespace typescript
{
namespace mlirgen
{
std::tuple<mlir::LogicalResult, bool, std::vector<std::shared_ptr<FunctionParamDOM>>> MLIRGenImpl::mlirGenParameters(
SignatureDeclarationBase parametersContextAST, const GenContext &genContext)
{
// to remove variables such as "this" from scope after using it in params context
SymbolTableScopeT varScope(symbolTable);
auto isGenericTypes = false;
std::vector<std::shared_ptr<FunctionParamDOM>> params;
SyntaxKind kind = parametersContextAST;
// add this param
auto isStatic =
hasModifier(parametersContextAST->parent, SyntaxKind::StaticKeyword)
|| hasModifier(parametersContextAST, SyntaxKind::StaticKeyword);
if (parametersContextAST->parent == SyntaxKind::InterfaceDeclaration)
{
params.push_back(std::make_shared<FunctionParamDOM>(THIS_NAME, getOpaqueType(), loc(parametersContextAST)));
}
else if (!isStatic &&
(kind == SyntaxKind::MethodDeclaration || kind == SyntaxKind::Constructor ||
kind == SyntaxKind::GetAccessor || kind == SyntaxKind::SetAccessor))
{
params.push_back(
std::make_shared<FunctionParamDOM>(THIS_NAME, genContext.thisType, loc(parametersContextAST)));
}
else if (!isStatic && genContext.thisType && !!parametersContextAST->parent &&
(kind == SyntaxKind::FunctionExpression ||
kind == SyntaxKind::ArrowFunction))
{
// TODO: this is very tricky code, if we rediscover function again and if by any chance thisType is not null, it will append thisType to lambda which very wrong code
params.push_back(
std::make_shared<FunctionParamDOM>(THIS_NAME, genContext.thisType, loc(parametersContextAST)));
}
auto formalParams = parametersContextAST->parameters;
for (auto [index, arg] : enumerate(formalParams))
{
auto namePtr = MLIRHelper::getName(arg->name, stringAllocator);
if (namePtr.empty())
{
namePtr = getArgumentName(index);
}
auto isBindingPattern = arg->name == SyntaxKind::ObjectBindingPattern || arg->name == SyntaxKind::ArrayBindingPattern;
mlir::Type type;
auto isMultiArgs = !!arg->dotDotDotToken;
auto isOptional = !!arg->questionToken;
auto typeParameter = arg->type;
auto location = loc(typeParameter);
if (typeParameter)
{
type = getType(typeParameter, genContext);
}
// special case, setup 'this' and type provided
if (namePtr == THIS_NAME && type)
{
// NOTE: upward mailbox: explicit this-parameter type must reach the prototype chain - see A7
const_cast<GenContext &>(genContext).thisType = type;
LLVM_DEBUG(dbgs() << "\n!! param " << THIS_NAME << " mapped to type " << type << "\n");
auto varDecl = std::make_shared<VariableDeclarationDOM>(THIS_NAME, type, location);
auto typeRefVal = builder.create<mlir_ts::TypeRefOp>(location, type);
declare(location, varDecl, typeRefVal, genContext);
}
// process init value
auto initializer = arg->initializer;
if (initializer)
{
auto evalType = evaluate(initializer, genContext);
if (evalType)
{
evalType = mth.wideStorageType(evalType);
// TODO: set type if not provided
isOptional = true;
if (mth.isNoneType(type))
{
type = evalType;
}
}
}
if (mth.isNoneType(type) && genContext.receiverFuncType && mth.isAnyFunctionType(genContext.receiverFuncType))
{
type = mth.getParamFromFuncRef(genContext.receiverFuncType, index);
if (!type)
{
emitError(location) << "can't resolve type for parameter '" << namePtr << "', the receiver function has less parameters.";
return {mlir::failure(), isGenericTypes, params};
}
LLVM_DEBUG(dbgs() << "\n!! param " << namePtr << " mapped to type " << type << "\n");
isGenericTypes |= mth.isGenericType(type);
}
// in case of binding
if (mth.isNoneType(type) && isBindingPattern)
{
type = mlirGenParameterObjectOrArrayBinding(arg->name, genContext);
LLVM_DEBUG(dbgs() << "\n!! binding param " << namePtr << " is type " << type << "\n");
}
if (mth.isNoneType(type))
{
if (!typeParameter && !initializer)
{
#ifndef ANY_AS_DEFAULT
if (!genContext.allowPartialResolve && !genContext.dummyRun)
{
auto funcName = MLIRHelper::getName(parametersContextAST->name);
emitError(loc(arg))
<< "type of parameter '" << namePtr
<< "' is not provided, parameter must have type or initializer, function: " << funcName;
}
return {mlir::failure(), isGenericTypes, params};
#else
emitWarning(loc(parametersContextAST)) << "type for parameter '" << namePtr << "' is any";
type = getAnyType();
#endif
}
else
{
emitError(location) << "can't resolve type for parameter '" << namePtr << "'";
return {mlir::failure(), isGenericTypes, params};
}
}
if (isa<mlir_ts::VoidType>(type))
{
emitError(location, "'Void' can't be used as parameter type");
return {mlir::failure(), isGenericTypes, params};
}
if (isa<mlir_ts::NeverType>(type))
{
emitError(location, "'Never' can't be used as parameter type");
return {mlir::failure(), isGenericTypes, params};
}
if (isBindingPattern)
{
params.push_back(
std::make_shared<FunctionParamDOM>(
namePtr, type, loc(arg), isOptional, isMultiArgs, initializer, arg->name));
}
else
{
params.push_back(
std::make_shared<FunctionParamDOM>(
namePtr, type, loc(arg), isOptional, isMultiArgs, initializer));
}
}
return {mlir::success(), isGenericTypes, params};
}
std::tuple<std::string, std::string> MLIRGenImpl::getNameOfFunction(SignatureDeclarationBase signatureDeclarationBaseAST,
const GenContext &genContext)
{
auto name = getNameWithArguments(signatureDeclarationBaseAST, genContext);
std::string objectOwnerName;
if (signatureDeclarationBaseAST->parent == SyntaxKind::ClassDeclaration ||
signatureDeclarationBaseAST->parent == SyntaxKind::ClassExpression)
{
objectOwnerName =
getNameWithArguments(signatureDeclarationBaseAST->parent.as<ClassDeclaration>(), genContext);
}
else if (signatureDeclarationBaseAST->parent == SyntaxKind::InterfaceDeclaration)
{
objectOwnerName =
getNameWithArguments(signatureDeclarationBaseAST->parent.as<InterfaceDeclaration>(), genContext);
}
else if (signatureDeclarationBaseAST->parent == SyntaxKind::ObjectLiteralExpression)
{
objectOwnerName = mlir::cast<mlir_ts::ObjectStorageType>(
mlir::cast<mlir_ts::ObjectType>(genContext.thisType).getStorageType()).getName().getValue();
}
else if (genContext.funcOp)
{
mlir_ts::FuncOp funcOp = genContext.funcOp;
objectOwnerName = funcOp.getSymName().str();
}
if (signatureDeclarationBaseAST == SyntaxKind::MethodDeclaration)
{
if (!objectOwnerName.empty())
{
// class method name
name = objectOwnerName + "." + name;
}
else
{
name = MLIRHelper::getAnonymousName(loc_check(signatureDeclarationBaseAST), ".md", "");
}
}
// TODO: for new () interfaces
else if (signatureDeclarationBaseAST == SyntaxKind::MethodSignature
|| signatureDeclarationBaseAST == SyntaxKind::ConstructSignature)
{
// class method name
name = objectOwnerName + "." + name;
}
else if (signatureDeclarationBaseAST == SyntaxKind::GetAccessor)
{
// class method name
name = objectOwnerName + ".get_" + name;
}
else if (signatureDeclarationBaseAST == SyntaxKind::SetAccessor)
{
// class method name
name = objectOwnerName + ".set_" + name;
}
else if (signatureDeclarationBaseAST == SyntaxKind::Constructor)
{
// class method name
auto isStatic =
hasModifier(signatureDeclarationBaseAST->parent, SyntaxKind::StaticKeyword)
|| hasModifier(signatureDeclarationBaseAST, SyntaxKind::StaticKeyword);
if (isStatic)
{
name = objectOwnerName + "." + STATIC_NAME + "_" + name;
}
else
{
name = objectOwnerName + "." + name;
}
}
auto fullName = concatFullNamespaceName(name);
return std::make_tuple(fullName, name);
}
std::tuple<mlir_ts::FuncOp, FunctionPrototypeDOM::TypePtr, mlir::LogicalResult, bool> MLIRGenImpl::mlirGenFunctionPrototype(
FunctionLikeDeclarationBase functionLikeDeclarationBaseAST, const GenContext &genContext)
{
auto location = loc(functionLikeDeclarationBaseAST);
mlir_ts::FuncOp funcOp;
auto [funcProto, funcType, argTypes] =
mlirGenFunctionSignaturePrototype(
functionLikeDeclarationBaseAST,
hasModifier(functionLikeDeclarationBaseAST, SyntaxKind::DeclareKeyword),
genContext);
if (!funcProto)
{
return std::make_tuple(funcOp, funcProto, mlir::failure(), false);
}
GenContext funcProtoGenContext(genContext);
funcProtoGenContext.funcProto = funcProto;
auto fullName = funcProto->getName();
mlir_ts::FunctionType functionDiscovered;
auto funcTypeIt = getFunctionTypeMap().find(fullName);
if (funcTypeIt != getFunctionTypeMap().end())
{
functionDiscovered = (*funcTypeIt).second;
}
// discover type & args
// seems we need to discover it all the time due to captured vars
auto detectReturnType = (!funcType || funcProtoGenContext.forceDiscover || !functionDiscovered)
&& !funcProto->getIsGeneric();
if (detectReturnType)
{
// register function to be able to call it if used in recursive call
// auto funcTypeTemp = getFunctionType(argTypes, builder.getNoneType(), funcProto->isMultiArgs());
// auto funcOpTemp = mlir_ts::FuncOp::create(location, fullName, funcTypeTemp, {});
// registerFunctionOp(funcProto, funcOpTemp);
if (mlir::succeeded(discoverFunctionReturnTypeAndCapturedVars(functionLikeDeclarationBaseAST, fullName,
argTypes, funcProto, funcProtoGenContext)))
{
if (!funcProtoGenContext.forceDiscover && funcType && funcType.getNumResults() > 0)
{
funcProto->setReturnType(funcType.getResult(0));
}
else if (auto typeParameter = functionLikeDeclarationBaseAST->type)
{
// rewrite ret type with actual value in case of specialized generic
auto returnType = getType(typeParameter, funcProtoGenContext);
funcProto->setReturnType(returnType);
}
else if (funcProtoGenContext.receiverFuncType)
{
// rewrite ret type with actual value
auto &argTypeDestFuncType = funcProtoGenContext.receiverFuncType;
auto retTypeFromReceiver = mth.isAnyFunctionType(argTypeDestFuncType)
? mth.getReturnTypeFromFuncRef(argTypeDestFuncType)
: mlir::Type();
if (retTypeFromReceiver
&& !mth.isNoneType(retTypeFromReceiver)
&& !mth.isGenericType(retTypeFromReceiver))
{
funcProto->setReturnType(retTypeFromReceiver);
LLVM_DEBUG(llvm::dbgs()
<< "\n!! set return type from receiver: " << retTypeFromReceiver << "\n";);
}
}
// create funcType
if (funcProto->getReturnType())
{
funcType = getFunctionType(argTypes, funcProto->getReturnType(), funcProto->isMultiArgs());
}
else
{
// no return type
funcType = getFunctionType(argTypes, {}, funcProto->isMultiArgs());
}
}
else
{
// false result
return std::make_tuple(funcOp, funcProto, mlir::failure(), false);
}
}
else if (functionDiscovered)
{
funcType = functionDiscovered;
}
// we need it, when we run rediscovery second time
if (!funcProto->getHasExtraFields())
{
funcProto->setHasExtraFields(existLocalVarsInThisContextMap(funcProto->getName()));
}
SmallVector<mlir::NamedAttribute> attrs;
auto dllExport = processFunctionAttributes(location, fullName, functionLikeDeclarationBaseAST, attrs, funcProtoGenContext);
if (funcType)
{
auto it = getCaptureVarsMap().find(funcProto->getName());
auto hasCapturedVars = funcProto->getHasCapturedVars() || (it != getCaptureVarsMap().end());
if (hasCapturedVars)
{
// important set when it is discovered and in process second type
funcProto->setHasCapturedVars(true);
funcOp = mlir_ts::FuncOp::create(location, fullName, funcType, attrs);
}
else
{
funcOp = mlir_ts::FuncOp::create(location, fullName, funcType, attrs);
}
funcProto->setFuncType(funcType);
if (dllExport)
{
if (functionLikeDeclarationBaseAST == SyntaxKind::FunctionDeclaration
|| functionLikeDeclarationBaseAST == SyntaxKind::ArrowFunction)
{
addFunctionDeclarationToExport(funcProto, currentNamespace);
}
}
}
if (!funcProto->getIsGeneric())
{
auto funcTypeIt = getFunctionTypeMap().find(fullName);
if (funcTypeIt != getFunctionTypeMap().end())
{
getFunctionTypeMap().erase(funcTypeIt);
}
getFunctionTypeMap().insert({fullName, funcType});
LLVM_DEBUG(llvm::dbgs() << "\n!! register func name: " << fullName << ", type: " << funcType << "\n";);
}
return std::make_tuple(funcOp, funcProto, mlir::success(), funcProto->getIsGeneric());
}
mlir::LogicalResult MLIRGenImpl::discoverFunctionReturnTypeAndCapturedVars(
FunctionLikeDeclarationBase functionLikeDeclarationBaseAST, StringRef name, SmallVector<mlir::Type> &argTypes,
const FunctionPrototypeDOM::TypePtr &funcProto, const GenContext &genContext)
{
if (funcProto->getDiscovered())
{
return mlir::failure();
}
LLVM_DEBUG(llvm::dbgs() << "\n\tdiscovering 'return type' & 'captured variables' for : " << name << "\n";);
mlir::OpBuilder::InsertionGuard guard(builder);
auto partialDeclFuncType = getFunctionType(argTypes, {}, false);
auto dummyFuncOp = mlir_ts::FuncOp::create(loc(functionLikeDeclarationBaseAST), name, partialDeclFuncType);
{
// simulate scope
SymbolTableScopeT varScope(symbolTable);
llvm::ScopedHashTableScope<StringRef, VariableDeclarationDOM::TypePtr>
fullNameGlobalsMapScope(fullNameGlobalsMap);
// owned here; GenContext borrows pointers to them (see GenContext::clean)
SmallVector<mlir::Block *> cleanUpsList;
SmallVector<mlir::Operation *> cleanUpOpsList;
PassResult passResultData;
int discoverState = 1;
GenContext genContextWithPassResult{};
genContextWithPassResult.funcOp = dummyFuncOp;
genContextWithPassResult.thisType = genContext.thisType;
genContextWithPassResult.thisClassType = genContext.thisClassType;
genContextWithPassResult.allowPartialResolve = true;
genContextWithPassResult.dummyRun = true;
genContextWithPassResult.cleanUps = &cleanUpsList;
genContextWithPassResult.cleanUpOps = &cleanUpOpsList;
genContextWithPassResult.passResult = &passResultData;
genContextWithPassResult.state = &discoverState;
genContextWithPassResult.allocateVarsInContextThis =
(functionLikeDeclarationBaseAST->internalFlags & InternalFlags::VarsInObjectContext) ==
InternalFlags::VarsInObjectContext;
genContextWithPassResult.discoverParamsOnly = genContext.discoverParamsOnly;
genContextWithPassResult.typeAliasMap = genContext.typeAliasMap;
genContextWithPassResult.typeParamsWithArgs = genContext.typeParamsWithArgs;
genContextWithPassResult.postponedMessages = genContext.postponedMessages;
registerNamespace(funcProto->getNameWithoutNamespace(), true);
if (succeeded(mlirGenFunctionBody(functionLikeDeclarationBaseAST, name, dummyFuncOp, funcProto,
genContextWithPassResult)))
{
exitNamespace();
auto &passResult = genContextWithPassResult.passResult;
if (passResult->functionReturnTypeShouldBeProvided
&& mth.isNoneType(passResult->functionReturnType))
{
// has return value but type is not provided yet
genContextWithPassResult.clean();
// if THIS discovery is itself nested inside an outer speculative
// discovery/dummy run (e.g. an object literal's method being
// return-type-discovered as a side effect of discovering the
// enclosing function - see the allowPartialResolve tolerance in
// mlirGenPropertyAccessExpressionBaseLogic), a sibling member's
// prototype may not be registered yet, so a return expression that
// depends on it can legitimately come back as "unknown" here. Don't
// hard-fail the whole discovery over that - the outer caller (and
// the real, non-dummy compile pass) will resolve it once every
// sibling's prototype is registered.
if (genContext.dummyRun || genContext.allowPartialResolve)
{
return mlir::failure();
}
emitError(loc(functionLikeDeclarationBaseAST)) << "'return' is not found in function or return type can't be resolved";
return mlir::failure();
}
funcProto->setDiscovered(true);
auto discoveredType = passResult->functionReturnType;
if (discoveredType && discoveredType != funcProto->getReturnType())
{
// TODO: do we need to convert it here? maybe send it as const object?
funcProto->setReturnType(mth.convertConstArrayTypeToArrayType(discoveredType));
LLVM_DEBUG(llvm::dbgs()
<< "\n!! ret type: " << funcProto->getReturnType() << ", name: " << name << "\n";);
}
// if we have captured parameters, add first param to send lambda's type(class)
if (passResult->outerVariables.size() > 0)
{
MLIRCodeLogic mcl(builder, compileOptions);
auto isObjectType =
genContext.thisType != nullptr && isa<mlir_ts::ObjectType>(genContext.thisType);
if (!isObjectType)
{
argTypes.insert(argTypes.begin(), mcl.CaptureType(passResult->outerVariables));
}
getCaptureVarsMap().insert({name, passResult->outerVariables});
funcProto->setHasCapturedVars(true);
LLVM_DEBUG(llvm::dbgs() << "\n!! has captured vars, name: " << name << "\n";);
LLVM_DEBUG(for (auto& var : passResult->outerVariables)
{
llvm::dbgs() << "\n!! ...captured var - name: " << var.second->getName() << ", type: " << var.second->getType() << "\n";
});
}
if (passResult->extraFieldsInThisContext.size() > 0)
{
getLocalVarsInThisContextMap().insert({name, passResult->extraFieldsInThisContext});
funcProto->setHasExtraFields(true);
}
genContextWithPassResult.clean();
LLVM_DEBUG(llvm::dbgs() << "\n\tSUCCESS - discovering 'return type' & 'captured variables' for : " << name << "\n";);
return mlir::success();
}
else
{
exitNamespace();
genContextWithPassResult.clean();
LLVM_DEBUG(llvm::dbgs() << "\n\tFAILED - discovering 'return type' & 'captured variables' for : " << name << "\n";);
return mlir::failure();
}
}
}
mlir::LogicalResult MLIRGenImpl::mlirGen(FunctionDeclaration functionDeclarationAST, const GenContext &genContext)
{
auto funcGenContext = GenContext(genContext);
funcGenContext.clearScopeVars();
// declaring function which is nested and object should not have this context (unless it is part of object declaration)
if (!functionDeclarationAST->parent && funcGenContext.thisType != nullptr)
{
funcGenContext.thisType = nullptr;
}
mlir::OpBuilder::InsertionGuard guard(builder);
auto res = mlirGenFunctionLikeDeclaration(functionDeclarationAST, funcGenContext);
return std::get<0>(res);
}
FunctionLikeDeclarationBase MLIRGenImpl::buildGeneratorWrapperDeclaration(
FunctionLikeDeclarationBase functionLikeDeclarationBaseAST, mlir::Location location)
{
auto fixThisReference = functionLikeDeclarationBaseAST == SyntaxKind::MethodDeclaration;
if (functionLikeDeclarationBaseAST->parameters.size() > 0)
{
auto nameNode = functionLikeDeclarationBaseAST->parameters.front()->name;
if (nameNode == SyntaxKind::Identifier)
{
auto ident = nameNode.as<Identifier>();
if (ident->escapedText == S(THIS_NAME))
{
fixThisReference = true;
}
}
}
NodeFactory nf(NodeFactoryFlags::None);
auto stepIdent = nf.createIdentifier(S(GENERATOR_STEP));
// create return object
NodeArray<ObjectLiteralElementLike> generatorObjectProperties;
// add step field
auto stepProp = nf.createPropertyAssignment(stepIdent, nf.createNumericLiteral(S("0"), TokenFlags::None));
generatorObjectProperties.push_back(stepProp);
// create body of next method
NodeArray<Statement> nextStatements;
// add main switcher
auto stepAccess = nf.createPropertyAccessExpression(nf.createToken(SyntaxKind::ThisKeyword), stepIdent);
// call stateswitch
auto callStat = nf.createExpressionStatement(
nf.createCallExpression(nf.createIdentifier(S(GENERATOR_SWITCHSTATE)), undefined, {stepAccess}));
nextStatements.push_back(callStat);
// add function body to statements to first step
if (functionLikeDeclarationBaseAST->body == SyntaxKind::Block)
{
// process every statement
auto block = functionLikeDeclarationBaseAST->body.as<ts::Block>();
for (auto statement : block->statements)
{
nextStatements.push_back(statement);
}
}
else if (functionLikeDeclarationBaseAST->body)
{
nextStatements.push_back(functionLikeDeclarationBaseAST->body);
}
// add next statements
// add default return with empty
nextStatements.push_back(
nf.createReturnStatement(getYieldReturnObject(nf, location, nf.createIdentifier(S(UNDEFINED_NAME)), true)));
// create next body
auto nextBody = nf.createBlock(nextStatements, /*multiLine*/ false);
// create method next in object
auto nextMethodDecl =
nf.createMethodDeclaration(undefined, undefined, nf.createIdentifier(S(ITERATOR_NEXT)), undefined,
undefined, undefined, undefined, nextBody);
nextMethodDecl->internalFlags |= InternalFlags::VarsInObjectContext;
// copy location info, to fix issue with names of anonymous functions
nextMethodDecl->pos = functionLikeDeclarationBaseAST->pos;
nextMethodDecl->_end = functionLikeDeclarationBaseAST->_end;
if (fixThisReference)
{
FilterVisitorSkipFuncsAST<Node> visitor(SyntaxKind::ThisKeyword, [&](auto thisNode) {
thisNode->internalFlags |= InternalFlags::ThisArgAlias;
});
for (auto it = begin(nextStatements) + 1; it != end(nextStatements); ++it)
{
visitor.visit(*it);
}
}
generatorObjectProperties.push_back(nextMethodDecl);
auto generatorObject = nf.createObjectLiteralExpression(generatorObjectProperties, false);
// the generator object has mutable identity (`step` advanced by next());
// it must be a reference type so aliases (params, closures, const bindings)
// share state -- box it on the GC heap instead of the default value tuple
generatorObject->internalFlags |= InternalFlags::BoxAsObject;
// copy location info, to fix issue with names of anonymous functions
generatorObject->pos = functionLikeDeclarationBaseAST->pos;
generatorObject->_end = functionLikeDeclarationBaseAST->_end;
// generator body
NodeArray<Statement> generatorStatements;
// TODO: this is hack, adding this as thisArg alias
if (fixThisReference)
{
// TODO: this is temp hack, add this alias as thisArg,
NodeArray<VariableDeclaration> _thisArgDeclarations;
auto _thisArg = nf.createIdentifier(S(THIS_ALIAS));
_thisArgDeclarations.push_back(nf.createVariableDeclaration(_thisArg, undefined, undefined, nf.createToken(SyntaxKind::ThisKeyword)));
auto _thisArgList = nf.createVariableDeclarationList(_thisArgDeclarations, NodeFlags::Const);
generatorStatements.push_back(nf.createVariableStatement(undefined, _thisArgList));
}
// step 1, add return object
auto retStat = nf.createReturnStatement(generatorObject);
generatorStatements.push_back(retStat);
auto body = nf.createBlock(generatorStatements, /*multiLine*/ false);
if (functionLikeDeclarationBaseAST == SyntaxKind::MethodDeclaration)
{
auto methodOp = nf.createMethodDeclaration(
functionLikeDeclarationBaseAST->modifiers, undefined,
functionLikeDeclarationBaseAST->name, undefined, functionLikeDeclarationBaseAST->typeParameters,
functionLikeDeclarationBaseAST->parameters, functionLikeDeclarationBaseAST->type, body);
// copy location info, to fix issue with names of anonymous functions
methodOp->pos = functionLikeDeclarationBaseAST->pos;
methodOp->_end = functionLikeDeclarationBaseAST->_end;
// to ensure correct full name
methodOp->parent = functionLikeDeclarationBaseAST->parent;
LLVM_DEBUG(printDebug(methodOp););
return methodOp;
}
else
{
auto funcOp = nf.createFunctionDeclaration(
functionLikeDeclarationBaseAST->modifiers, undefined,
functionLikeDeclarationBaseAST->name, functionLikeDeclarationBaseAST->typeParameters,
functionLikeDeclarationBaseAST->parameters, functionLikeDeclarationBaseAST->type, body);
// copy location info, to fix issue with names of anonymous functions
funcOp->pos = functionLikeDeclarationBaseAST->pos;
funcOp->_end = functionLikeDeclarationBaseAST->_end;
LLVM_DEBUG(printDebug(funcOp););
return funcOp;
}
}
std::tuple<mlir::LogicalResult, mlir_ts::FuncOp, std::string, bool> MLIRGenImpl::mlirGenFunctionGenerator(
FunctionLikeDeclarationBase functionLikeDeclarationBaseAST, const GenContext &genContext)
{
auto location = loc(functionLikeDeclarationBaseAST);
auto wrapperDecl = buildGeneratorWrapperDeclaration(functionLikeDeclarationBaseAST, location);
return mlirGenFunctionLikeDeclaration(wrapperDecl, genContext);
}
bool MLIRGenImpl::registerFunctionOp(FunctionPrototypeDOM::TypePtr funcProto, mlir_ts::FuncOp funcOp)
{
auto name = funcProto->getNameWithoutNamespace();
if (!getFunctionMap().count(name))
{
getFunctionMap().insert({name, makeFunctionEntry(funcOp)});
LLVM_DEBUG(llvm::dbgs() << "\n!! reg. func: " << name << " type:" << funcOp.getFunctionType() << " function name: " << funcProto->getName()
<< " num inputs:" << mlir::cast<mlir_ts::FunctionType>(funcOp.getFunctionType()).getNumInputs()
<< "\n";);
return true;
}
LLVM_DEBUG(llvm::dbgs() << "\n!! re-reg. func: " << name << " type:" << funcOp.getFunctionType() << " function name: " << funcProto->getName()
<< " num inputs:" << mlir::cast<mlir_ts::FunctionType>(funcOp.getFunctionType()).getNumInputs()
<< "\n";);
return false;
}
std::tuple<mlir::LogicalResult, mlir_ts::FuncOp, std::string, bool> MLIRGenImpl::mlirGenFunctionLikeDeclaration(
FunctionLikeDeclarationBase functionLikeDeclarationBaseAST, const GenContext &genContext)
{
auto funcDeclGenContext = GenContext(genContext);
auto instantiateSpecializedFunction = funcDeclGenContext.instantiateSpecializedFunction;
auto isGenericFunction =
functionLikeDeclarationBaseAST->typeParameters.size() > 0
|| !genContext.isGlobalVarReceiver && isGenericParameters(functionLikeDeclarationBaseAST, genContext);
if (isGenericFunction && !instantiateSpecializedFunction)
{
auto [result, name] = registerGenericFunctionLike(functionLikeDeclarationBaseAST, false, funcDeclGenContext);
return {result, mlir_ts::FuncOp(), name, false};
}
// check if it is generator
if (functionLikeDeclarationBaseAST->asteriskToken)
{
// this is generator, let's generate other function out of it
return mlirGenFunctionGenerator(functionLikeDeclarationBaseAST, funcDeclGenContext);
}
// we need to clear instantiateSpecializedFunction otherwise nested generics will be
// instantiated as well by mistake
funcDeclGenContext.instantiateSpecializedFunction = false;
// do not process generic functions more then 1 time
auto checkIfCreated = isGenericFunction && instantiateSpecializedFunction;
if (checkIfCreated)
{
auto [fullFunctionName, functionName] = getNameOfFunction(functionLikeDeclarationBaseAST, funcDeclGenContext);
auto funcEntry = lookupFunctionMap(functionName);
if (funcEntry && theModule.lookupSymbol(functionName)
|| theModule.lookupSymbol(fullFunctionName))
{
// resolve a live op from the module instead of returning a cached handle;
// the registered symbol is usually the full name
auto funcOp = theModule.lookupSymbol<mlir_ts::FuncOp>(functionName);
if (!funcOp)
{
funcOp = theModule.lookupSymbol<mlir_ts::FuncOp>(fullFunctionName);
}
return {mlir::success(), funcOp, functionName, false};
}
}
// go to root
mlir::OpBuilder::InsertPoint savePoint;
if (isGenericFunction)
{
savePoint = builder.saveInsertionPoint();
builder.setInsertionPointToStart(theModule.getBody());
}
auto location = loc(functionLikeDeclarationBaseAST);
auto [funcOp, funcProto, result, isGeneric] =
mlirGenFunctionPrototype(functionLikeDeclarationBaseAST, funcDeclGenContext);
if (mlir::failed(result))
{
// in case of ArrowFunction without params and receiver is generic function as well
return {result, funcOp, "", false};
}
if (mlir::succeeded(result) && isGeneric)
{
auto [result, name] = registerGenericFunctionLike(functionLikeDeclarationBaseAST, true, funcDeclGenContext);
return {result, funcOp, name, isGeneric};
}
// check decorator for class
auto dynamicImport = false;
iterateDecorators(functionLikeDeclarationBaseAST, genContext, [&](StringRef name, SmallVector<StringRef> args) {
if (name == DLL_IMPORT && args.size() > 0)
{
dynamicImport = true;
}
});
if (dynamicImport)
{
// TODO: we do not need to register funcOp as we need to reference global variables
auto result = mlirGenFunctionLikeDeclarationDynamicImport(
location, funcProto->getNameWithoutNamespace(), funcOp.getFunctionType(),
funcProto->getName(), funcDeclGenContext, false);
return {result, funcOp, funcProto->getName().str(), false};
}
auto funcGenContext = GenContext(funcDeclGenContext);
funcGenContext.clearScopeVars();
funcGenContext.funcOp = funcOp;
int funcState = 1;
funcGenContext.state = &funcState;
// if funcGenContext.passResult is null and allocateVarsInContextThis is true, this type should contain fully
// defined object with local variables as fields
funcGenContext.allocateVarsInContextThis =
(functionLikeDeclarationBaseAST->internalFlags & InternalFlags::VarsInObjectContext) ==
InternalFlags::VarsInObjectContext;
auto it = getCaptureVarsMap().find(funcProto->getName());
if (it != getCaptureVarsMap().end())
{
funcGenContext.capturedVars = &it->getValue();
LLVM_DEBUG(llvm::dbgs() << "\n!! func has captured vars: " << funcProto->getName() << "\n";);
}
else
{
assert(funcGenContext.capturedVars == nullptr);
}
// register function to be able to call it if used in recursive call
registerFunctionOp(funcProto, funcOp);
// generate body
auto resultFromBody = mlir::failure();
{
MLIRNamespaceGuard nsGuard(currentNamespace);
registerNamespace(funcProto->getNameWithoutNamespace(), true);
SymbolTableScopeT varScope(symbolTable);
resultFromBody = mlirGenFunctionBody(
functionLikeDeclarationBaseAST, funcProto->getNameWithoutNamespace(), funcOp, funcProto, funcGenContext);
}
if (mlir::failed(resultFromBody))
{
return {mlir::failure(), funcOp, "", false};
}
// set visibility index
auto isPublic =
getExportModifier(functionLikeDeclarationBaseAST)
/* we need to forcebly set to Public to prevent SymbolDCEPass to remove unused name */
|| hasModifier(functionLikeDeclarationBaseAST, SyntaxKind::ExportKeyword);
// force public
isPublic |=
((functionLikeDeclarationBaseAST->internalFlags & InternalFlags::DllExport) == InternalFlags::DllExport)
|| ((functionLikeDeclarationBaseAST->internalFlags & InternalFlags::IsPublic) == InternalFlags::IsPublic)
|| funcProto->getName() == MAIN_ENTRY_NAME;
// if explicit public/protected - set public visibility
if (hasModifier(functionLikeDeclarationBaseAST, SyntaxKind::PublicKeyword)
|| hasModifier(functionLikeDeclarationBaseAST, SyntaxKind::ProtectedKeyword))
{
isPublic = true;
}
// if explicit private - do not set public visibility
if (hasModifier(functionLikeDeclarationBaseAST, SyntaxKind::PrivateKeyword))
{
isPublic = false;
}
if (isPublic && !funcProto->getNoBody() && !declarationMode)
{
funcOp.setPublic();
}
else
{
funcOp.setPrivate();
}
if (!funcDeclGenContext.dummyRun)
{
theModule.push_back(funcOp);
}
if (isGenericFunction)
{
builder.restoreInsertionPoint(savePoint);
}
else
{
builder.setInsertionPointAfter(funcOp);
}
return {mlir::success(), funcOp, funcProto->getName().str(), false};
}
mlir::LogicalResult MLIRGenImpl::mlirGenFunctionLikeDeclarationDynamicImport(mlir::Location location, StringRef funcName,
mlir_ts::FunctionType functionType, StringRef dllFuncName, const GenContext &genContext, bool isFullNamespaceName)
{
registerVariable(location, funcName, isFullNamespaceName, VariableType::Var,
[&](mlir::Location location, const GenContext &context) -> TypeValueInitType {
// add command to load reference fron DLL
auto fullName = V(mlirGenStringValue(location, dllFuncName.str(), true));
auto referenceToFuncOpaque = builder.create<mlir_ts::SearchForAddressOfSymbolOp>(location, getOpaqueType(), fullName);
auto result = cast(location, functionType, referenceToFuncOpaque, genContext);
auto referenceToFunc = V(result);
return {referenceToFunc.getType(), referenceToFunc, TypeProvided::No};
},
genContext);
return mlir::success();
}
mlir::LogicalResult MLIRGenImpl::mlirGenFunctionEntry(mlir::Location location, FunctionPrototypeDOM::TypePtr funcProto,
const GenContext &genContext)
{
return mlirGenFunctionEntry(location, funcProto->getReturnType(), genContext);
}
mlir::LogicalResult MLIRGenImpl::mlirGenFunctionEntry(mlir::Location location, mlir::Type retType, const GenContext &genContext)
{
auto hasReturn = retType && !isa<mlir_ts::VoidType>(retType);
if (hasReturn)
{
auto entryOp = builder.create<mlir_ts::EntryOp>(location, mlir_ts::RefType::get(retType));
auto varDecl = std::make_shared<VariableDeclarationDOM>(RETURN_VARIABLE_NAME, retType, location);
varDecl->setReadWriteAccess();
DECLARE(varDecl, entryOp.getReference());
}
else
{
builder.create<mlir_ts::EntryOp>(location, mlir::Type());
}
return mlir::success();
}
mlir::LogicalResult MLIRGenImpl::mlirGenFunctionExit(mlir::Location location, const GenContext &genContext)
{
mlir_ts::FuncOp contextFuncOp = genContext.funcOp;
auto callableResult = contextFuncOp.getCallableResults();
auto retType = callableResult.size() > 0 ? callableResult.front() : mlir::Type();
auto hasReturn = retType && !isa<mlir_ts::VoidType>(retType);
if (hasReturn)
{
auto retVarInfo = symbolTable.lookup(RETURN_VARIABLE_NAME);
if (!retVarInfo.second)
{
if (genContext.allowPartialResolve)
{
return mlir::success();
}
emitError(location) << "can't find return variable";
return mlir::failure();
}
builder.create<mlir_ts::ExitOp>(location, retVarInfo.first);
}
else
{
builder.create<mlir_ts::ExitOp>(location, mlir::Value());
}
return mlir::success();
}
mlir::LogicalResult MLIRGenImpl::mlirGenFunctionCapturedParam(mlir::Location location, int &firstIndex,
FunctionPrototypeDOM::TypePtr funcProto,
mlir::Block::BlockArgListType arguments,
const GenContext &genContext)
{
if (genContext.capturedVars == nullptr)
{
return mlir::success();
}
auto isObjectType = genContext.thisType != nullptr && isa<mlir_ts::ObjectType>(genContext.thisType);
if (isObjectType)
{
return mlir::success();
}
auto capturedParam = arguments[firstIndex++];