-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathctx.cpp
2020 lines (1734 loc) · 75 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-2011, 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 "llvmutil.h"
#include "type.h"
#include "stmt.h"
#include "expr.h"
#include "module.h"
#include "sym.h"
#include <map>
#include <llvm/DerivedTypes.h>
#include <llvm/Instructions.h>
#include <llvm/Support/Dwarf.h>
#include <llvm/Metadata.h>
#include <llvm/Module.h>
/** 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 *savedLoopMask);
bool IsIf() { return type == If; }
bool IsLoop() { return type == Loop; }
bool IsVaryingType() { return !isUniform; }
bool IsUniform() { return isUniform; }
enum CFType { If, Loop };
CFType type;
bool isUniform;
llvm::BasicBlock *savedBreakTarget, *savedContinueTarget;
llvm::Value *savedBreakLanesPtr, *savedContinueLanesPtr;
llvm::Value *savedMask, *savedLoopMask;
private:
CFInfo(CFType t, bool uniformIf, llvm::Value *sm) {
assert(t == If);
type = t;
isUniform = uniformIf;
savedBreakTarget = savedContinueTarget = NULL;
savedBreakLanesPtr = savedContinueLanesPtr = NULL;
savedMask = savedLoopMask = sm;
}
CFInfo(CFType t, bool iu, llvm::BasicBlock *bt, llvm::BasicBlock *ct,
llvm::Value *sb, llvm::Value *sc, llvm::Value *sm,
llvm::Value *lm) {
assert(t == Loop);
type = t;
isUniform = iu;
savedBreakTarget = bt;
savedContinueTarget = ct;
savedBreakLanesPtr = sb;
savedContinueLanesPtr = sc;
savedMask = sm;
savedLoopMask = lm;
}
};
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 *savedLoopMask) {
return new CFInfo(Loop, isUniform, breakTarget, continueTarget,
savedBreakLanesPtr, savedContinueLanesPtr,
savedMask, savedLoopMask);
}
///////////////////////////////////////////////////////////////////////////
FunctionEmitContext::FunctionEmitContext(const Type *rt, llvm::Function *function,
Symbol *funSym, SourcePos firstStmtPos) {
/* Create a new basic block to store all of the allocas */
allocaBlock = llvm::BasicBlock::Create(*g->ctx, "allocas", function, 0);
bblock = llvm::BasicBlock::Create(*g->ctx, "entry", function, 0);
/* But jump from it immediately into the real entry block */
llvm::BranchInst::Create(bblock, allocaBlock);
maskPtr = AllocaInst(LLVMTypes::MaskType, "mask_memory");
StoreInst(LLVMMaskAllOn, maskPtr);
funcStartPos = funSym->pos;
returnType = rt;
entryMask = NULL;
loopMask = NULL;
breakLanesPtr = continueLanesPtr = NULL;
breakTarget = continueTarget = NULL;
returnedLanesPtr = AllocaInst(LLVMTypes::MaskType, "returned_lanes_memory");
StoreInst(LLVMMaskAllOff, returnedLanesPtr);
if (!returnType || returnType == AtomicType::Void)
returnValuePtr = NULL;
else {
LLVM_TYPE_CONST llvm::Type *ftype = returnType->LLVMType(g->ctx);
returnValuePtr = AllocaInst(ftype, "return_value_memory");
// FIXME: don't do this store???
StoreInst(llvm::Constant::getNullValue(ftype), returnValuePtr);
}
#ifndef LLVM_2_8
if (m->diBuilder) {
/* If debugging is enabled, tell the debug information emission
code about this new function */
diFile = funcStartPos.GetDIFile();
llvm::DIType retType = rt->GetDIType(diFile);
int flags = llvm::DIDescriptor::FlagPrototyped; // ??
diFunction = m->diBuilder->createFunction(diFile, /* scope */
function->getName(), // mangled
funSym->name,
diFile,
funcStartPos.first_line,
retType,
funSym->isStatic,
true, /* is definition */
flags,
g->opt.level > 0,
function);
/* And start a scope representing the initial function scope */
StartScope();
}
#endif // LLVM_2_8
launchedTasks = false;
// connect the funciton's mask memory to the __mask symbol
Symbol *maskSymbol = m->symbolTable->LookupVariable("__mask");
assert(maskSymbol != NULL);
maskSymbol->storagePtr = maskPtr;
#ifndef LLVM_2_8
// add debugging info for __mask, programIndex, ...
if (m->diBuilder) {
maskSymbol->pos = funcStartPos;
EmitVariableDebugInfo(maskSymbol);
llvm::DIFile file = funcStartPos.GetDIFile();
Symbol *programIndexSymbol = m->symbolTable->LookupVariable("programIndex");
assert(programIndexSymbol && programIndexSymbol->storagePtr);
m->diBuilder->createGlobalVariable(programIndexSymbol->name,
file,
funcStartPos.first_line,
programIndexSymbol->type->GetDIType(file),
true /* static */,
programIndexSymbol->storagePtr);
Symbol *programCountSymbol = m->symbolTable->LookupVariable("programCount");
assert(programCountSymbol);
m->diBuilder->createGlobalVariable(programCountSymbol->name,
file,
funcStartPos.first_line,
programCountSymbol->type->GetDIType(file),
true /* static */,
programCountSymbol->storagePtr);
}
#endif
}
FunctionEmitContext::~FunctionEmitContext() {
assert(controlFlowInfo.size() == 0);
#ifndef LLVM_2_8
assert(debugScopes.size() == (m->diBuilder ? 1 : 0));
#endif
}
llvm::BasicBlock *
FunctionEmitContext::GetCurrentBasicBlock() {
return bblock;
}
void
FunctionEmitContext::SetCurrentBasicBlock(llvm::BasicBlock *bb) {
bblock = bb;
}
llvm::Value *
FunctionEmitContext::GetMask() {
return LoadInst(maskPtr, NULL, "load_mask");
}
void
FunctionEmitContext::SetEntryMask(llvm::Value *value) {
entryMask = value;
SetMask(value);
}
void
FunctionEmitContext::SetLoopMask(llvm::Value *value) {
loopMask = value;
}
void
FunctionEmitContext::SetMask(llvm::Value *value) {
StoreInst(value, maskPtr);
}
void
FunctionEmitContext::MaskAnd(llvm::Value *oldMask, llvm::Value *test) {
llvm::Value *mask = BinaryOperator(llvm::Instruction::And, oldMask,
test, "oldMask&test");
SetMask(mask);
}
void
FunctionEmitContext::MaskAndNot(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");
SetMask(mask);
}
void
FunctionEmitContext::BranchIfMaskAny(llvm::BasicBlock *btrue, llvm::BasicBlock *bfalse) {
assert(bblock != NULL);
llvm::Value *any = Any(GetMask());
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) {
assert(bblock != NULL);
llvm::Value *all = All(GetMask());
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) {
assert(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(llvm::Value *oldMask) {
controlFlowInfo.push_back(CFInfo::GetIf(true, oldMask));
}
void
FunctionEmitContext::StartVaryingIf(llvm::Value *oldMask) {
controlFlowInfo.push_back(CFInfo::GetIf(false, oldMask));
}
void
FunctionEmitContext::EndIf() {
// Make sure we match up with a Start{Uniform,Varying}If().
assert(controlFlowInfo.size() > 0 && controlFlowInfo.back()->IsIf());
CFInfo *ci = controlFlowInfo.back();
controlFlowInfo.pop_back();
// '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) {
// 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'
// consdition, 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.
if (breakLanesPtr != NULL) {
assert(continueLanesPtr != NULL);
// newMask = (oldMask & ~(breakLanes | continueLanes))
llvm::Value *oldMask = GetMask();
llvm::Value *breakLanes = LoadInst(breakLanesPtr, NULL,
"break_lanes");
llvm::Value *continueLanes = LoadInst(continueLanesPtr, NULL,
"continue_lanes");
llvm::Value *breakOrContinueLanes =
BinaryOperator(llvm::Instruction::Or, breakLanes, continueLanes,
"break|continue_lanes");
llvm::Value *notBreakOrContinue = NotOperator(breakOrContinueLanes,
"!(break|continue)_lanes");
llvm::Value *newMask =
BinaryOperator(llvm::Instruction::And, oldMask, notBreakOrContinue,
"new_mask");
SetMask(newMask);
}
}
}
void
FunctionEmitContext::StartLoop(llvm::BasicBlock *bt, llvm::BasicBlock *ct,
bool uniformCF, llvm::Value *oldMask) {
// Store the current values of various loop-related state so that we
// can restore it when we exit this loop.
controlFlowInfo.push_back(CFInfo::GetLoop(uniformCF, breakTarget,
continueTarget, breakLanesPtr,
continueLanesPtr, oldMask, loopMask));
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;
loopMask = NULL; // this better be set by the loop!
}
void
FunctionEmitContext::EndLoop() {
assert(controlFlowInfo.size() && !controlFlowInfo.back()->IsIf());
CFInfo *ci = controlFlowInfo.back();
controlFlowInfo.pop_back();
// Restore the break/continue state information to what it was before
// we went into this loop.
breakTarget = ci->savedBreakTarget;
continueTarget = ci->savedContinueTarget;
breakLanesPtr = ci->savedBreakLanesPtr;
continueLanesPtr = ci->savedContinueLanesPtr;
loopMask = ci->savedLoopMask;
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::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, NULL, "returned_lanes");
llvm::Value *notReturned = NotOperator(returnedLanes, "~returned_lanes");
llvm::Value *newMask = BinaryOperator(llvm::Instruction::And,
oldMask, notReturned, "new_mask");
SetMask(newMask);
}
void
FunctionEmitContext::Break(bool doCoherenceCheck) {
if (breakTarget == NULL) {
Error(currentPos, "\"break\" statement is illegal outside of for/while/do loops.");
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 (ifsInLoopAllUniform() || GetMask() == LLVMMaskAllOn) {
BranchInst(breakTarget);
if (ifsInLoopAllUniform() && doCoherenceCheck)
Warning(currentPos, "Coherent break statement not necessary in fully uniform "
"control flow.");
// Set bblock to NULL since the jump has terminated the basic block
bblock = NULL;
}
else {
// Otherwise we need to update the mask of the lanes that have
// executed a 'break' statement:
// breakLanes = breakLanes | mask
assert(breakLanesPtr != NULL);
llvm::Value *mask = GetMask();
llvm::Value *breakMask = LoadInst(breakLanesPtr, NULL, "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.
SetMask(LLVMMaskAllOff);
if (doCoherenceCheck)
// 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.
// FIXME: if the loop only has break statements and no
// continues, we can jump to breakTarget in that case.
jumpIfAllLoopLanesAreDone(continueTarget);
}
}
void
FunctionEmitContext::Continue(bool doCoherenceCheck) {
if (!continueTarget) {
Error(currentPos, "\"continue\" statement illegal outside of for/while/do loops.");
return;
}
if (ifsInLoopAllUniform() || GetMask() == LLVMMaskAllOn) {
// 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.
AddInstrumentationPoint("continue: uniform CF, jumped");
if (ifsInLoopAllUniform() && doCoherenceCheck)
Warning(currentPos, "Coherent continue statement not necessary in fully uniform "
"control flow.");
BranchInst(continueTarget);
bblock = NULL;
}
else {
// Otherwise update the stored value of which lanes have 'continue'd.
// continueLanes = continueLanes | mask
assert(continueLanesPtr);
llvm::Value *mask = GetMask();
llvm::Value *continueMask =
LoadInst(continueLanesPtr, NULL, "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'
SetMask(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 have 'uniform'
tests.
*/
bool
FunctionEmitContext::ifsInLoopAllUniform() const {
assert(controlFlowInfo.size() > 0);
// Go backwards through controlFlowInfo, since we add new nested scopes
// to the back. Stop once we come to the first enclosing loop.
int i = controlFlowInfo.size() - 1;
while (i >= 0 && controlFlowInfo[i]->type != CFInfo::Loop) {
if (controlFlowInfo[i]->isUniform == false)
// Found a scope due to an 'if' statement with a varying test
return false;
--i;
}
assert(i >= 0); // else we didn't find a loop!
return true;
}
void
FunctionEmitContext::jumpIfAllLoopLanesAreDone(llvm::BasicBlock *target) {
// 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, NULL, "returned_lanes");
llvm::Value *continued = LoadInst(continueLanesPtr, NULL, "continue_lanes");
llvm::Value *breaked = LoadInst(breakLanesPtr, NULL, "break_lanes");
llvm::Value *returnedOrContinued = BinaryOperator(llvm::Instruction::Or,
returned, continued,
"returned|continued");
llvm::Value *returnedOrContinuedOrBreaked =
BinaryOperator(llvm::Instruction::Or, returnedOrContinued,
breaked, "returned|continued");
// Do we match the mask at loop entry?
llvm::Value *allRCB = MasksAllEqual(returnedOrContinuedOrBreaked, loopMask);
llvm::BasicBlock *bAll = CreateBasicBlock("all_continued_or_breaked");
llvm::BasicBlock *bNotAll = CreateBasicBlock("not_all_continued_or_breaked");
BranchInst(bAll, bNotAll, allRCB);
// 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 = GetMask();
llvm::Value *continueMask = LoadInst(continueLanesPtr, NULL, "continue_mask");
llvm::Value *orMask = BinaryOperator(llvm::Instruction::Or,
mask, continueMask, "mask|continue_mask");
SetMask(orMask);
// continueLanes = 0
StoreInst(LLVMMaskAllOff, continueLanesPtr);
}
int
FunctionEmitContext::VaryingCFDepth() const {
int sum = 0;
for (unsigned int i = 0; i < controlFlowInfo.size(); ++i)
if (controlFlowInfo[i]->IsVaryingType())
++sum;
return sum;
}
void
FunctionEmitContext::CurrentLanesReturned(Expr *expr, bool doCoherenceCheck) {
if (returnType == AtomicType::Void) {
if (expr != NULL)
Error(expr->pos, "Can't return non-void type \"%s\" from void function.",
expr->GetType()->GetString().c_str());
}
else {
if (expr == NULL) {
Error(funcStartPos,
"Must provide return value for return statement for non-void function.");
return;
}
// Use a masked store to store the value of the expression in the
// return value memory; this preserves the return values from other
// lanes that may have executed return statements previously.
Expr *r = expr->TypeConv(returnType, "return statement");
if (r != NULL) {
llvm::Value *retVal = r->GetValue(this);
StoreInst(retVal, returnValuePtr, GetMask(), returnType);
}
}
if (VaryingCFDepth() == 0) {
// If there is only uniform control flow between us and the
// function entry, then it's guaranteed that all lanes are running,
// so we can just emit a true return instruction
AddInstrumentationPoint("return: uniform control flow");
ReturnInst();
}
else {
// Otherwise we update the returnedLanes value by ANDing it with
// the current lane mask.
llvm::Value *oldReturnedLanes = LoadInst(returnedLanesPtr, NULL,
"old_returned_lanes");
llvm::Value *newReturnedLanes = BinaryOperator(llvm::Instruction::Or,
oldReturnedLanes,
GetMask(), "old_mask|returned_lanes");
// For 'coherent' return statements, emit code to check if all
// lanes have returned
if (doCoherenceCheck) {
// if newReturnedLanes == entryMask, get out of here!
llvm::Value *cmp = MasksAllEqual(entryMask, newReturnedLanes);
llvm::BasicBlock *bDoReturn = CreateBasicBlock("do_return");
llvm::BasicBlock *bNoReturn = CreateBasicBlock("no_return");
BranchInst(bDoReturn, bNoReturn, cmp);
bblock = bDoReturn;
AddInstrumentationPoint("return: all lanes have returned");
ReturnInst();
bblock = bNoReturn;
}
// Otherwise update returnedLanesPtr and turn off all of the lanes
// in the current mask so that any subsequent statements in the
// same scope after the return have no effect
StoreInst(newReturnedLanes, returnedLanesPtr);
AddInstrumentationPoint("return: some but not all lanes have returned");
SetMask(LLVMMaskAllOff);
}
}
llvm::Value *
FunctionEmitContext::Any(llvm::Value *mask) {
llvm::Value *mmval = LaneMask(mask);
return CmpInst(llvm::Instruction::ICmp, llvm::CmpInst::ICMP_NE, mmval,
LLVMInt32(0), "any_mm_cmp");
}
llvm::Value *
FunctionEmitContext::All(llvm::Value *mask) {
llvm::Value *mmval = LaneMask(mask);
return CmpInst(llvm::Instruction::ICmp, llvm::CmpInst::ICMP_EQ, mmval,
LLVMInt32((1<<g->target.vectorWidth)-1), "all_mm_cmp");
}
llvm::Value *
FunctionEmitContext::LaneMask(llvm::Value *v) {
// Call the target-dependent movmsk function to turn the vector mask
// into an i32 value
std::vector<Symbol *> *mm = m->symbolTable->LookupFunction("__movmsk");
// There should be one with signed int signature, one unsigned int.
assert(mm && mm->size() == 2);
llvm::Function *fmm = (*mm)[0]->function;
return CallInst(fmm, v, "val_movmsk");
}
llvm::Value *
FunctionEmitContext::MasksAllEqual(llvm::Value *v1, llvm::Value *v2) {
// Compare the two masks to get a vector of i1s
llvm::Value *cmp = CmpInst(llvm::Instruction::ICmp, llvm::CmpInst::ICMP_EQ,
v1, v2, "v1==v2");
// Turn that into a bool vector type (often i32s)
cmp = I1VecToBoolVec(cmp);
// And see if it's all on
return All(cmp);
}
llvm::Value *
FunctionEmitContext::GetStringPtr(const std::string &str) {
llvm::Constant *lstr = llvm::ConstantArray::get(*g->ctx, str);
llvm::GlobalValue::LinkageTypes linkage = llvm::GlobalValue::InternalLinkage;
llvm::Value *lstrPtr = new llvm::GlobalVariable(*m->module, lstr->getType(),
true /*isConst*/,
linkage, lstr, "__str");
return new llvm::BitCastInst(lstrPtr, LLVMTypes::VoidPointerType,
"str_void_ptr", bblock);
}
llvm::BasicBlock *
FunctionEmitContext::CreateBasicBlock(const char *name) {
llvm::Function *function = bblock->getParent();
return llvm::BasicBlock::Create(*g->ctx, name, function);
}
llvm::Value *
FunctionEmitContext::I1VecToBoolVec(llvm::Value *b) {
LLVM_TYPE_CONST llvm::ArrayType *at =
llvm::dyn_cast<LLVM_TYPE_CONST llvm::ArrayType>(b->getType());
if (at) {
// If we're given an array of vectors of i1s, then do the
// conversion for each of the elements
LLVM_TYPE_CONST llvm::Type *boolArrayType =
llvm::ArrayType::get(LLVMTypes::BoolVectorType, at->getNumElements());
llvm::Value *ret = llvm::UndefValue::get(boolArrayType);
for (unsigned int i = 0; i < at->getNumElements(); ++i) {
llvm::Value *elt = ExtractInst(b, i);
llvm::Value *sext = SExtInst(elt, LLVMTypes::BoolVectorType,
"val_to_boolvec32");
ret = InsertInst(ret, sext, i);
}
return ret;
}
else
return SExtInst(b, LLVMTypes::BoolVectorType, "val_to_boolvec32");
}
llvm::Value *
FunctionEmitContext::EmitMalloc(LLVM_TYPE_CONST llvm::Type *ty, int align) {
// Emit code to compute the size of the given type using a GEP with a
// NULL base pointer, indexing one element of the given type, and
// casting the resulting 'pointer' to an int giving its size.
LLVM_TYPE_CONST llvm::Type *ptrType = llvm::PointerType::get(ty, 0);
llvm::Value *nullPtr = llvm::Constant::getNullValue(ptrType);
llvm::Value *index[1] = { LLVMInt32(1) };
#if defined(LLVM_3_0) || defined(LLVM_3_0svn)
llvm::ArrayRef<llvm::Value *> arrayRef(&index[0], &index[1]);
llvm::Value *poffset = llvm::GetElementPtrInst::Create(nullPtr, arrayRef,
"offset_ptr", bblock);
#else
llvm::Value *poffset = llvm::GetElementPtrInst::Create(nullPtr, &index[0], &index[1],
"offset_ptr", bblock);
#endif
AddDebugPos(poffset);
llvm::Value *sizeOf = PtrToIntInst(poffset, LLVMTypes::Int64Type, "offset_int");
// And given the size, call the malloc function
llvm::Function *fmalloc = m->module->getFunction("ISPCMalloc");
assert(fmalloc != NULL);
llvm::Value *mem = CallInst(fmalloc, sizeOf, LLVMInt32(align),
"raw_argmem");
// Cast the void * back to the result pointer type
return BitCastInst(mem, ptrType, "mem_bitcast");
}
void
FunctionEmitContext::EmitFree(llvm::Value *ptr) {
llvm::Value *freeArg = BitCastInst(ptr, LLVMTypes::VoidPointerType,
"argmemfree");
llvm::Function *ffree = m->module->getFunction("ISPCFree");
assert(ffree != NULL);
CallInst(ffree, freeArg);
}
static llvm::Value *
lGetStringAsValue(llvm::BasicBlock *bblock, const char *s) {
llvm::Constant *sConstant = llvm::ConstantArray::get(*g->ctx, s);
llvm::Value *sPtr = new llvm::GlobalVariable(*m->module, sConstant->getType(),
true /* const */,
llvm::GlobalValue::InternalLinkage,
sConstant, s);
llvm::Value *indices[2] = { LLVMInt32(0), LLVMInt32(0) };
#if defined(LLVM_3_0) || defined(LLVM_3_0svn)
llvm::ArrayRef<llvm::Value *> arrayRef(&indices[0], &indices[2]);
return llvm::GetElementPtrInst::Create(sPtr, arrayRef, "sptr", bblock);
#else
return llvm::GetElementPtrInst::Create(sPtr, &indices[0], &indices[2],
"sptr", bblock);
#endif
}
void
FunctionEmitContext::AddInstrumentationPoint(const char *note) {
assert(note != NULL);
if (!g->emitInstrumentation)
return;
std::vector<llvm::Value *> args;
// arg 1: filename as string
args.push_back(lGetStringAsValue(bblock, currentPos.name));
// arg 2: provided note
args.push_back(lGetStringAsValue(bblock, note));
// arg 3: line number
args.push_back(LLVMInt32(currentPos.first_line));
// arg 4: current mask, movmsk'ed down to an int32
args.push_back(LaneMask(GetMask()));
llvm::Function *finst = m->module->getFunction("ISPCInstrument");
CallInst(finst, args, "");
}
void
FunctionEmitContext::SetDebugPos(SourcePos pos) {
currentPos = pos;
}
SourcePos
FunctionEmitContext::GetDebugPos() const {
return currentPos;
}
void
FunctionEmitContext::AddDebugPos(llvm::Value *value, const SourcePos *pos,
llvm::DIScope *scope) {
#ifndef LLVM_2_8
llvm::Instruction *inst = llvm::dyn_cast<llvm::Instruction>(value);
if (inst != NULL && m->diBuilder) {
SourcePos p = pos ? *pos : currentPos;
if (p.first_line != 0)
// If first_line == 0, then we're in the middle of setting up
// the standard library or the like; don't add debug positions
// for those functions
inst->setDebugLoc(llvm::DebugLoc::get(p.first_line, p.first_column,
scope ? *scope : GetDIScope()));
}
#endif
}
void
FunctionEmitContext::StartScope() {
#ifndef LLVM_2_8
if (m->diBuilder != NULL) {
llvm::DIScope parentScope;
if (debugScopes.size() > 0)
parentScope = debugScopes.back();
else
parentScope = diFunction;
llvm::DILexicalBlock lexicalBlock =
m->diBuilder->createLexicalBlock(parentScope, diFile,
currentPos.first_line,
currentPos.first_column);
debugScopes.push_back(lexicalBlock);
}
#endif
}
void
FunctionEmitContext::EndScope() {
#ifndef LLVM_2_8
if (m->diBuilder != NULL) {
assert(debugScopes.size() > 0);
debugScopes.pop_back();
}
#endif
}
llvm::DIScope
FunctionEmitContext::GetDIScope() const {
assert(debugScopes.size() > 0);
return debugScopes.back();
}
void
FunctionEmitContext::EmitVariableDebugInfo(Symbol *sym) {
#ifndef LLVM_2_8
if (m->diBuilder == NULL)
return;
llvm::DIScope scope = GetDIScope();
llvm::DIVariable var =
m->diBuilder->createLocalVariable(llvm::dwarf::DW_TAG_auto_variable,
scope,
sym->name,
sym->pos.GetDIFile(),
sym->pos.first_line,
sym->type->GetDIType(scope),
true /* preserve through opts */);
llvm::Instruction *declareInst =
m->diBuilder->insertDeclare(sym->storagePtr, var, bblock);
AddDebugPos(declareInst, &sym->pos, &scope);
#endif
}
void
FunctionEmitContext::EmitFunctionParameterDebugInfo(Symbol *sym) {
#ifndef LLVM_2_8
if (m->diBuilder == NULL)
return;
llvm::DIScope scope = diFunction;
llvm::DIVariable var =
m->diBuilder->createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
scope,
sym->name,
sym->pos.GetDIFile(),
sym->pos.first_line,
sym->type->GetDIType(scope),
true /* preserve through opts */);
llvm::Instruction *declareInst =
m->diBuilder->insertDeclare(sym->storagePtr, var, bblock);
AddDebugPos(declareInst, &sym->pos, &scope);
#endif
}
/** If the given type is an array of vector types, then it's the
representation of an ispc VectorType with varying elements. If it is
one of these, return the array size (i.e. the VectorType's size).
Otherwise return zero.
*/
static int
lArrayVectorWidth(LLVM_TYPE_CONST llvm::Type *t) {
LLVM_TYPE_CONST llvm::ArrayType *arrayType =
llvm::dyn_cast<LLVM_TYPE_CONST llvm::ArrayType>(t);
if (arrayType == NULL)
return 0;
// We shouldn't be seeing arrays of anything but vectors being passed
// to things like FunctionEmitContext::BinaryOperator() as operands
LLVM_TYPE_CONST llvm::VectorType *vectorElementType =
llvm::dyn_cast<LLVM_TYPE_CONST llvm::VectorType>(arrayType->getElementType());
assert(vectorElementType != NULL &&
(int)vectorElementType->getNumElements() == g->target.vectorWidth);
return (int)arrayType->getNumElements();
}
llvm::Value *
FunctionEmitContext::BinaryOperator(llvm::Instruction::BinaryOps inst,
llvm::Value *v0, llvm::Value *v1,
const char *name) {
if (v0 == NULL || v1 == NULL) {
assert(m->errorCount > 0);
return NULL;
}
assert(v0->getType() == v1->getType());
LLVM_TYPE_CONST llvm::Type *type = v0->getType();
int arraySize = lArrayVectorWidth(type);
if (arraySize == 0) {
llvm::Instruction *bop =
llvm::BinaryOperator::Create(inst, v0, v1, name ? name : "", bblock);
AddDebugPos(bop);
return bop;
}
else {
// If this is an ispc VectorType, apply the binary operator to each
// of the elements of the array (which in turn should be either
// scalar types or llvm::VectorTypes.)
llvm::Value *ret = llvm::UndefValue::get(type);
for (int i = 0; i < arraySize; ++i) {
llvm::Value *a = ExtractInst(v0, i);
llvm::Value *b = ExtractInst(v1, i);
llvm::Value *op = BinaryOperator(inst, a, b);
ret = InsertInst(ret, op, i);
}