forked from ispc/ispc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ctx.cpp
4127 lines (3535 loc) · 156 KB
/
ctx.cpp
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 (c) 2010-2015, Intel Corporation
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/** @file ctx.cpp
@brief Implementation of the FunctionEmitContext class
*/
#include "ctx.h"
#include "util.h"
#include "func.h"
#include "llvmutil.h"
#include "type.h"
#include "stmt.h"
#include "expr.h"
#include "module.h"
#include "sym.h"
#include <map>
#include <llvm/Support/Dwarf.h>
#if ISPC_LLVM_VERSION == ISPC_LLVM_3_2
#include <llvm/Metadata.h>
#include <llvm/Module.h>
#include <llvm/Instructions.h>
#include <llvm/DerivedTypes.h>
#else
#include <llvm/IR/Metadata.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/DerivedTypes.h>
#endif
#ifdef ISPC_NVPTX_ENABLED
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/FormattedStream.h>
#endif /* ISPC_NVPTX_ENABLED */
/** This is a small utility structure that records information related to one
level of nested control flow. It's mostly used in correctly restoring
the mask and other state as we exit control flow nesting levels.
*/
struct CFInfo {
/** Returns a new instance of the structure that represents entering an
'if' statement */
static CFInfo *GetIf(bool isUniform, llvm::Value *savedMask);
/** Returns a new instance of the structure that represents entering a
loop. */
static CFInfo *GetLoop(bool isUniform, llvm::BasicBlock *breakTarget,
llvm::BasicBlock *continueTarget,
llvm::Value *savedBreakLanesPtr,
llvm::Value *savedContinueLanesPtr,
llvm::Value *savedMask, llvm::Value *savedBlockEntryMask);
static CFInfo *GetForeach(FunctionEmitContext::ForeachType ft,
llvm::BasicBlock *breakTarget,
llvm::BasicBlock *continueTarget,
llvm::Value *savedBreakLanesPtr,
llvm::Value *savedContinueLanesPtr,
llvm::Value *savedMask, llvm::Value *savedBlockEntryMask);
static CFInfo *GetSwitch(bool isUniform, llvm::BasicBlock *breakTarget,
llvm::BasicBlock *continueTarget,
llvm::Value *savedBreakLanesPtr,
llvm::Value *savedContinueLanesPtr,
llvm::Value *savedMask, llvm::Value *savedBlockEntryMask,
llvm::Value *switchExpr,
llvm::BasicBlock *bbDefault,
const std::vector<std::pair<int, llvm::BasicBlock *> > *bbCases,
const std::map<llvm::BasicBlock *, llvm::BasicBlock *> *bbNext,
bool scUniform);
bool IsIf() { return type == If; }
bool IsLoop() { return type == Loop; }
bool IsForeach() { return (type == ForeachRegular ||
type == ForeachActive ||
type == ForeachUnique); }
bool IsSwitch() { return type == Switch; }
bool IsVarying() { return !isUniform; }
bool IsUniform() { return isUniform; }
enum CFType { If, Loop, ForeachRegular, ForeachActive, ForeachUnique,
Switch };
CFType type;
bool isUniform;
llvm::BasicBlock *savedBreakTarget, *savedContinueTarget;
llvm::Value *savedBreakLanesPtr, *savedContinueLanesPtr;
llvm::Value *savedMask, *savedBlockEntryMask;
llvm::Value *savedSwitchExpr;
llvm::BasicBlock *savedDefaultBlock;
const std::vector<std::pair<int, llvm::BasicBlock *> > *savedCaseBlocks;
const std::map<llvm::BasicBlock *, llvm::BasicBlock *> *savedNextBlocks;
bool savedSwitchConditionWasUniform;
private:
CFInfo(CFType t, bool uniformIf, llvm::Value *sm) {
Assert(t == If);
type = t;
isUniform = uniformIf;
savedBreakTarget = savedContinueTarget = NULL;
savedBreakLanesPtr = savedContinueLanesPtr = NULL;
savedMask = savedBlockEntryMask = sm;
savedSwitchExpr = NULL;
savedDefaultBlock = NULL;
savedCaseBlocks = NULL;
savedNextBlocks = NULL;
}
CFInfo(CFType t, bool iu, llvm::BasicBlock *bt, llvm::BasicBlock *ct,
llvm::Value *sb, llvm::Value *sc, llvm::Value *sm,
llvm::Value *lm, llvm::Value *sse = NULL, llvm::BasicBlock *bbd = NULL,
const std::vector<std::pair<int, llvm::BasicBlock *> > *bbc = NULL,
const std::map<llvm::BasicBlock *, llvm::BasicBlock *> *bbn = NULL,
bool scu = false) {
Assert(t == Loop || t == Switch);
type = t;
isUniform = iu;
savedBreakTarget = bt;
savedContinueTarget = ct;
savedBreakLanesPtr = sb;
savedContinueLanesPtr = sc;
savedMask = sm;
savedBlockEntryMask = lm;
savedSwitchExpr = sse;
savedDefaultBlock = bbd;
savedCaseBlocks = bbc;
savedNextBlocks = bbn;
savedSwitchConditionWasUniform = scu;
}
CFInfo(CFType t, llvm::BasicBlock *bt, llvm::BasicBlock *ct,
llvm::Value *sb, llvm::Value *sc, llvm::Value *sm,
llvm::Value *lm) {
Assert(t == ForeachRegular || t == ForeachActive || t == ForeachUnique);
type = t;
isUniform = false;
savedBreakTarget = bt;
savedContinueTarget = ct;
savedBreakLanesPtr = sb;
savedContinueLanesPtr = sc;
savedMask = sm;
savedBlockEntryMask = lm;
savedSwitchExpr = NULL;
savedDefaultBlock = NULL;
savedCaseBlocks = NULL;
savedNextBlocks = NULL;
}
};
CFInfo *
CFInfo::GetIf(bool isUniform, llvm::Value *savedMask) {
return new CFInfo(If, isUniform, savedMask);
}
CFInfo *
CFInfo::GetLoop(bool isUniform, llvm::BasicBlock *breakTarget,
llvm::BasicBlock *continueTarget,
llvm::Value *savedBreakLanesPtr,
llvm::Value *savedContinueLanesPtr,
llvm::Value *savedMask, llvm::Value *savedBlockEntryMask) {
return new CFInfo(Loop, isUniform, breakTarget, continueTarget,
savedBreakLanesPtr, savedContinueLanesPtr,
savedMask, savedBlockEntryMask);
}
CFInfo *
CFInfo::GetForeach(FunctionEmitContext::ForeachType ft,
llvm::BasicBlock *breakTarget,
llvm::BasicBlock *continueTarget,
llvm::Value *savedBreakLanesPtr,
llvm::Value *savedContinueLanesPtr,
llvm::Value *savedMask, llvm::Value *savedForeachMask) {
CFType cfType;
switch (ft) {
case FunctionEmitContext::FOREACH_REGULAR:
cfType = ForeachRegular;
break;
case FunctionEmitContext::FOREACH_ACTIVE:
cfType = ForeachActive;
break;
case FunctionEmitContext::FOREACH_UNIQUE:
cfType = ForeachUnique;
break;
default:
FATAL("Unhandled foreach type");
return NULL;
}
return new CFInfo(cfType, breakTarget, continueTarget,
savedBreakLanesPtr, savedContinueLanesPtr,
savedMask, savedForeachMask);
}
CFInfo *
CFInfo::GetSwitch(bool isUniform, llvm::BasicBlock *breakTarget,
llvm::BasicBlock *continueTarget,
llvm::Value *savedBreakLanesPtr,
llvm::Value *savedContinueLanesPtr, llvm::Value *savedMask,
llvm::Value *savedBlockEntryMask, llvm::Value *savedSwitchExpr,
llvm::BasicBlock *savedDefaultBlock,
const std::vector<std::pair<int, llvm::BasicBlock *> > *savedCases,
const std::map<llvm::BasicBlock *, llvm::BasicBlock *> *savedNext,
bool savedSwitchConditionUniform) {
return new CFInfo(Switch, isUniform, breakTarget, continueTarget,
savedBreakLanesPtr, savedContinueLanesPtr,
savedMask, savedBlockEntryMask, savedSwitchExpr, savedDefaultBlock,
savedCases, savedNext, savedSwitchConditionUniform);
}
///////////////////////////////////////////////////////////////////////////
FunctionEmitContext::FunctionEmitContext(Function *func, Symbol *funSym,
llvm::Function *lf,
SourcePos firstStmtPos) {
function = func;
llvmFunction = lf;
/* Create a new basic block to store all of the allocas */
allocaBlock = llvm::BasicBlock::Create(*g->ctx, "allocas", llvmFunction, 0);
bblock = llvm::BasicBlock::Create(*g->ctx, "entry", llvmFunction, 0);
/* But jump from it immediately into the real entry block */
llvm::BranchInst::Create(bblock, allocaBlock);
funcStartPos = funSym->pos;
internalMaskPointer = AllocaInst(LLVMTypes::MaskType, "internal_mask_memory");
StoreInst(LLVMMaskAllOn, internalMaskPointer);
functionMaskValue = LLVMMaskAllOn;
fullMaskPointer = AllocaInst(LLVMTypes::MaskType, "full_mask_memory");
StoreInst(LLVMMaskAllOn, fullMaskPointer);
blockEntryMask = NULL;
breakLanesPtr = continueLanesPtr = NULL;
breakTarget = continueTarget = NULL;
switchExpr = NULL;
caseBlocks = NULL;
defaultBlock = NULL;
nextBlocks = NULL;
returnedLanesPtr = AllocaInst(LLVMTypes::MaskType, "returned_lanes_memory");
StoreInst(LLVMMaskAllOff, returnedLanesPtr);
launchedTasks = false;
launchGroupHandlePtr = AllocaInst(LLVMTypes::VoidPointerType, "launch_group_handle");
StoreInst(llvm::Constant::getNullValue(LLVMTypes::VoidPointerType),
launchGroupHandlePtr);
disableGSWarningCount = 0;
const Type *returnType = function->GetReturnType();
if (!returnType || returnType->IsVoidType())
returnValuePtr = NULL;
else {
llvm::Type *ftype = returnType->LLVMType(g->ctx);
returnValuePtr = AllocaInst(ftype, "return_value_memory");
}
if (g->opt.disableMaskAllOnOptimizations) {
// This is really disgusting. We want to be able to fool the
// compiler to not be able to reason that the mask is all on, but
// we don't want to pay too much of a price at the start of each
// function to do so.
//
// Therefore: first, we declare a module-static __all_on_mask
// variable that will hold an "all on" mask value. At the start of
// each function, we'll load its value and call SetInternalMaskAnd
// with the result to set the current internal execution mask.
// (This is a no-op at runtime.)
//
// Then, to fool the optimizer that maybe the value of
// __all_on_mask can't be guaranteed to be "all on", we emit a
// dummy function that sets __all_on_mask be "all off". (That
// function is never actually called.)
llvm::Value *globalAllOnMaskPtr =
m->module->getNamedGlobal("__all_on_mask");
if (globalAllOnMaskPtr == NULL) {
globalAllOnMaskPtr =
new llvm::GlobalVariable(*m->module, LLVMTypes::MaskType, false,
llvm::GlobalValue::InternalLinkage,
LLVMMaskAllOn, "__all_on_mask");
char buf[256];
sprintf(buf, "__off_all_on_mask_%s", g->target->GetISAString());
llvm::Constant *offFunc =
m->module->getOrInsertFunction(buf, LLVMTypes::VoidType,
NULL);
AssertPos(currentPos, llvm::isa<llvm::Function>(offFunc));
llvm::BasicBlock *offBB =
llvm::BasicBlock::Create(*g->ctx, "entry",
(llvm::Function *)offFunc, 0);
llvm::StoreInst *inst =
new llvm::StoreInst(LLVMMaskAllOff, globalAllOnMaskPtr, offBB);
if (g->opt.forceAlignedMemory) {
inst->setAlignment(g->target->getNativeVectorAlignment());
}
llvm::ReturnInst::Create(*g->ctx, offBB);
}
llvm::Value *allOnMask = LoadInst(globalAllOnMaskPtr, "all_on_mask");
SetInternalMaskAnd(LLVMMaskAllOn, allOnMask);
}
if (m->diBuilder) {
currentPos = funSym->pos;
/* If debugging is enabled, tell the debug information emission
code about this new function */
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_6 /* 3.2, 3.3, 3.4, 3.5, 3.6 */
diFile = funcStartPos.GetDIFile();
AssertPos(currentPos, diFile.Verify());
#else /* LLVM 3.7+ */
diFile = funcStartPos.GetDIFile();
#endif
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_3 /* 3.2, 3.3 */
llvm::DIScope scope = llvm::DIScope(m->diBuilder->getCU());
#elif ISPC_LLVM_VERSION <= ISPC_LLVM_3_6 /* 3.4, 3.5, 3.6 */
llvm::DIScope scope = llvm::DIScope(m->diCompileUnit);
#else /* LLVM 3.7+ */
llvm::DIScope *scope = m->diCompileUnit;
//llvm::MDScope *scope = m->diCompileUnit;
#endif
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_6 /* 3.2, 3.3, 3.4, 3.5, 3.6 */
llvm::DIType diSubprogramType;
AssertPos(currentPos, scope.Verify());
#else /* LLVM 3.7+ */
llvm::DIType *diSubprogramType = NULL;
//llvm::MDType *diSubprogramType = NULL;
#endif
const FunctionType *functionType = function->GetType();
if (functionType == NULL)
AssertPos(currentPos, m->errorCount > 0);
else {
diSubprogramType = functionType->GetDIType(scope);
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_6 /* 3.2, 3.3, 3.4, 3.5, 3.6 */
AssertPos(currentPos, diSubprogramType.Verify());
#else /* LLVM 3.7+ */
//comming soon
#endif
}
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_3 /* 3.2, 3.3 */
llvm::DIType diSubprogramType_n = diSubprogramType;
int flags = llvm::DIDescriptor::FlagPrototyped;
#elif ISPC_LLVM_VERSION <= ISPC_LLVM_3_6 /* 3.4, 3.5, 3.6 */
Assert(diSubprogramType.isCompositeType());
llvm::DICompositeType diSubprogramType_n =
static_cast<llvm::DICompositeType>(diSubprogramType);
int flags = llvm::DIDescriptor::FlagPrototyped;
#elif ISPC_LLVM_VERSION == ISPC_LLVM_3_7 /* LLVM 3.7 */
Assert(llvm::isa<llvm::DICompositeTypeBase>(diSubprogramType));
llvm::DISubroutineType *diSubprogramType_n =
llvm::cast<llvm::DISubroutineType>(getDICompositeType(diSubprogramType));
int flags = llvm::DINode::FlagPrototyped;
#else /* LLVM 3.8+ */
Assert(llvm::isa<llvm::DISubroutineType>(diSubprogramType));
llvm::DISubroutineType *diSubprogramType_n = llvm::cast<llvm::DISubroutineType>(diSubprogramType);
int flags = llvm::DINode::FlagPrototyped;
#endif
std::string mangledName = llvmFunction->getName();
if (mangledName == funSym->name)
mangledName = "";
bool isStatic = (funSym->storageClass == SC_STATIC);
bool isOptimized = (g->opt.level > 0);
int firstLine = funcStartPos.first_line;
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_6 /* 3.2, 3.3, 3.4, 3.5, 3.6 */
diSubprogram =
m->diBuilder->createFunction(diFile /* scope */, funSym->name,
mangledName, diFile,
firstLine, diSubprogramType_n,
isStatic, true, /* is defn */
firstLine, flags,
isOptimized, llvmFunction);
AssertPos(currentPos, diSubprogram.Verify());
#elif ISPC_LLVM_VERSION == ISPC_LLVM_3_7 /* LLVM 3.7 */
diSubprogram =
m->diBuilder->createFunction(diFile /* scope */, funSym->name,
mangledName, diFile,
firstLine, diSubprogramType_n,
isStatic, true, /* is defn */
firstLine, flags,
isOptimized, llvmFunction);
#else /* LLVM 3.8+ */
diSubprogram =
m->diBuilder->createFunction(diFile /* scope */, funSym->name,
mangledName, diFile,
firstLine, diSubprogramType_n,
isStatic, true, /* is defn */
firstLine, flags,
isOptimized);
#endif
/* And start a scope representing the initial function scope */
StartScope();
}
}
FunctionEmitContext::~FunctionEmitContext() {
AssertPos(currentPos, controlFlowInfo.size() == 0);
AssertPos(currentPos, debugScopes.size() == (m->diBuilder ? 1 : 0));
}
const Function *
FunctionEmitContext::GetFunction() const {
return function;
}
llvm::BasicBlock *
FunctionEmitContext::GetCurrentBasicBlock() {
return bblock;
}
void
FunctionEmitContext::SetCurrentBasicBlock(llvm::BasicBlock *bb) {
bblock = bb;
}
llvm::Value *
FunctionEmitContext::GetFunctionMask() {
return functionMaskValue;
}
llvm::Value *
FunctionEmitContext::GetInternalMask() {
return LoadInst(internalMaskPointer, "load_mask");
}
llvm::Value *
FunctionEmitContext::GetFullMask() {
return BinaryOperator(llvm::Instruction::And, GetInternalMask(),
functionMaskValue, "internal_mask&function_mask");
}
llvm::Value *
FunctionEmitContext::GetFullMaskPointer() {
return fullMaskPointer;
}
void
FunctionEmitContext::SetFunctionMask(llvm::Value *value) {
functionMaskValue = value;
if (bblock != NULL)
StoreInst(GetFullMask(), fullMaskPointer);
}
void
FunctionEmitContext::SetBlockEntryMask(llvm::Value *value) {
blockEntryMask = value;
}
void
FunctionEmitContext::SetInternalMask(llvm::Value *value) {
StoreInst(value, internalMaskPointer);
// kludge so that __mask returns the right value in ispc code.
StoreInst(GetFullMask(), fullMaskPointer);
}
void
FunctionEmitContext::SetInternalMaskAnd(llvm::Value *oldMask, llvm::Value *test) {
llvm::Value *mask = BinaryOperator(llvm::Instruction::And, oldMask,
test, "oldMask&test");
SetInternalMask(mask);
}
void
FunctionEmitContext::SetInternalMaskAndNot(llvm::Value *oldMask, llvm::Value *test) {
llvm::Value *notTest = BinaryOperator(llvm::Instruction::Xor, test, LLVMMaskAllOn,
"~test");
llvm::Value *mask = BinaryOperator(llvm::Instruction::And, oldMask, notTest,
"oldMask&~test");
SetInternalMask(mask);
}
void
FunctionEmitContext::BranchIfMaskAny(llvm::BasicBlock *btrue, llvm::BasicBlock *bfalse) {
AssertPos(currentPos, bblock != NULL);
llvm::Value *any = Any(GetFullMask());
BranchInst(btrue, bfalse, any);
// It's illegal to add any additional instructions to the basic block
// now that it's terminated, so set bblock to NULL to be safe
bblock = NULL;
}
void
FunctionEmitContext::BranchIfMaskAll(llvm::BasicBlock *btrue, llvm::BasicBlock *bfalse) {
AssertPos(currentPos, bblock != NULL);
llvm::Value *all = All(GetFullMask());
BranchInst(btrue, bfalse, all);
// It's illegal to add any additional instructions to the basic block
// now that it's terminated, so set bblock to NULL to be safe
bblock = NULL;
}
void
FunctionEmitContext::BranchIfMaskNone(llvm::BasicBlock *btrue, llvm::BasicBlock *bfalse) {
AssertPos(currentPos, bblock != NULL);
// switch sense of true/false bblocks
BranchIfMaskAny(bfalse, btrue);
// It's illegal to add any additional instructions to the basic block
// now that it's terminated, so set bblock to NULL to be safe
bblock = NULL;
}
void
FunctionEmitContext::StartUniformIf() {
controlFlowInfo.push_back(CFInfo::GetIf(true, GetInternalMask()));
}
void
FunctionEmitContext::StartVaryingIf(llvm::Value *oldMask) {
controlFlowInfo.push_back(CFInfo::GetIf(false, oldMask));
}
void
FunctionEmitContext::EndIf() {
CFInfo *ci = popCFState();
// Make sure we match up with a Start{Uniform,Varying}If().
AssertPos(currentPos, ci->IsIf());
// 'uniform' ifs don't change the mask so we only need to restore the
// mask going into the if for 'varying' if statements
if (ci->IsUniform() || bblock == NULL)
return;
// We can't just restore the mask as it was going into the 'if'
// statement. First we have to take into account any program
// instances that have executed 'return' statements; the restored
// mask must be off for those lanes.
restoreMaskGivenReturns(ci->savedMask);
// If the 'if' statement is inside a loop with a 'varying'
// condition, we also need to account for any break or continue
// statements that executed inside the 'if' statmeent; we also must
// leave the lane masks for the program instances that ran those
// off after we restore the mask after the 'if'. The code below
// ends up being optimized out in the case that there were no break
// or continue statements (and breakLanesPtr and continueLanesPtr
// have their initial 'all off' values), so we don't need to check
// for that here.
//
// There are three general cases to deal with here:
// - Loops: both break and continue are allowed, and thus the corresponding
// lane mask pointers are non-NULL
// - Foreach: only continueLanesPtr may be non-NULL
// - Switch: only breakLanesPtr may be non-NULL
if (continueLanesPtr != NULL || breakLanesPtr != NULL) {
// We want to compute:
// newMask = (oldMask & ~(breakLanes | continueLanes)),
// treading breakLanes or continueLanes as "all off" if the
// corresponding pointer is NULL.
llvm::Value *bcLanes = NULL;
if (continueLanesPtr != NULL)
bcLanes = LoadInst(continueLanesPtr, "continue_lanes");
else
bcLanes = LLVMMaskAllOff;
if (breakLanesPtr != NULL) {
llvm::Value *breakLanes = LoadInst(breakLanesPtr, "break_lanes");
bcLanes = BinaryOperator(llvm::Instruction::Or, bcLanes,
breakLanes, "|break_lanes");
}
llvm::Value *notBreakOrContinue =
BinaryOperator(llvm::Instruction::Xor,
bcLanes, LLVMMaskAllOn,
"!(break|continue)_lanes");
llvm::Value *oldMask = GetInternalMask();
llvm::Value *newMask =
BinaryOperator(llvm::Instruction::And, oldMask,
notBreakOrContinue, "new_mask");
SetInternalMask(newMask);
}
}
void
FunctionEmitContext::StartLoop(llvm::BasicBlock *bt, llvm::BasicBlock *ct,
bool uniformCF) {
// Store the current values of various loop-related state so that we
// can restore it when we exit this loop.
llvm::Value *oldMask = GetInternalMask();
controlFlowInfo.push_back(CFInfo::GetLoop(uniformCF, breakTarget,
continueTarget, breakLanesPtr,
continueLanesPtr, oldMask, blockEntryMask));
if (uniformCF)
// If the loop has a uniform condition, we don't need to track
// which lanes 'break' or 'continue'; all of the running ones go
// together, so we just jump
breakLanesPtr = continueLanesPtr = NULL;
else {
// For loops with varying conditions, allocate space to store masks
// that record which lanes have done these
continueLanesPtr = AllocaInst(LLVMTypes::MaskType, "continue_lanes_memory");
StoreInst(LLVMMaskAllOff, continueLanesPtr);
breakLanesPtr = AllocaInst(LLVMTypes::MaskType, "break_lanes_memory");
StoreInst(LLVMMaskAllOff, breakLanesPtr);
}
breakTarget = bt;
continueTarget = ct;
blockEntryMask = NULL; // this better be set by the loop!
}
void
FunctionEmitContext::EndLoop() {
CFInfo *ci = popCFState();
AssertPos(currentPos, ci->IsLoop());
if (!ci->IsUniform())
// If the loop had a 'uniform' test, then it didn't make any
// changes to the mask so there's nothing to restore. If it had a
// varying test, we need to restore the mask to what it was going
// into the loop, but still leaving off any lanes that executed a
// 'return' statement.
restoreMaskGivenReturns(ci->savedMask);
}
void
FunctionEmitContext::StartForeach(ForeachType ft) {
// Issue an error if we're in a nested foreach...
if (ft == FOREACH_REGULAR) {
for (int i = 0; i < (int)controlFlowInfo.size(); ++i) {
if (controlFlowInfo[i]->type == CFInfo::ForeachRegular) {
Error(currentPos, "Nested \"foreach\" statements are currently "
"illegal.");
break;
// Don't return here, however, and in turn allow the caller to
// do the rest of its codegen and then call EndForeach()
// normally--the idea being that this gives a chance to find
// any other errors inside the body of the foreach loop...
}
}
}
// Store the current values of various loop-related state so that we
// can restore it when we exit this loop.
llvm::Value *oldMask = GetInternalMask();
controlFlowInfo.push_back(CFInfo::GetForeach(ft, breakTarget, continueTarget,
breakLanesPtr, continueLanesPtr,
oldMask, blockEntryMask));
breakLanesPtr = NULL;
breakTarget = NULL;
continueLanesPtr = AllocaInst(LLVMTypes::MaskType, "foreach_continue_lanes");
StoreInst(LLVMMaskAllOff, continueLanesPtr);
continueTarget = NULL; // should be set by SetContinueTarget()
blockEntryMask = NULL;
}
void
FunctionEmitContext::EndForeach() {
CFInfo *ci = popCFState();
AssertPos(currentPos, ci->IsForeach());
}
void
FunctionEmitContext::restoreMaskGivenReturns(llvm::Value *oldMask) {
if (!bblock)
return;
// Restore the mask to the given old mask, but leave off any lanes that
// executed a return statement.
// newMask = (oldMask & ~returnedLanes)
llvm::Value *returnedLanes = LoadInst(returnedLanesPtr,
"returned_lanes");
llvm::Value *notReturned = BinaryOperator(llvm::Instruction::Xor,
returnedLanes, LLVMMaskAllOn,
"~returned_lanes");
llvm::Value *newMask = BinaryOperator(llvm::Instruction::And,
oldMask, notReturned, "new_mask");
SetInternalMask(newMask);
}
/** Returns "true" if the first enclosing non-if control flow expression is
a "switch" statement.
*/
bool
FunctionEmitContext::inSwitchStatement() const {
// Go backwards through controlFlowInfo, since we add new nested scopes
// to the back.
int i = controlFlowInfo.size() - 1;
while (i >= 0 && controlFlowInfo[i]->IsIf())
--i;
// Got to the first non-if (or end of CF info)
if (i == -1)
return false;
return controlFlowInfo[i]->IsSwitch();
}
void
FunctionEmitContext::Break(bool doCoherenceCheck) {
if (breakTarget == NULL) {
Error(currentPos, "\"break\" statement is illegal outside of "
"for/while/do loops and \"switch\" statements.");
return;
}
AssertPos(currentPos, controlFlowInfo.size() > 0);
if (bblock == NULL)
return;
if (inSwitchStatement() == true &&
switchConditionWasUniform == true &&
ifsInCFAllUniform(CFInfo::Switch)) {
// We know that all program instances are executing the break, so
// just jump to the block immediately after the switch.
AssertPos(currentPos, breakTarget != NULL);
BranchInst(breakTarget);
bblock = NULL;
return;
}
// If all of the enclosing 'if' tests in the loop have uniform control
// flow or if we can tell that the mask is all on, then we can just
// jump to the break location.
if (inSwitchStatement() == false && ifsInCFAllUniform(CFInfo::Loop)) {
BranchInst(breakTarget);
// Set bblock to NULL since the jump has terminated the basic block
bblock = NULL;
}
else {
// Varying switch, uniform switch where the 'break' is under
// varying control flow, or a loop with varying 'if's above the
// break. In these cases, we need to update the mask of the lanes
// that have executed a 'break' statement:
// breakLanes = breakLanes | mask
AssertPos(currentPos, breakLanesPtr != NULL);
llvm::Value *mask = GetInternalMask();
llvm::Value *breakMask = LoadInst(breakLanesPtr,
"break_mask");
llvm::Value *newMask = BinaryOperator(llvm::Instruction::Or,
mask, breakMask, "mask|break_mask");
StoreInst(newMask, breakLanesPtr);
// Set the current mask to be all off, just in case there are any
// statements in the same scope after the 'break'. Most of time
// this will be optimized away since we'll likely end the scope of
// an 'if' statement and restore the mask then.
SetInternalMask(LLVMMaskAllOff);
if (doCoherenceCheck) {
if (continueTarget != NULL)
// If the user has indicated that this is a 'coherent'
// break statement, then check to see if the mask is all
// off. If so, we have to conservatively jump to the
// continueTarget, not the breakTarget, since part of the
// reason the mask is all off may be due to 'continue'
// statements that executed in the current loop iteration.
jumpIfAllLoopLanesAreDone(continueTarget);
else if (breakTarget != NULL)
// Similarly handle these for switch statements, where we
// only have a break target.
jumpIfAllLoopLanesAreDone(breakTarget);
}
}
}
static bool
lEnclosingLoopIsForeachActive(const std::vector<CFInfo *> &controlFlowInfo) {
for (int i = (int)controlFlowInfo.size() - 1; i >= 0; --i) {
if (controlFlowInfo[i]->type == CFInfo::ForeachActive)
return true;
}
return false;
}
void
FunctionEmitContext::Continue(bool doCoherenceCheck) {
if (!continueTarget) {
Error(currentPos, "\"continue\" statement illegal outside of "
"for/while/do/foreach loops.");
return;
}
AssertPos(currentPos, controlFlowInfo.size() > 0);
if (ifsInCFAllUniform(CFInfo::Loop) ||
lEnclosingLoopIsForeachActive(controlFlowInfo)) {
// Similarly to 'break' statements, we can immediately jump to the
// continue target if we're only in 'uniform' control flow within
// loop or if we can tell that the mask is all on. Here, we can
// also jump if the enclosing loop is a 'foreach_active' loop, in
// which case we know that only a single program instance is
// executing.
AddInstrumentationPoint("continue: uniform CF, jumped");
BranchInst(continueTarget);
bblock = NULL;
}
else {
// Otherwise update the stored value of which lanes have 'continue'd.
// continueLanes = continueLanes | mask
AssertPos(currentPos, continueLanesPtr);
llvm::Value *mask = GetInternalMask();
llvm::Value *continueMask =
LoadInst(continueLanesPtr, "continue_mask");
llvm::Value *newMask =
BinaryOperator(llvm::Instruction::Or, mask, continueMask,
"mask|continueMask");
StoreInst(newMask, continueLanesPtr);
// And set the current mask to be all off in case there are any
// statements in the same scope after the 'continue'
SetInternalMask(LLVMMaskAllOff);
if (doCoherenceCheck)
// If this is a 'coherent continue' statement, then emit the
// code to see if all of the lanes are now off due to
// breaks/continues and jump to the continue target if so.
jumpIfAllLoopLanesAreDone(continueTarget);
}
}
/** This function checks to see if all of the 'if' statements (if any)
between the current scope and the first enclosing loop/switch of given
control flow type have 'uniform' tests.
*/
bool
FunctionEmitContext::ifsInCFAllUniform(int type) const {
AssertPos(currentPos, controlFlowInfo.size() > 0);
// Go backwards through controlFlowInfo, since we add new nested scopes
// to the back. Stop once we come to the first enclosing control flow
// structure of the desired type.
int i = controlFlowInfo.size() - 1;
while (i >= 0 && controlFlowInfo[i]->type != type) {
if (controlFlowInfo[i]->isUniform == false)
// Found a scope due to an 'if' statement with a varying test
return false;
--i;
}
AssertPos(currentPos, i >= 0); // else we didn't find the expected control flow type!
return true;
}
void
FunctionEmitContext::jumpIfAllLoopLanesAreDone(llvm::BasicBlock *target) {
llvm::Value *allDone = NULL;
if (breakLanesPtr == NULL) {
llvm::Value *continued = LoadInst(continueLanesPtr,
"continue_lanes");
continued = BinaryOperator(llvm::Instruction::And,
continued, GetFunctionMask(),
"continued&func");
allDone = MasksAllEqual(continued, blockEntryMask);
}
else {
// Check to see if (returned lanes | continued lanes | break lanes) is
// equal to the value of mask at the start of the loop iteration. If
// so, everyone is done and we can jump to the given target
llvm::Value *returned = LoadInst(returnedLanesPtr,
"returned_lanes");
llvm::Value *breaked = LoadInst(breakLanesPtr, "break_lanes");
llvm::Value *finishedLanes = BinaryOperator(llvm::Instruction::Or,
returned, breaked,
"returned|breaked");
if (continueLanesPtr != NULL) {
// It's NULL for "switch" statements...
llvm::Value *continued = LoadInst(continueLanesPtr,
"continue_lanes");
finishedLanes = BinaryOperator(llvm::Instruction::Or, finishedLanes,
continued, "returned|breaked|continued");
}
finishedLanes = BinaryOperator(llvm::Instruction::And,
finishedLanes, GetFunctionMask(),
"finished&func");
// Do we match the mask at loop or switch statement entry?
allDone = MasksAllEqual(finishedLanes, blockEntryMask);
}
llvm::BasicBlock *bAll = CreateBasicBlock("all_continued_or_breaked");
llvm::BasicBlock *bNotAll = CreateBasicBlock("not_all_continued_or_breaked");
BranchInst(bAll, bNotAll, allDone);
// If so, have an extra basic block along the way to add
// instrumentation, if the user asked for it.
bblock = bAll;
AddInstrumentationPoint("break/continue: all dynamically went");
BranchInst(target);
// And set the current basic block to a new one for future instructions
// for the path where we weren't able to jump
bblock = bNotAll;
AddInstrumentationPoint("break/continue: not all went");
}
void
FunctionEmitContext::RestoreContinuedLanes() {
if (continueLanesPtr == NULL)
return;
// mask = mask & continueFlags
llvm::Value *mask = GetInternalMask();
llvm::Value *continueMask = LoadInst(continueLanesPtr,
"continue_mask");
llvm::Value *orMask = BinaryOperator(llvm::Instruction::Or,
mask, continueMask, "mask|continue_mask");
SetInternalMask(orMask);
// continueLanes = 0
StoreInst(LLVMMaskAllOff, continueLanesPtr);
}
void
FunctionEmitContext::ClearBreakLanes() {
if (breakLanesPtr == NULL)
return;
// breakLanes = 0
StoreInst(LLVMMaskAllOff, breakLanesPtr);
}
void
FunctionEmitContext::StartSwitch(bool cfIsUniform, llvm::BasicBlock *bbBreak) {
llvm::Value *oldMask = GetInternalMask();
controlFlowInfo.push_back(CFInfo::GetSwitch(cfIsUniform, breakTarget,
continueTarget, breakLanesPtr,
continueLanesPtr, oldMask,
blockEntryMask, switchExpr, defaultBlock,
caseBlocks, nextBlocks,
switchConditionWasUniform));
breakLanesPtr = AllocaInst(LLVMTypes::MaskType, "break_lanes_memory");
StoreInst(LLVMMaskAllOff, breakLanesPtr);
breakTarget = bbBreak;
continueLanesPtr = NULL;
continueTarget = NULL;