-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopt.cpp
2537 lines (2210 loc) · 103 KB
/
opt.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 opt.cpp
@brief Implementations of various ispc optimization passes that operate
on the LLVM IR.
*/
#include "opt.h"
#include "ctx.h"
#include "sym.h"
#include "module.h"
#include "util.h"
#include "llvmutil.h"
#include <stdio.h>
#include <llvm/Pass.h>
#include <llvm/Module.h>
#include <llvm/PassManager.h>
#include <llvm/PassRegistry.h>
#include <llvm/Assembly/PrintModulePass.h>
#include <llvm/Function.h>
#include <llvm/BasicBlock.h>
#include <llvm/Instructions.h>
#include <llvm/Intrinsics.h>
#include <llvm/Constants.h>
#ifndef LLVM_2_8
#include <llvm/Target/TargetLibraryInfo.h>
#ifdef LLVM_2_9
#include <llvm/Support/StandardPasses.h>
#else
#include <llvm/Support/PassManagerBuilder.h>
#endif // LLVM_2_9
#endif // LLVM_2_8
#include <llvm/ADT/Triple.h>
#include <llvm/Transforms/Scalar.h>
#include <llvm/Transforms/IPO.h>
#include <llvm/Transforms/Utils/BasicBlockUtils.h>
#include <llvm/Target/TargetOptions.h>
#include <llvm/Target/TargetData.h>
#include <llvm/Analysis/Verifier.h>
#include <llvm/Support/raw_ostream.h>
#ifndef LLVM_2_8
#include <llvm/Analysis/DIBuilder.h>
#endif
#include <llvm/Analysis/DebugInfo.h>
#include <llvm/Support/Dwarf.h>
static llvm::Pass *CreateIntrinsicsOptPass();
static llvm::Pass *CreateGatherScatterFlattenPass();
static llvm::Pass *CreateGatherScatterImprovementsPass();
static llvm::Pass *CreateLowerGatherScatterPass();
static llvm::Pass *CreateLowerMaskedStorePass();
static llvm::Pass *CreateMaskedStoreOptPass();
static llvm::Pass *CreateIsCompileTimeConstantPass(bool isLastTry);
static llvm::Pass *CreateMakeInternalFuncsStaticPass();
///////////////////////////////////////////////////////////////////////////
/** This utility routine copies the metadata (if any) attached to the
'from' instruction in the IR to the 'to' instruction.
For flexibility, this function takes an llvm::Value rather than an
llvm::Instruction for the 'to' parameter; at some places in the code
below, we sometimes use a llvm::Value to start out storing a value and
then later store instructions. If a llvm::Value is passed to this, the
routine just returns without doing anything; if it is in fact an
LLVM::Instruction, then the metadata can be copied to it.
*/
static void
lCopyMetadata(llvm::Value *vto, const llvm::Instruction *from) {
llvm::Instruction *to = llvm::dyn_cast<llvm::Instruction>(vto);
if (!to)
return;
llvm::SmallVector<std::pair<unsigned int, llvm::MDNode *>, 8> metadata;
from->getAllMetadata(metadata);
for (unsigned int i = 0; i < metadata.size(); ++i)
to->setMetadata(metadata[i].first, metadata[i].second);
}
/** We have a protocol with the front-end LLVM IR code generation process
that allows us to encode the source file position that corresponds with
instructions. (For example, this allows us to issue performance
warnings related to things like scatter and gather after optimization
has been performed, so that we aren't warning about scatters and
gathers that have been improved to stores and loads by optimization
passes.) Note that this is slightly redundant with the source file
position encoding generated for debugging symbols, though we don't
always generate debugging information but we do always generate this
position data.
This function finds the SourcePos that the metadata in the instruction
(if present) corresponds to. See the implementation of
FunctionEmitContext::addGSMetadata(), which encodes the source position during
code generation.
@param inst Instruction to try to find the source position of
@param pos Output variable in which to store the position
@returns True if source file position metadata was present and *pos
has been set. False otherwise.
*/
static bool
lGetSourcePosFromMetadata(const llvm::Instruction *inst, SourcePos *pos) {
llvm::MDNode *filename = inst->getMetadata("filename");
llvm::MDNode *line = inst->getMetadata("line");
llvm::MDNode *column = inst->getMetadata("column");
if (!filename || !line || !column)
return false;
// All of these asserts are things that FunctionEmitContext::addGSMetadata() is
// expected to have done in its operation
assert(filename->getNumOperands() == 1 && line->getNumOperands() == 1);
llvm::MDString *str = llvm::dyn_cast<llvm::MDString>(filename->getOperand(0));
assert(str);
llvm::ConstantInt *lnum = llvm::dyn_cast<llvm::ConstantInt>(line->getOperand(0));
assert(lnum);
llvm::ConstantInt *colnum = llvm::dyn_cast<llvm::ConstantInt>(column->getOperand(0));
assert(column);
*pos = SourcePos(str->getString().data(), (int)lnum->getZExtValue(),
(int)colnum->getZExtValue());
return true;
}
/** Utility routine that prints out the LLVM IR for everything in the
module. (Used for debugging).
*/
static void
lPrintModuleCode(llvm::Module *module) {
llvm::PassManager ppm;
ppm.add(llvm::createPrintModulePass(&llvm::outs()));
ppm.run(*module);
}
void
Optimize(llvm::Module *module, int optLevel) {
if (g->debugPrint) {
printf("*** Code going into optimization ***\n");
lPrintModuleCode(module);
}
llvm::PassManager optPM;
llvm::FunctionPassManager funcPM(module);
#ifndef LLVM_2_8
llvm::TargetLibraryInfo *targetLibraryInfo =
new llvm::TargetLibraryInfo(llvm::Triple(module->getTargetTriple()));
optPM.add(targetLibraryInfo);
#endif
optPM.add(new llvm::TargetData(module));
if (optLevel == 0) {
// This is more or less the minimum set of optimizations that we
// need to do to generate code that will actually run. (We can't
// run absolutely no optimizations, since the front-end needs us to
// take the various __pseudo_* functions it has emitted and turn
// them into something that can actually execute.
optPM.add(CreateGatherScatterFlattenPass());
optPM.add(CreateLowerGatherScatterPass());
optPM.add(CreateLowerMaskedStorePass());
optPM.add(CreateIsCompileTimeConstantPass(true));
optPM.add(llvm::createFunctionInliningPass());
optPM.add(CreateMakeInternalFuncsStaticPass());
optPM.add(llvm::createGlobalDCEPass());
}
else {
// Otherwise throw the kitchen sink of optimizations at the code.
// This is almost certainly overkill and likely could be reduced,
// but on the other hand trying to remove some of these has
// historically caused performance slowdowns. Benchmark carefully
// if changing these around.
//
// Note in particular that a number of the ispc optimization
// passes are run repeatedly along the way; they often can kick in
// only later in the optimization process as things like constant
// propagation have done their thing, and then when they do kick
// in, they can often open up new opportunities for optimization...
#ifndef LLVM_2_8
llvm::PassRegistry *registry = llvm::PassRegistry::getPassRegistry();
llvm::initializeCore(*registry);
llvm::initializeScalarOpts(*registry);
llvm::initializeIPO(*registry);
llvm::initializeAnalysis(*registry);
llvm::initializeIPA(*registry);
llvm::initializeTransformUtils(*registry);
llvm::initializeInstCombine(*registry);
llvm::initializeInstrumentation(*registry);
llvm::initializeTarget(*registry);
#endif
// Early optimizations to try to reduce the total amount of code to
// work with if we can
optPM.add(CreateGatherScatterFlattenPass());
optPM.add(llvm::createReassociatePass());
optPM.add(llvm::createConstantPropagationPass());
if (!g->opt.disableMaskedStoreOptimizations) {
optPM.add(CreateIntrinsicsOptPass());
optPM.add(CreateMaskedStoreOptPass());
}
optPM.add(llvm::createDeadInstEliminationPass());
optPM.add(llvm::createConstantPropagationPass());
optPM.add(llvm::createDeadInstEliminationPass());
// On to more serious optimizations
optPM.add(llvm::createCFGSimplificationPass());
optPM.add(llvm::createScalarReplAggregatesPass());
optPM.add(llvm::createInstructionCombiningPass());
optPM.add(llvm::createCFGSimplificationPass());
optPM.add(llvm::createPromoteMemoryToRegisterPass());
optPM.add(llvm::createGlobalOptimizerPass());
optPM.add(llvm::createReassociatePass());
optPM.add(llvm::createIPConstantPropagationPass());
optPM.add(llvm::createDeadArgEliminationPass());
optPM.add(llvm::createInstructionCombiningPass());
optPM.add(llvm::createCFGSimplificationPass());
optPM.add(llvm::createPruneEHPass());
optPM.add(llvm::createFunctionAttrsPass());
optPM.add(llvm::createFunctionInliningPass());
optPM.add(llvm::createConstantPropagationPass());
optPM.add(llvm::createDeadInstEliminationPass());
optPM.add(llvm::createCFGSimplificationPass());
optPM.add(llvm::createArgumentPromotionPass());
optPM.add(llvm::createSimplifyLibCallsPass());
optPM.add(llvm::createInstructionCombiningPass());
optPM.add(llvm::createJumpThreadingPass());
optPM.add(llvm::createCFGSimplificationPass());
optPM.add(llvm::createScalarReplAggregatesPass());
optPM.add(llvm::createInstructionCombiningPass());
optPM.add(llvm::createTailCallEliminationPass());
if (!g->opt.disableMaskedStoreOptimizations) {
optPM.add(CreateIntrinsicsOptPass());
optPM.add(CreateMaskedStoreOptPass());
}
optPM.add(CreateLowerMaskedStorePass());
if (!g->opt.disableGatherScatterOptimizations)
optPM.add(CreateGatherScatterImprovementsPass());
optPM.add(CreateLowerMaskedStorePass());
optPM.add(CreateLowerGatherScatterPass());
optPM.add(llvm::createFunctionInliningPass());
optPM.add(llvm::createConstantPropagationPass());
optPM.add(CreateIntrinsicsOptPass());
#if defined(LLVM_2_8)
optPM.add(CreateIsCompileTimeConstantPass(true));
#elif defined(LLVM_2_9)
llvm::createStandardModulePasses(&optPM, 3,
false /* opt size */,
true /* unit at a time */,
false /* unroll loops */,
true /* simplify lib calls */,
false /* may have exceptions */,
llvm::createFunctionInliningPass());
llvm::createStandardLTOPasses(&optPM, true /* internalize pass */,
true /* inline once again */,
false /* verify after each pass */);
llvm::createStandardFunctionPasses(&optPM, 3);
optPM.add(CreateIsCompileTimeConstantPass(true));
optPM.add(CreateIntrinsicsOptPass());
llvm::createStandardModulePasses(&optPM, 3,
false /* opt size */,
true /* unit at a time */,
false /* unroll loops */,
true /* simplify lib calls */,
false /* may have exceptions */,
llvm::createFunctionInliningPass());
#else
llvm::PassManagerBuilder builder;
builder.OptLevel = 3;
builder.Inliner = llvm::createFunctionInliningPass();
builder.populateFunctionPassManager(funcPM);
builder.populateModulePassManager(optPM);
optPM.add(CreateIsCompileTimeConstantPass(true));
optPM.add(CreateIntrinsicsOptPass());
builder.populateLTOPassManager(optPM, true /* internalize */,
true /* inline once again */);
optPM.add(CreateIsCompileTimeConstantPass(true));
optPM.add(CreateIntrinsicsOptPass());
builder.populateModulePassManager(optPM);
#endif
optPM.add(CreateMakeInternalFuncsStaticPass());
optPM.add(llvm::createGlobalDCEPass());
}
// Finish up by making sure we didn't mess anything up in the IR along
// the way.
optPM.add(llvm::createVerifierPass());
for (llvm::Module::iterator fiter = module->begin(); fiter != module->end();
++fiter)
funcPM.run(*fiter);
optPM.run(*module);
if (g->debugPrint) {
printf("\n*****\nFINAL OUTPUT\n*****\n");
lPrintModuleCode(module);
}
}
///////////////////////////////////////////////////////////////////////////
// IntrinsicsOpt
/** This is a relatively simple optimization pass that does a few small
optimizations that LLVM's x86 optimizer doesn't currently handle.
(Specifically, MOVMSK of a constant can be replaced with the
corresponding constant value, BLENDVPS and AVX masked load/store with
either an 'all on' or 'all off' masks can be replaced with simpler
operations.
@todo The better thing to do would be to submit a patch to LLVM to get
these; they're presumably pretty simple patterns to match.
*/
class IntrinsicsOpt : public llvm::BasicBlockPass {
public:
IntrinsicsOpt();
const char *getPassName() const { return "Intrinsics Cleanup Optimization"; }
bool runOnBasicBlock(llvm::BasicBlock &BB);
static char ID;
private:
struct MaskInstruction {
MaskInstruction(llvm::Function *f) { function = f; }
llvm::Function *function;
};
std::vector<MaskInstruction> maskInstructions;
/** Structure that records everything we need to know about a blend
instruction for this optimization pass.
*/
struct BlendInstruction {
BlendInstruction(llvm::Function *f, int ao, int o0, int o1, int of)
: function(f), allOnMask(ao), op0(o0), op1(o1), opFactor(of) { }
/** Function pointer for the blend instruction */
llvm::Function *function;
/** Mask value for an "all on" mask for this instruction */
int allOnMask;
/** The operand number in the llvm CallInst corresponds to the
first operand to blend with. */
int op0;
/** The operand number in the CallInst corresponding to the second
operand to blend with. */
int op1;
/** The operand in the call inst where the blending factor is
found. */
int opFactor;
};
std::vector<BlendInstruction> blendInstructions;
bool matchesMaskInstruction(llvm::Function *function);
BlendInstruction *matchingBlendInstruction(llvm::Function *function);
};
char IntrinsicsOpt::ID = 0;
llvm::RegisterPass<IntrinsicsOpt> sse("sse-constants", "Intrinsics Cleanup Pass");
IntrinsicsOpt::IntrinsicsOpt()
: BasicBlockPass(ID) {
// All of the mask instructions we may encounter. Note that even if
// compiling for AVX, we may still encounter the regular 4-wide SSE
// MOVMSK instruction.
llvm::Function *sseMovmsk =
llvm::Intrinsic::getDeclaration(m->module, llvm::Intrinsic::x86_sse_movmsk_ps);
maskInstructions.push_back(sseMovmsk);
maskInstructions.push_back(m->module->getFunction("__movmsk"));
#if defined(LLVM_3_0) || defined(LLVM_3_0svn)
llvm::Function *avxMovmsk =
llvm::Intrinsic::getDeclaration(m->module, llvm::Intrinsic::x86_avx_movmsk_ps_256);
assert(avxMovmsk != NULL);
maskInstructions.push_back(avxMovmsk);
#endif
// And all of the blend instructions
blendInstructions.push_back(BlendInstruction(
llvm::Intrinsic::getDeclaration(m->module, llvm::Intrinsic::x86_sse41_blendvps),
0xf, 0, 1, 2));
blendInstructions.push_back(BlendInstruction(
m->module->getFunction("llvm.x86.avx.blendvps"), 0xff, 0, 1, 2));
}
/** Given an llvm::Value represinting a vector mask, see if the value is a
constant. If so, return the integer mask found by taking the high bits
of the mask values in turn and concatenating them into a single integer.
In other words, given the 4-wide mask: < 0xffffffff, 0, 0, 0xffffffff >,
we have 0b1001 = 9.
@todo This will break if we ever do 32-wide compilation, in which case
it don't be possible to distinguish between -1 for "don't know" and
"known and all bits on".
*/
static int
lGetMask(llvm::Value *factor) {
llvm::ConstantVector *cv = llvm::dyn_cast<llvm::ConstantVector>(factor);
if (cv) {
int mask = 0;
llvm::SmallVector<llvm::Constant *, ISPC_MAX_NVEC> elements;
cv->getVectorElements(elements);
for (unsigned int i = 0; i < elements.size(); ++i) {
llvm::APInt intMaskValue;
// SSE has the "interesting" approach of encoding blending
// masks as <n x float>.
llvm::ConstantFP *cf = llvm::dyn_cast<llvm::ConstantFP>(elements[i]);
if (cf) {
llvm::APFloat apf = cf->getValueAPF();
intMaskValue = apf.bitcastToAPInt();
}
else {
// Otherwise get it as an int
llvm::ConstantInt *ci = llvm::dyn_cast<llvm::ConstantInt>(elements[i]);
assert(ci != NULL); // vs return -1 if NULL?
intMaskValue = ci->getValue();
}
// Is the high-bit set? If so, OR in the appropriate bit in
// the result mask
if (intMaskValue.countLeadingOnes() > 0)
mask |= (1 << i);
}
return mask;
}
else if (llvm::isa<llvm::ConstantAggregateZero>(factor))
return 0;
else {
// else we should be able to handle it above...
assert(!llvm::isa<llvm::Constant>(factor));
return -1;
}
}
/** Given an llvm::Value, return true if we can determine that it's an
undefined value. This only makes a weak attempt at chasing this down,
only detecting flat-out undef values, and bitcasts of undef values.
@todo Is it worth working harder to find more of these? It starts to
get tricky, since having an undef operand doesn't necessarily mean that
the result will be undefined. (And for that matter, is there an LLVM
call that will do this for us?)
*/
static bool
lIsUndef(llvm::Value *value) {
if (llvm::isa<llvm::UndefValue>(value))
return true;
llvm::BitCastInst *bci = llvm::dyn_cast<llvm::BitCastInst>(value);
if (bci)
return lIsUndef(bci->getOperand(0));
return false;
}
bool
IntrinsicsOpt::runOnBasicBlock(llvm::BasicBlock &bb) {
#if defined(LLVM_3_0) || defined(LLVM_3_0svn)
llvm::Function *avxMaskedLoad32 =
llvm::Intrinsic::getDeclaration(m->module, llvm::Intrinsic::x86_avx_maskload_ps_256);
llvm::Function *avxMaskedLoad64 =
llvm::Intrinsic::getDeclaration(m->module, llvm::Intrinsic::x86_avx_maskload_pd_256);
llvm::Function *avxMaskedStore32 =
llvm::Intrinsic::getDeclaration(m->module, llvm::Intrinsic::x86_avx_maskstore_ps_256);
llvm::Function *avxMaskedStore64 =
llvm::Intrinsic::getDeclaration(m->module, llvm::Intrinsic::x86_avx_maskstore_pd_256);
assert(avxMaskedLoad32 != NULL && avxMaskedStore32 != NULL);
assert(avxMaskedLoad64 != NULL && avxMaskedStore64 != NULL);
#endif
bool modifiedAny = false;
restart:
for (llvm::BasicBlock::iterator iter = bb.begin(), e = bb.end(); iter != e; ++iter) {
llvm::CallInst *callInst = llvm::dyn_cast<llvm::CallInst>(&*iter);
if (!callInst)
continue;
BlendInstruction *blend = matchingBlendInstruction(callInst->getCalledFunction());
if (blend != NULL) {
llvm::Value *v[2] = { callInst->getArgOperand(blend->op0),
callInst->getArgOperand(blend->op1) };
llvm::Value *factor = callInst->getArgOperand(blend->opFactor);
// If the values are the same, then no need to blend..
if (v[0] == v[1]) {
llvm::ReplaceInstWithValue(iter->getParent()->getInstList(),
iter, v[0]);
modifiedAny = true;
goto restart;
}
// If one of the two is undefined, we're allowed to replace
// with the value of the other. (In other words, the only
// valid case is that the blend factor ends up having a value
// that only selects from the defined one of the two operands,
// otherwise the result is undefined and any value is fine,
// ergo the defined one is an acceptable result.)
if (lIsUndef(v[0])) {
llvm::ReplaceInstWithValue(iter->getParent()->getInstList(),
iter, v[1]);
modifiedAny = true;
goto restart;
}
if (lIsUndef(v[1])) {
llvm::ReplaceInstWithValue(iter->getParent()->getInstList(),
iter, v[0]);
modifiedAny = true;
goto restart;
}
int mask = lGetMask(factor);
llvm::Value *value = NULL;
if (mask == 0)
// Mask all off -> replace with the first blend value
value = v[0];
else if (mask == blend->allOnMask)
// Mask all on -> replace with the second blend value
value = v[1];
if (value != NULL) {
llvm::ReplaceInstWithValue(iter->getParent()->getInstList(),
iter, value);
modifiedAny = true;
goto restart;
}
}
else if (matchesMaskInstruction(callInst->getCalledFunction())) {
llvm::Value *factor = callInst->getArgOperand(0);
int mask = lGetMask(factor);
if (mask != -1) {
// If the vector-valued mask has a known value, replace it
// with the corresponding integer mask from its elements
// high bits.
llvm::Value *value = LLVMInt32(mask);
llvm::ReplaceInstWithValue(iter->getParent()->getInstList(),
iter, value);
modifiedAny = true;
goto restart;
}
}
#if defined(LLVM_3_0) || defined(LLVM_3_0svn)
else if (callInst->getCalledFunction() == avxMaskedLoad32 ||
callInst->getCalledFunction() == avxMaskedLoad64) {
llvm::Value *factor = callInst->getArgOperand(1);
int mask = lGetMask(factor);
if (mask == 0) {
// nothing being loaded, replace with undef value
llvm::Type *returnType = callInst->getType();
assert(llvm::isa<llvm::VectorType>(returnType));
llvm::Value *undefValue = llvm::UndefValue::get(returnType);
llvm::ReplaceInstWithValue(iter->getParent()->getInstList(),
iter, undefValue);
modifiedAny = true;
goto restart;
}
else if (mask == 0xff) {
// all lanes active; replace with a regular load
llvm::Type *returnType = callInst->getType();
assert(llvm::isa<llvm::VectorType>(returnType));
// cast the i8 * to the appropriate type
llvm::Value *castPtr =
new llvm::BitCastInst(callInst->getArgOperand(0),
llvm::PointerType::get(returnType, 0),
"ptr2vec", callInst);
lCopyMetadata(castPtr, callInst);
llvm::Instruction *loadInst =
new llvm::LoadInst(castPtr, "load", false /* not volatile */,
0 /* align */, (llvm::Instruction *)NULL);
lCopyMetadata(loadInst, callInst);
llvm::ReplaceInstWithInst(callInst, loadInst);
modifiedAny = true;
goto restart;
}
}
else if (callInst->getCalledFunction() == avxMaskedStore32 ||
callInst->getCalledFunction() == avxMaskedStore64) {
// NOTE: mask is the 2nd parameter, not the 3rd one!!
llvm::Value *factor = callInst->getArgOperand(1);
int mask = lGetMask(factor);
if (mask == 0) {
// nothing actually being stored, just remove the inst
callInst->eraseFromParent();
modifiedAny = true;
goto restart;
}
else if (mask == 0xff) {
// all lanes storing, so replace with a regular store
llvm::Value *rvalue = callInst->getArgOperand(1);
llvm::Type *storeType = rvalue->getType();
llvm::Value *castPtr =
new llvm::BitCastInst(callInst->getArgOperand(0),
llvm::PointerType::get(storeType, 0),
"ptr2vec", callInst);
lCopyMetadata(castPtr, callInst);
llvm::Instruction *storeInst =
new llvm::StoreInst(rvalue, castPtr, (llvm::Instruction *)NULL);
lCopyMetadata(storeInst, callInst);
llvm::ReplaceInstWithInst(callInst, storeInst);
modifiedAny = true;
goto restart;
}
}
#endif
}
return modifiedAny;
}
bool
IntrinsicsOpt::matchesMaskInstruction(llvm::Function *function) {
for (unsigned int i = 0; i < maskInstructions.size(); ++i)
if (function == maskInstructions[i].function)
return true;
return false;
}
IntrinsicsOpt::BlendInstruction *
IntrinsicsOpt::matchingBlendInstruction(llvm::Function *function) {
for (unsigned int i = 0; i < blendInstructions.size(); ++i)
if (function == blendInstructions[i].function)
return &blendInstructions[i];
return NULL;
}
static llvm::Pass *
CreateIntrinsicsOptPass() {
return new IntrinsicsOpt;
}
///////////////////////////////////////////////////////////////////////////
// GatherScatterFlattenOpt
/** When the front-end emits gathers and scatters, it generates an array of
vector-width pointers to represent the set of addresses to read from or
write to. However, because ispc doesn't support pointers, it turns
out to be the case that scatters and gathers always end up indexing
into an array with a common base pointer. Therefore, this optimization
transforms the original arrays of general pointers into a single base
pointer and an array of offsets.
(Implementation seems to be easier with this approach versus having the
front-end try to emit base pointer + offset stuff from the start,
though arguably the latter approach would be a little more elegant.)
See for example the comments discussing the __pseudo_gather functions
in builtins.cpp for more information about this.
@todo The implementation of this is pretty messy, and it sure would be
nice to not have all the complexity of built-in assumptions of the
structure of how the front end will have generated code, all of the
instruction dyn_casts, etc. Can we do something simpler, e.g. an early
pass to flatten out GEPs when the size is known, then do LLVM's
constant folding, then flatten into an array, etc.?
*/
class GatherScatterFlattenOpt : public llvm::BasicBlockPass {
public:
static char ID;
GatherScatterFlattenOpt() : BasicBlockPass(ID) { }
const char *getPassName() const { return "Gather/Scatter Flattening"; }
bool runOnBasicBlock(llvm::BasicBlock &BB);
};
char GatherScatterFlattenOpt::ID = 0;
llvm::RegisterPass<GatherScatterFlattenOpt> gsf("gs-flatten", "Gather/Scatter Flatten Pass");
/** Given an llvm::Value known to be an unsigned integer, return its value as
an int64_t.
*/
static uint64_t
lGetIntValue(llvm::Value *offset) {
llvm::ConstantInt *intOffset = llvm::dyn_cast<llvm::ConstantInt>(offset);
assert(intOffset && (intOffset->getBitWidth() == 32 ||
intOffset->getBitWidth() == 64));
return intOffset->getZExtValue();
}
/** Returns the size of the given llvm::Type as an llvm::Value, if the size
can be easily determined at compile type. If it's not easy to figure
out the size, this just returns NULL and we handle finding its size
differently.
*/
static bool
lSizeOfIfKnown(const llvm::Type *type, uint64_t *size) {
if (type == LLVMTypes::Int8Type) {
*size = 1;
return true;
}
if (type == LLVMTypes::Int8VectorType) {
*size = g->target.vectorWidth * 1;
return true;
}
else if (type == LLVMTypes::Int16Type) {
*size = 2;
return true;
}
if (type == LLVMTypes::Int16VectorType) {
*size = g->target.vectorWidth * 2;
return true;
}
else if (type == LLVMTypes::FloatType || type == LLVMTypes::Int32Type) {
*size = 4;
return true;
}
else if (type == LLVMTypes::FloatVectorType || type == LLVMTypes::Int32VectorType) {
*size = g->target.vectorWidth * 4;
return true;
}
else if (type == LLVMTypes::DoubleType || type == LLVMTypes::Int64Type) {
*size = 8;
return true;
}
else if (type == LLVMTypes::DoubleVectorType || type == LLVMTypes::Int64VectorType) {
*size = g->target.vectorWidth * 8;
return true;
}
else if (llvm::isa<const llvm::ArrayType>(type)) {
const llvm::ArrayType *at = llvm::dyn_cast<const llvm::ArrayType>(type);
uint64_t eltSize;
if (lSizeOfIfKnown(at->getElementType(), &eltSize)) {
*size = eltSize * at->getNumElements();
return true;
}
else
return false;
}
return false;
}
/** This function returns an llvm::Value giving the size of the given type.
If any instructions need to be generated to compute the size, they are
inserted before insertBefore.
*/
static llvm::Value *
lSizeOf(LLVM_TYPE_CONST llvm::Type *type, llvm::Instruction *insertBefore) {
// First try the easy case and see if we can get it as a simple
// constant..
uint64_t size;
if (lSizeOfIfKnown(type, &size))
return LLVMInt64(size);
// Otherwise use the trick of doing a GEP with a NULL pointer to get
// the pointer to the second element of an array of items of this type.
// Then convert that pointer to an int and we've got the offset to the
// second element in the array, a.k.a. the size of the type.
LLVM_TYPE_CONST llvm::Type *ptrType = llvm::PointerType::get(type, 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", insertBefore);
#else
llvm::Value *poffset = llvm::GetElementPtrInst::Create(nullPtr, &index[0], &index[1],
"offset_ptr", insertBefore);
#endif
lCopyMetadata(poffset, insertBefore);
llvm::Instruction *inst = new llvm::PtrToIntInst(poffset, LLVMTypes::Int64Type,
"offset_int", insertBefore);
lCopyMetadata(inst, insertBefore);
return inst;
}
/** This function returns a value that gives the offset in bytes from the
start of the given structure type to the given struct member. The
instructions that compute this value are inserted before insertBefore.
*/
static llvm::Value *
lStructOffset(LLVM_TYPE_CONST llvm::Type *type, uint64_t member,
llvm::Instruction *insertBefore) {
// Do a similar trick to the one done in lSizeOf above; compute the
// pointer to the member starting from a NULL base pointer and then
// cast that 'pointer' to an int...
assert(llvm::isa<const llvm::StructType>(type));
LLVM_TYPE_CONST llvm::Type *ptrType = llvm::PointerType::get(type, 0);
llvm::Value *nullPtr = llvm::Constant::getNullValue(ptrType);
llvm::Value *index[2] = { LLVMInt32(0), LLVMInt32((int32_t)member) };
#if defined(LLVM_3_0) || defined(LLVM_3_0svn)
llvm::ArrayRef<llvm::Value *> arrayRef(&index[0], &index[2]);
llvm::Value *poffset = llvm::GetElementPtrInst::Create(nullPtr, arrayRef,
"member_ptr", insertBefore);
#else
llvm::Value *poffset = llvm::GetElementPtrInst::Create(nullPtr, &index[0], &index[2],
"member_ptr", insertBefore);
#endif
lCopyMetadata(poffset, insertBefore);
llvm::Instruction *inst = new llvm::PtrToIntInst(poffset, LLVMTypes::Int64Type,
"member_int", insertBefore);
lCopyMetadata(inst, insertBefore);
return inst;
}
static llvm::Value *
lGetTypeSize(LLVM_TYPE_CONST llvm::Type *type, llvm::Instruction *insertBefore) {
LLVM_TYPE_CONST llvm::ArrayType *arrayType =
llvm::dyn_cast<LLVM_TYPE_CONST llvm::ArrayType>(type);
if (arrayType != NULL)
type = arrayType->getElementType();
llvm::Value *scale = lSizeOf(type, insertBefore);
llvm::Instruction *inst = new llvm::TruncInst(scale, LLVMTypes::Int32Type, "sizeof32",
insertBefore);
lCopyMetadata(inst, insertBefore);
return inst;
}
static llvm::Value *
lGetOffsetForLane(int lane, llvm::Value *value, llvm::Value **offset,
LLVM_TYPE_CONST llvm::Type **scaleType, bool *leafIsVarying,
llvm::Instruction *insertBefore) {
if (!llvm::isa<llvm::GetElementPtrInst>(value)) {
assert(llvm::isa<llvm::BitCastInst>(value));
value = llvm::dyn_cast<llvm::BitCastInst>(value)->getOperand(0);
llvm::ExtractValueInst *ev = llvm::dyn_cast<llvm::ExtractValueInst>(value);
assert(ev->hasIndices() && ev->getNumIndices() == 1);
assert(int(*(ev->idx_begin())) == lane);
llvm::InsertValueInst *iv = llvm::dyn_cast<llvm::InsertValueInst>(ev->getOperand(0));
assert(iv->hasIndices() && iv->getNumIndices() == 1);
while (int(*(iv->idx_begin())) != lane) {
iv = llvm::dyn_cast<llvm::InsertValueInst>(iv->getOperand(0));
assert(iv && iv->hasIndices() && iv->getNumIndices() == 1);
}
value = iv->getOperand(1);
}
if (leafIsVarying != NULL) {
LLVM_TYPE_CONST llvm::Type *pt = value->getType();
LLVM_TYPE_CONST llvm::PointerType *ptrType =
llvm::dyn_cast<LLVM_TYPE_CONST llvm::PointerType>(pt);
assert(ptrType);
LLVM_TYPE_CONST llvm::Type *eltType = ptrType->getElementType();
*leafIsVarying = llvm::isa<LLVM_TYPE_CONST llvm::VectorType>(eltType);
}
llvm::GetElementPtrInst *gep = llvm::dyn_cast<llvm::GetElementPtrInst>(value);
assert(gep);
assert(lGetIntValue(gep->getOperand(1)) == 0);
LLVM_TYPE_CONST llvm::PointerType *targetPtrType =
llvm::dyn_cast<LLVM_TYPE_CONST llvm::PointerType>(gep->getOperand(0)->getType());
assert(targetPtrType);
LLVM_TYPE_CONST llvm::Type *targetType = targetPtrType->getElementType();
if (llvm::isa<const llvm::StructType>(targetType)) {
*offset = lStructOffset(targetType, lGetIntValue(gep->getOperand(2)),
insertBefore);
*offset = new llvm::TruncInst(*offset, LLVMTypes::Int32Type, "member32",
insertBefore);
lCopyMetadata(*offset, insertBefore);
*scaleType = LLVMTypes::Int8Type; // aka char aka sizeof(1)
}
else {
*offset = gep->getOperand(2);
assert(*scaleType == NULL || *scaleType == targetType);
*scaleType = targetType;
}
llvm::ExtractValueInst *ee =
llvm::dyn_cast<llvm::ExtractValueInst>(gep->getOperand(0));
if (ee == NULL) {
// found the base pointer, here it is...
return gep->getOperand(0);
}
else {
assert(ee->hasIndices() && ee->getNumIndices() == 1 &&
int(*(ee->idx_begin())) == lane);
llvm::InsertValueInst *iv =
llvm::dyn_cast<llvm::InsertValueInst>(ee->getOperand(0));
assert(iv != NULL);
// do this chain of inserts for the next dimension...
return iv;
}
}
/** We have an LLVM array of pointer values, where each pointer has been
computed with a GEP from some common base pointer value. This function
deconstructs the LLVM array, storing the offset from the base pointer
as an llvm::Value for the i'th element into the i'th element of the
offsets[] array passed in to the function. It returns a scale factor
for the offsets via *scaleType, and sets *leafIsVarying to true if the
leaf data type being indexed into is a 'varying' ispc type. The
return value is either the base pointer or the an array of pointers for
the next dimension of indexing (that we'll in turn deconstruct with
this function).
@todo All of the additional indexing magic for varying stuff should
happen in the front end.
*/
static llvm::Value *
lTraverseInsertChain(llvm::Value *ptrs, llvm::Value *offsets[ISPC_MAX_NVEC],
LLVM_TYPE_CONST llvm::Type **scaleType, bool *leafIsVarying,
llvm::Instruction *insertBefore) {
// This depends on the front-end constructing the arrays of pointers
// via InsertValue instructions. (Which it does do in
// FunctionEmitContext::GetElementPtrInst()).
llvm::InsertValueInst *ivInst = llvm::dyn_cast<llvm::InsertValueInst>(ptrs);
assert(ivInst != NULL);
// We have a chain of insert value instructions where each instruction
// sets one of the elements of the array and where the input array is
// either the base pointer or another insert value instruction. Here
// we talk through all of the insert value instructions until we hit
// the end.
llvm::Value *nextChain = NULL;
while (ivInst != NULL) {
// Figure out which array index this current instruction is setting
// the value of.
assert(ivInst->hasIndices() && ivInst->getNumIndices() == 1);
int elementIndex = *(ivInst->idx_begin());
assert(elementIndex >= 0 && elementIndex < g->target.vectorWidth);
// We shouldn't have already seen something setting the value for
// this index.
assert(offsets[elementIndex] == NULL);
// Set offsets[elementIndex] here. This returns the value from
// which the GEP operation was done; this should either be the base
// pointer or an insert value chain for another dimension of the
// array being indexed into.
llvm::Value *myNext = lGetOffsetForLane(elementIndex, ivInst->getOperand(1),
&offsets[elementIndex], scaleType,
leafIsVarying, insertBefore);
if (nextChain == NULL)
nextChain = myNext;
else
// All of these insert value instructions should have the same
// base value
assert(nextChain == myNext);
// Do we have another element of the array to process?
llvm::Value *nextInsert = ivInst->getOperand(0);
ivInst = llvm::dyn_cast<llvm::InsertValueInst>(nextInsert);
if (!ivInst)
assert(llvm::isa<llvm::UndefValue>(nextInsert));
}
return nextChain;
}
/** Given a scalar value, return a vector of width g->target.vectorWidth
that has the scalar replicated across each of its elements.