forked from chapel-lang/chapel
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcg-symbol.cpp
More file actions
3767 lines (3271 loc) · 124 KB
/
cg-symbol.cpp
File metadata and controls
3767 lines (3271 loc) · 124 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
/*
* Copyright 2020-2026 Hewlett Packard Enterprise Development LP
* Copyright 2004-2019 Cray Inc.
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#include "symbol.h"
#include "AstToText.h"
#include "AstVisitorTraverse.h"
#include "bb.h"
#include "AstVisitor.h"
#include "astutil.h"
#include "build.h"
#include "CForLoop.h"
#include "chpl/util/string-escapes.h"
#include "clangUtil.h"
#include "codegen.h"
#include "CollapseBlocks.h"
#include "DoWhileStmt.h"
#include "driver.h"
#include "expr.h"
#include "files.h"
#include "fixupExports.h"
#include "ForLoop.h"
#include "intlimits.h"
#include "iterator.h"
#include "LayeredValueTable.h"
#include "library.h"
#include "llvmDebug.h"
#include "llvmExtractIR.h"
#include "llvmTracker.h"
#include "llvmUtil.h"
#include "LoopStmt.h"
#include "misc.h"
#include "optimizations.h"
#include "passes.h"
#include "stlUtil.h"
#include "stmt.h"
#include "stringutil.h"
#include "type.h"
#include "resolution.h"
#include "wellknown.h"
#include "WhileDoStmt.h"
#include "global-ast-vecs.h"
#include "chpl/libraries/LibraryFile.h"
#include "chpl/parsing/parsing-queries.h"
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <cstring>
#include <inttypes.h>
#include <stdint.h>
#ifdef HAVE_LLVM
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#if LLVM_VERSION_MAJOR >= 21
#include "llvm/IR/Intrinsics.h"
#else
#include "llvm/Target/TargetIntrinsicInfo.h"
#endif
#include "clang/CodeGen/CGFunctionInfo.h"
#endif
/******************************** | *********************************
* *
* *
********************************* | ********************************/
// these are sets of astrs
// Chapel function names requested to be disassembled, and whether they've been
// matched to C symbol names.
static std::unordered_map<const char*, bool> llvmPrintIrRequestedNames;
// Corresponding C function names to disassemble
static std::set<const char*> llvmPrintIrCNames;
static const char* cnamesToPrintFilename = "cnamesToPrint.tmp";
llvmStageNum_t llvmPrintIrStageNum = llvmStageNum::NOPRINT;
std::string llvmPrintIrFileName;
bool shouldLlvmPrintIrToFile() {
return !llvmPrintIrFileName.empty();
}
chpl::owned<llvm::raw_fd_ostream> llvmPrintIrFile = nullptr;
llvm::raw_fd_ostream* getLlvmPrintIrFile() {
if (!llvmPrintIrFile && shouldLlvmPrintIrToFile()) {
std::error_code error;
llvmPrintIrFile =
std::make_unique<llvm::raw_fd_ostream>(llvmPrintIrFileName, error);
if (!llvmPrintIrFile) {
USR_FATAL("Could not open file '%s'", llvmPrintIrFileName.c_str());
}
}
return shouldLlvmPrintIrToFile() ? llvmPrintIrFile.get() : &llvm::outs();
}
const char* llvmStageName[llvmStageNum::LAST] = {
"", //llvmStageNum::NOPRINT
"none", //llvmStageNum::NONE
"basic", //llvmStageNum::BASIC
"full", //llvmStageNum::FULL
"asm", //llvmStageNum::ASM
"every", //llvmStageNum::EVERY
"early-as-possible",
"module-optimizer-early",
"late-loop-optimizer",
"loop-optimizer-end",
"scalar-optimizer-late",
"early-simplification",
"optimizer-early",
"optimizer-last",
"cgscc-optimizer-late",
"vectorizer-start",
"enabled-on-opt-level0",
"peephole",
};
const char *llvmStageNameFromLlvmStageNum(llvmStageNum_t stageNum) {
if(stageNum < llvmStageNum::LAST)
return llvmStageName[stageNum];
else
return NULL;
}
llvmStageNum_t llvmStageNumFromLlvmStageName(const char* stageName) {
for(int i = 0; i < llvmStageNum::LAST; i++)
if(strcmp(llvmStageName[i], stageName) == 0)
return static_cast<llvmStageNum_t>(i);
return llvmStageNum::NOPRINT;
}
void addNameToPrintLlvmIrRequestedNames(const char* name) {
llvmPrintIrRequestedNames.emplace(astr(name), false);
}
static void addCNameToPrintLlvmIr(std::string_view name) {
llvmPrintIrCNames.insert(astr(name));
}
bool shouldLlvmPrintIrCName(const char* cname) {
return llvmPrintIrCNames.count(astr(cname)) > 0;
}
// finds if fn's name, cname, or ID is present in the requested names
// to print for --llvm-print-ir
static bool shouldLlvmPrintIrFnFindName(FnSymbol* fn, const char*& foundName) {
if (llvmPrintIrRequestedNames.count(fn->name)) {
foundName = fn->name;
return true;
}
if (llvmPrintIrRequestedNames.count(fn->cname)) {
foundName = fn->cname;
return true;
}
if (!fn->astloc.id().isEmpty()) {
const char* idstr = astr(fn->astloc.id().symbolPath());
if (llvmPrintIrRequestedNames.count(idstr)) {
foundName = idstr;
return true;
}
}
return false;
}
// Collect the cnames to print into a vector with (lex) ordering.
// Order of the list is non-deterministic otherwise, because it stores astrs
// for performance.
std::vector<std::string> gatherPrintLlvmIrCNames() {
std::vector<std::string> ret;
for (auto elt : llvmPrintIrCNames) {
ret.push_back(std::string(elt));
}
// sort the symbols by value to have deterministic ordering
std::sort(ret.begin(), ret.end());
return ret;
}
#ifdef HAVE_LLVM
static std::set<const llvm::GlobalValue*> funcsToPrint;
static llvmStageNum_t partlyPrintedStage = llvmStageNum::NOPRINT;
void printLlvmIr(const char* name, llvm::Function *func, llvmStageNum_t numStage) {
if(func) {
auto fd = getLlvmPrintIrFile();
*fd << "; " << "LLVM IR representation of " << name
<< " function after " << llvmStageNameFromLlvmStageNum(numStage)
<< " optimization stage\n";
fd->flush();
if (!(numStage == llvmStageNum::BASIC ||
numStage == llvmStageNum::FULL)) {
// Basic and full can happen module-at-a-time due to current
// compiler structure. For the others, we can't save the Function*,
// so just print out multiple modules if there are multiple functions.
std::set<const llvm::GlobalValue*> funcs;
funcs.insert(func);
extractAndPrintFunctionsLLVM(&funcs);
} else {
funcsToPrint.insert(func);
partlyPrintedStage = numStage;
}
}
}
#endif
void completePrintLlvmIrStage(llvmStageNum_t numStage) {
#ifdef HAVE_LLVM
extractAndPrintFunctionsLLVM(&funcsToPrint);
partlyPrintedStage = llvmStageNum_t::NOPRINT;
funcsToPrint.clear();
#endif
}
void restorePrintIrCNames() {
assert(llvmPrintIrCNames.empty() &&
"tried to restore list of cnames to print from disk, but we already "
"have them in memory");
restoreDriverTmp(cnamesToPrintFilename, &addCNameToPrintLlvmIr);
}
void preparePrintLlvmIrForCodegen() {
if (llvmPrintIrRequestedNames.empty() && llvmPrintIrCNames.empty())
return;
if (llvmPrintIrStageNum == llvmStageNum::NOPRINT)
return;
// Gather the cnames for the functions in names
forv_Vec(FnSymbol, fn, gFnSymbols) {
const char* foundName = nullptr;
if (shouldLlvmPrintIrFnFindName(fn, foundName) && foundName) {
addCNameToPrintLlvmIr(fn->cname);
// mark Chapel symbol as found
llvmPrintIrRequestedNames[astr(foundName)] = true;
}
}
// Ensure cnames were found for all Chapel function names
std::vector<std::string> namesNotFound;
for (const auto& nameInfo : llvmPrintIrRequestedNames) {
if (nameInfo.second == false) {
namesNotFound.emplace_back(nameInfo.first);
}
}
// Emit warning for any symbols not found
if (!namesNotFound.empty()) {
// Deterministically order
std::sort(namesNotFound.begin(), namesNotFound.end());
std::string nameList;
for (auto it = namesNotFound.begin(); it != namesNotFound.end(); ++it) {
if (it != namesNotFound.begin()) {
nameList += ", ";
}
nameList += *it;
}
USR_WARN("Could not find requested symbol%s for disassembly: %s",
(namesNotFound.size() == 1 ? "" : "s"), nameList.c_str());
}
// Extend cnames with the cnames of task functions
bool changed;
do {
changed = false;
forv_Vec(FnSymbol, fn, gFnSymbols) {
if (shouldLlvmPrintIrCName(fn->cname)) {
std::vector<CallExpr*> calls;
collectFnCalls(fn, calls);
for_vector(CallExpr, call, calls) {
if (FnSymbol* calledFn = call->resolvedFunction()) {
if (isTaskFun(calledFn) ||
calledFn->hasFlag(FLAG_COBEGIN_OR_COFORALL_BLOCK)) {
auto pair = llvmPrintIrCNames.insert(calledFn->cname);
if (pair.second) {
// it was inserted
changed = true;
}
}
}
}
}
}
} while (changed);
// If running in compiler-driver mode, save cnames to print IR for to disk.
// This is so that handlePrintAsm can access them later from the makeBinary
// phase, when we don't have a way to determine name->cname correspondence.
if (fDriverCompilationPhase) {
saveDriverTmpMultiple(cnamesToPrintFilename, std::vector<std::string_view>(
llvmPrintIrCNames.begin(),
llvmPrintIrCNames.end()));
}
}
/******************************** | *********************************
* *
* *
********************************* | ********************************/
GenRet Symbol::codegen() {
GenInfo* info = gGenInfo;
GenRet ret;
if( info->cfile ) ret.c = cname;
return ret;
}
void Symbol::codegenDef() {
INT_FATAL(this, "Unanticipated call to Symbol::codegenDef");
}
void Symbol::codegenPrototype() { }
/******************************** | *********************************
* *
* *
********************************* | ********************************/
#ifdef HAVE_LLVM
static
llvm::Value* codegenImmediateLLVM(Immediate* i)
{
GenInfo* info = gGenInfo;
llvm::Value* ret = NULL;
switch(i->const_kind) {
case NUM_KIND_BOOL:
switch(i->num_index) {
case BOOL_SIZE_SYS:
ret = llvm::ConstantInt::get(
llvm::Type::getInt8Ty(info->module->getContext()),
i->bool_value());
break;
}
break;
case NUM_KIND_UINT:
switch(i->num_index) {
case INT_SIZE_8:
ret = llvm::ConstantInt::get(
llvm::Type::getInt8Ty(info->module->getContext()),
i->uint_value());
break;
case INT_SIZE_16:
ret = llvm::ConstantInt::get(
llvm::Type::getInt16Ty(info->module->getContext()),
i->uint_value());
break;
case INT_SIZE_32:
ret = llvm::ConstantInt::get(
llvm::Type::getInt32Ty(info->module->getContext()),
i->uint_value());
break;
case INT_SIZE_64:
ret = llvm::ConstantInt::get(
llvm::Type::getInt64Ty(info->module->getContext()),
i->uint_value());
break;
}
break;
case NUM_KIND_COMMID:
ret = llvm::ConstantInt::get(
llvm::Type::getInt64Ty(info->module->getContext()),
i->commid_value(),
true);
break;
case NUM_KIND_INT:
switch(i->num_index) {
case INT_SIZE_8:
ret = llvm::ConstantInt::get(
llvm::Type::getInt8Ty(info->module->getContext()),
i->int_value(),
true);
break;
case INT_SIZE_16:
ret = llvm::ConstantInt::get(
llvm::Type::getInt16Ty(info->module->getContext()),
i->int_value(),
true);
break;
case INT_SIZE_32:
ret = llvm::ConstantInt::get(
llvm::Type::getInt32Ty(info->module->getContext()),
i->int_value(),
true);
break;
case INT_SIZE_64:
ret = llvm::ConstantInt::get(
llvm::Type::getInt64Ty(info->module->getContext()),
i->int_value(),
true);
break;
}
break;
case NUM_KIND_REAL:
case NUM_KIND_IMAG:
switch(i->num_index) {
case FLOAT_SIZE_32:
ret = llvm::ConstantFP::get(
llvm::Type::getFloatTy(info->module->getContext()),
i->v_float32);
break;
case FLOAT_SIZE_64:
ret = llvm::ConstantFP::get(
llvm::Type::getDoubleTy(info->module->getContext()),
i->v_float64);
break;
default:
INT_ASSERT("unsupported floating point width");
}
break;
case NUM_KIND_COMPLEX:
switch(i->num_index) {
case COMPLEX_SIZE_64: {
std::vector<llvm::Constant *> elements(2);
elements[0] = llvm::ConstantFP::get(
llvm::Type::getFloatTy(info->module->getContext()),
i->v_complex64.r);
elements[1] = llvm::ConstantFP::get(
llvm::Type::getFloatTy(info->module->getContext()),
i->v_complex64.i);
ret = llvm::ConstantStruct::get(
llvm::cast<llvm::StructType>(getTypeLLVM("_complex64")),
elements);
break;
}
case COMPLEX_SIZE_128: {
std::vector<llvm::Constant *> elements(2);
elements[0] = llvm::ConstantFP::get(
llvm::Type::getDoubleTy(info->module->getContext()),
i->v_complex128.r);
elements[1] = llvm::ConstantFP::get(
llvm::Type::getDoubleTy(info->module->getContext()),
i->v_complex128.i);
ret = llvm::ConstantStruct::get(
llvm::cast<llvm::StructType>(getTypeLLVM("_complex128")),
elements);
break;
}
default:
INT_ASSERT("unsupported complex floating point width");
}
break;
case CONST_KIND_STRING:
// Note that string immediate values are stored
// with C escapes - that is newline is 2 chars \ n
// so we have to convert to a sequence of bytes
// for LLVM (the C backend can just print it out).
std::string newString = chpl::unescapeStringC(i->v_string.c_str());
ret = info->irBuilder->CreateGlobalString(newString);
trackLLVMValue(ret);
break;
}
return ret;
}
#endif
GenRet VarSymbol::codegenVarSymbol(bool lhsInSetReference) {
GenInfo* info = gGenInfo;
FILE* outfile = info->cfile;
GenRet ret;
ret.chplType = typeInfo();
if (id == breakOnCodegenID)
debuggerBreakHere();
if( outfile ) {
// dtString immediates don't actually codegen as immediates, we just use
// them for param string functionality.
if (immediate && ret.chplType != dtString && ret.chplType != dtBytes) {
ret.isLVPtr = GEN_VAL;
if (immediate->const_kind == CONST_KIND_STRING) {
ret.c += '"';
ret.c += immediate->v_string.c_str();
ret.c += '"';
} else if (immediate->const_kind == NUM_KIND_BOOL) {
std::string bstring = (immediate->bool_value())?"true":"false";
const char* castString = "(";
switch (immediate->num_index) {
case BOOL_SIZE_SYS:
castString = "UINT8(";
break;
default:
INT_FATAL("Unexpected immediate->num_index: %d\n", immediate->num_index);
}
ret.c = castString + bstring + ")";
} else if (immediate->const_kind == NUM_KIND_INT) {
int64_t iconst = immediate->int_value();
if (iconst == (1ll<<63)) {
ret.c = "(-INT64(9223372036854775807) - INT64(1))";
} else if (iconst <= -2147483648ll || iconst >= 2147483647ll) {
ret.c = "INT64(" + int64_to_string(iconst) + ")";
} else {
const char* castString = "(";
switch (immediate->num_index) {
case INT_SIZE_8:
castString = "INT8(";
break;
case INT_SIZE_16:
castString = "INT16(";
break;
case INT_SIZE_32:
castString = "INT32(";
break;
case INT_SIZE_64:
castString = "INT64(";
break;
default:
INT_FATAL("Unexpected immediate->num_index: %d\n", immediate->num_index);
}
ret.c = castString + int64_to_string(iconst) + ")";
}
} else if (immediate->const_kind == NUM_KIND_UINT) {
uint64_t uconst = immediate->uint_value();
if( uconst <= (uint64_t) INT32_MAX ) {
const char* castString = "(";
switch (immediate->num_index) {
case INT_SIZE_8:
castString = "UINT8(";
break;
case INT_SIZE_16:
castString = "UINT16(";
break;
case INT_SIZE_32:
castString = "UINT32(";
break;
case INT_SIZE_64:
castString = "UINT64(";
break;
default:
INT_FATAL("Unexpected immediate->num_index: %d\n", immediate->num_index);
}
ret.c = castString + uint64_to_string(uconst) + ")";
} else {
ret.c = "UINT64(" + uint64_to_string(uconst) + ")";
}
} else if (immediate->const_kind == NUM_KIND_COMMID) {
int64_t iconst = immediate->commid_value();
if (iconst == (1ll<<63)) {
ret.c = "(-COMMID(9223372036854775807) - COMMID(1))";
} else {
INT_ASSERT(immediate->num_index == INT_SIZE_64);
ret.c = "COMMID(" + int64_to_string(iconst) + ")";
}
} else if (immediate->const_kind == NUM_KIND_REAL ||
immediate->const_kind == NUM_KIND_IMAG) {
double value = immediate->real_value();
const char* castString = NULL;
switch (immediate->num_index) {
case FLOAT_SIZE_32:
castString = "REAL32(";
break;
case FLOAT_SIZE_64:
castString = "REAL64(";
break;
default:
INT_FATAL("Unexpected immediate->num_index");
}
ret.c = castString + real_to_string(value) + ")";
} else if (immediate->const_kind == NUM_KIND_COMPLEX) {
IF1_float_type flType = FLOAT_SIZE_32;
const char* chplComplexN = NULL;
switch(immediate->num_index) {
case COMPLEX_SIZE_64:
flType = FLOAT_SIZE_32;
chplComplexN = "_chpl_complex64";
break;
case COMPLEX_SIZE_128:
flType = FLOAT_SIZE_64;
chplComplexN = "_chpl_complex128";
break;
default:
INT_ASSERT("unsupported complex floating point width");
}
Immediate r_imm = getDefaultImmediate(dtReal[flType]);
Immediate i_imm = getDefaultImmediate(dtImag[flType]);
// get the real and imaginary parts
coerce_immediate(gContext, immediate, &r_imm);
coerce_immediate(gContext, immediate, &i_imm);
VarSymbol* r = new_ImmediateSymbol(&r_imm);
VarSymbol* i = new_ImmediateSymbol(&i_imm);
ret = codegenCallExpr(chplComplexN,
new SymExpr(r),
new SymExpr(i));
ret.chplType = typeInfo();
} else {
INT_FATAL("Unexpected immediate type");
}
} else {
// not immediate
// is it a constant extern? If it is, it might be for example
// an enum or #define'd value, in which case taking the address
// of it is simply nonsense. Therefore, we code generate
// extern const symbols as GEN_VAL (ie not an lvalue).
if( hasFlag(FLAG_CONST) && hasFlag(FLAG_EXTERN) ) {
ret.isLVPtr = GEN_VAL;
ret.c = cname;
} else {
QualifiedType qt = qualType();
if (lhsInSetReference) {
ret.c = '&';
ret.c += cname;
ret.isLVPtr = GEN_PTR;
if (qt.isRef() && !qt.isRefType())
ret.chplType = getOrMakeRefTypeDuringCodegen(typeInfo());
else if (qt.isWideRef() && !qt.isWideRefType()) {
Type* refType = getOrMakeRefTypeDuringCodegen(typeInfo());
ret.chplType = getOrMakeWideTypeDuringCodegen(refType);
}
} else {
if (qt.isRef() && !qt.isRefType()) {
ret.c = cname;
ret.isLVPtr = GEN_PTR;
} else if(qt.isWideRef() && !qt.isWideRefType()) {
ret.c = cname;
ret.isLVPtr = GEN_WIDE_PTR;
} else {
ret.c = '&';
ret.c += cname;
ret.isLVPtr = GEN_PTR;
}
}
}
// Print string contents in a comment if developer mode
// and savec is set.
if (developer &&
!saveCDir.empty() &&
immediate &&
ret.chplType == dtString &&
immediate->const_kind == CONST_KIND_STRING) {
if (strstr(immediate->v_string.c_str(), "/*") ||
strstr(immediate->v_string.c_str(), "*/")) {
// Don't emit comment b/c string contained comment character.
} else {
ret.c += " /* \"";
ret.c += immediate->v_string.c_str();
ret.c += "\" */";
}
}
}
return ret;
} else {
#ifdef HAVE_LLVM
// for LLVM
// Handle extern type variables.
if( hasFlag(FLAG_EXTERN) && isType() ) {
// code generate the type.
GenRet got = typeInfo();
return got;
}
// for nil, generate a void pointer of chplType dtNil
// to allow LLVM pointer cast
// e.g. T = ( (locale) (nil) );
//
// We would just compare against dtNil, but in some cases
// the code generator needs to assign e.g.
// _ret:dtNil = nil
if( typeInfo() == dtNil && 0 == strcmp(cname, "nil") ) {
GenRet voidPtr;
voidPtr.val = llvm::Constant::getNullValue(getPointerType(info->irBuilder));
voidPtr.chplType = dtNil;
return voidPtr;
}
if (typeInfo() == dtBool){
// since "true" and "false" are read into the LVT during ReadMacrosAction
// they will generate an LLVM value of type i32 instead of i8
if (0 == strcmp(cname, "false")){
GenRet boolVal = new_UIntSymbol(0, INT_SIZE_8)->codegen();
return boolVal;
}
if (0 == strcmp(cname, "true")){
GenRet boolVal = new_UIntSymbol(1, INT_SIZE_8)->codegen();
return boolVal;
}
}
if(!isImmediate()) {
// check LVT for value
GenRet got = info->lvt->getValue(cname);
got.chplType = typeInfo();
Type* valType = getValType();
if (got.val && hasFlag(FLAG_EXTERN)) {
// extern C arrays might be declared with type c_ptr(eltType)
// (which is a lie but works OK in C). In that event, generate
// a pointer to the first element when the variable is used.
bool cArrayLie = valType->symbol->hasFlag(FLAG_C_PTR_CLASS) &&
info->lvt->isCArray(cname);
if (cArrayLie) {
auto global = llvm::cast<llvm::GlobalValue>(got.val);
INT_ASSERT(global);
llvm::Type* gepTy = global->getValueType();
got.val = info->irBuilder->CreateStructGEP(gepTy, got.val, 0);
got.isLVPtr = GEN_VAL;
trackLLVMValue(got.val);
}
// check for extern global variables where there is a different
// type provided by clang
clang::TypeDecl* unusedCType = nullptr;
clang::ValueDecl* cValue = nullptr;
const char* cCastToType = nullptr;
astlocT cLoc(0, nullptr);
Type* chapelType = got.chplType;
info->lvt->getCDecl(cname, &unusedCType, &cValue, &cCastToType, &cLoc);
llvm::Type* genCType = nullptr;
llvm::Type* genChplType = nullptr;
if (cCastToType) {
genCType = getTypeLLVM(cCastToType);
} else if (cValue) {
genCType = codegenCType(cValue->getType());
}
{
GenRet tmp = chapelType->codegen();
genChplType = tmp.type;
}
if (cValue && llvm::isa<clang::EnumConstantDecl>(cValue)) {
// if there is a mismatch for an enum constant, don't worry about it
// c enum types are always 'int' but code might assume it is smaller
// TODO: should we check this?
} else if (cArrayLie) {
// ignore mismatch for c arrays due to identifying it as the
// same as c_ptr.
} else if (genCType && genChplType && genCType != genChplType) {
USR_FATAL_CONT(this, "type conflict for extern variable '%s'",
name);
if (cCastToType) {
USR_PRINT(cLoc, "the C type is '%s'", cCastToType);
} else {
clang::QualType qt = cValue->getType();
USR_PRINT(cLoc, "the C type is '%s'", qt.getAsString().c_str());
}
USR_PRINT(this, "the Chapel type is '%s'", toString(chapelType));
USR_STOP();
}
}
if (got.val) {
return got;
}
}
if(isImmediate()) {
ret.isLVPtr = GEN_VAL;
if(immediate->const_kind == CONST_KIND_STRING) {
if(llvm::Value *value = info->module->getNamedGlobal(cname)) {
ret.val = value;
ret.isLVPtr = GEN_PTR;
return ret;
}
llvm::Value *constString = codegenImmediateLLVM(immediate);
auto globalConstString = llvm::cast<llvm::GlobalValue>(constString);
llvm::Type* gepTy = globalConstString->getValueType();
llvm::GlobalVariable *globalValue =
llvm::cast<llvm::GlobalVariable>(
info->module->getOrInsertGlobal
(cname, getPointerType(info->irBuilder)));
globalValue->setConstant(true);
if (fDynoLibGenOrUse)
globalValue->setLinkage(llvm::GlobalVariable::LinkOnceODRLinkage);
llvm::Value* gep = info->irBuilder->CreateConstInBoundsGEP2_32(
gepTy, globalConstString, 0, 0);
trackLLVMValue(gep);
globalValue->setInitializer(llvm::cast<llvm::Constant>(gep));
ret.val = globalValue;
ret.isLVPtr = GEN_PTR;
} else {
ret.val = codegenImmediateLLVM(immediate);
}
return ret;
}
if(std::string(cname) == "0") {
// Chapel compiler should not make these.
INT_FATAL(" zero value BOO ");
return ret;
} else if (std::string(cname) == "NULL") {
GenRet voidPtr;
voidPtr.val = llvm::Constant::getNullValue(getPointerType(info->irBuilder));
voidPtr.chplType = typeInfo();
return voidPtr;
}
#endif
}
USR_FATAL(this->defPoint, "Could not find C variable %s - "
"perhaps it is a complex macro?", cname);
return ret;
}
GenRet VarSymbol::codegen() {
return codegenVarSymbol(true);
}
void VarSymbol::codegenDefC(bool global, bool isHeader) {
GenInfo* info = gGenInfo;
if (this->hasFlag(FLAG_EXTERN) && !this->hasFlag(FLAG_GENERATE_SIGNATURE))
return;
if (type == dtNothing || type == dtVoid)
return;
AggregateType* ct = toAggregateType(type);
QualifiedType qt = qualType();
if (qt.isRef() && !qt.isRefType()) {
Type* refType = getOrMakeRefTypeDuringCodegen(type);
ct = toAggregateType(refType);
}
if (qt.isWideRef() && !qt.isWideRefType()) {
Type* refType = getOrMakeRefTypeDuringCodegen(type);
Type* wideType = getOrMakeWideTypeDuringCodegen(refType);
ct = toAggregateType(wideType);
}
Type* useType = type;
if (ct) useType = ct;
std::string typestr = (this->hasFlag(FLAG_SUPER_CLASS) ?
std::string(toAggregateType(useType)->classStructName(true)) :
useType->codegen().c);
//
// a variable can be codegen'd as static if it is global and neither
// exported nor external.
//
std::string str;
if(fIncrementalCompilation || (this->hasFlag(FLAG_EXTERN) &&
this->hasFlag(FLAG_GENERATE_SIGNATURE))) {
bool addExtern = global && isHeader;
str = (addExtern ? "extern " : "") + typestr + " " + cname;
} else {
bool isStatic = global && !hasFlag(FLAG_EXPORT) && !hasFlag(FLAG_EXTERN);
str = (isStatic ? "static " : "") + typestr + " " + cname;
}
if (ct) {
if (ct->isClass()) {
if (isFnSymbol(defPoint->parentSymbol)) {
str += " = NULL";
}
} else if (ct->symbol->hasFlag(FLAG_WIDE_REF) ||
ct->symbol->hasFlag(FLAG_WIDE_CLASS)) {
if (isFnSymbol(defPoint->parentSymbol)) {
//
// CHPL_LOCALEID_T_INIT is #defined in the chpl-locale-model.h
// file in the runtime, for the selected locale model.
//
str += " = {CHPL_LOCALEID_T_INIT, NULL}";
}
}
}
if (fGenIDS)
str = idCommentTemp(this) + str;
if (printCppLineno && !isHeader && !isTypeSymbol(defPoint->parentSymbol))
str = zlineToString(this) + str;
info->cLocalDecls.push_back(str);
}
void VarSymbol::codegenGlobalDef(bool isHeader) {
GenInfo* info = gGenInfo;
if( id == breakOnCodegenID ||
(breakOnCodegenCname[0] &&
0 == strcmp(cname, breakOnCodegenCname)) ) {
debuggerBreakHere();
}
if( info->cfile ) {
codegenDefC(/*global=*/true, isHeader);
} else {
#ifdef HAVE_LLVM
if(type == dtNothing || !isHeader) {
return;
}
if( this->hasFlag(FLAG_EXTERN) ) {
// Make sure that it already exists in the layered value table.
if( isType() ) {
llvm::Type* t = info->lvt->getType(cname);
if( ! t ) {
// TODO should be USR_FATAL
USR_WARN(this, "Could not find extern def of type %s", cname);
}
} else {
GenRet v = info->lvt->getValue(cname);
if( ! v.val ) {
// TODO should be USR_FATAL
// Commenting out to prevent problems with S_IRWXU and friends
// USR_WARN(this, "Could not find extern def of %s", cname);
}
}
} else {
bool existing;
existing = (info->module->getNamedValue(cname) != NULL);
if( existing )
INT_FATAL(this, "Redefinition of a global variable %s", cname);
// Now, create a global variable with appropriate linkage.
llvm::Type* llTy = type->codegen().type;
INT_ASSERT(llTy);
auto linkage = llvm::GlobalVariable::InternalLinkage;
if (fDynoLibGenOrUse)
linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
if (hasFlag(FLAG_EXPORT))
linkage = llvm::GlobalVariable::ExternalLinkage;
llvm::GlobalVariable *gVar =
new llvm::GlobalVariable(
*info->module,
llTy,
false, /* is constant */
linkage,
llvm::Constant::getNullValue(llTy), /* initializer, */
cname);
trackLLVMValue(gVar);
info->lvt->addGlobalValue(cname, gVar, GEN_PTR, ! isSignedType(type), type);
gVar->setDSOLocal(true);
setValueAlignment(gVar, type, this);
if (debugInfo && debugInfo->shouldAddDebugInfoFor(this)) {
auto di = debugInfo->getGlobalVariable(this);
if (di) {
gVar->addDebugInfo(di);
}
}
}
#endif
}
}
void VarSymbol::codegenDef() {
GenInfo* info = gGenInfo;
if (id == breakOnCodegenID)
debuggerBreakHere();
// Local variable symbols should never be
// generated for extern or void types
if (this->hasFlag(FLAG_EXTERN))
return;
if (type == dtNothing || type == dtVoid)
return;
// Check sizes for c_array
if (type->symbol->hasFlag(FLAG_C_ARRAY)) {
int64_t sizeInt = toAggregateType(type)->cArrayLength();
if (sizeInt > INT_MAX)