File: CoalescingEngine.hpp

package info (click to toggle)
intel-graphics-compiler 1.0.12504.6-1%2Bdeb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 83,912 kB
  • sloc: cpp: 910,147; lisp: 202,655; ansic: 15,197; python: 4,025; yacc: 2,241; lex: 1,570; pascal: 244; sh: 104; makefile: 25
file content (1023 lines) | stat: -rw-r--r-- 34,259 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
/*========================== begin_copyright_notice ============================

Copyright (C) 2017-2021 Intel Corporation

SPDX-License-Identifier: MIT

============================= end_copyright_notice ===========================*/

#pragma once

#include "Compiler/CISACodeGen/WIAnalysis.hpp"
#include "Compiler/CISACodeGen/PatternMatchPass.hpp"
#include "Compiler/MetaDataUtilsWrapper.h"
#include "Compiler/CISACodeGen/PayloadMapping.hpp"
#include "common/LLVMWarningsPush.hpp"
#include <llvm/Pass.h>
#include <llvm/ADT/DenseSet.h>
#include <llvm/IR/InstVisitor.h>
#include <llvm/IR/Dominators.h>
#include <llvm/Support/Debug.h>
#include <llvm/Support/Allocator.h>
#include "common/LLVMWarningsPop.hpp"
#include "GenISAIntrinsics/GenIntrinsicInst.h"
#include "Probe/Assertion.h"

namespace IGC {

    class CEncoder;
    class CVariable;
    class CodeGenContextWrapper;
    class DeSSA;


    class CoalescingEngine : public llvm::FunctionPass, public llvm::InstVisitor<CoalescingEngine>
    {
        //TODO: this is fixed for now, but once we have pressure heuristic, could be relaxed
        static const int MaxTupleSize = 12;

    public:
        static char ID; // Pass identification, replacement for typeid
        CoalescingEngine();

        virtual void getAnalysisUsage(llvm::AnalysisUsage& AU) const override;

        virtual void releaseMemory() override {
            Allocator.Reset();

            for (auto itr = m_CCTupleList.begin(),
                iend = m_CCTupleList.end();
                itr != iend; ++itr)
            {
                CCTuple* ccTuple = *itr;
                delete ccTuple;
            }
            m_CCTupleList.clear();
            //Nodes need not be deallocated since they are
            //owned by bump allocator (Allocator), and are destroyed
            //once bump allocator goes out the the scope.
            NodeCCTupleMap.clear();
            ValueNodeMap.clear();
            BBProcessingDefs.clear();
            NodeOffsetMap.clear();
        }

        bool runOnFunction(llvm::Function&) override;

        virtual llvm::StringRef getPassName() const override {
            return "CoalescingEngine";
        }

        /// print - print partitions in human readable form
        void print(llvm::raw_ostream& OS, const llvm::Module* = 0) const override;

        /// dump - Dump the partitions to dbgs().
        void dump() const;

        void ProcessBlock(llvm::BasicBlock* bb);

        //
        bool MatchSingleInstruction(llvm::GenIntrinsicInst* I);


        int GetSingleElementWidth(
            SIMDMode simdMode,
            const llvm::DataLayout* pDL,
            llvm::Value* val)
        {
            int result = 0;
            int mult = 1;
            if (val->getType()->isHalfTy() && simdMode == SIMDMode::SIMD8)
            {
                mult = 2;
            }

            result = int_cast<int>(mult *
                numLanes(simdMode) *
                pDL->getTypeAllocSize(val->getType()));

            return result;
        }

        //
        CVariable* PrepareExplicitPayload(
            CShader* outProgram,
            CEncoder* encoder,
            SIMDMode simdMode,
            const llvm::DataLayout* pDL,
            llvm::Instruction* inst,
            int& payloadOffset);

        CVariable* PrepareUniformUrbWritePayload(
            CShader* shader,
            CEncoder* encoder,
            llvm::GenIntrinsicInst* inst);

        CVariable* PrepareSplitUrbWritePayload(
            CShader* outProgram,
            CEncoder* encoder,
            SIMDMode simdMode,
            uint32_t splitPartNo,
            llvm::Instruction* inst);

        void visitCastInst(llvm::CastInst& I);
        void visitBinaryOperator(llvm::BinaryOperator& I);
        void visitCmpInst(llvm::CmpInst& I);
        void visitPHINode(llvm::PHINode& I);
        void visitUnaryInstruction(llvm::UnaryInstruction& I);
        void visitCallInst(llvm::CallInst& I);
        void visitSelectInst(llvm::SelectInst& I);
        void visitBitCastInst(llvm::BitCastInst& I);
        void visitInstruction(llvm::Instruction& I);
        void visitLoadInst(llvm::LoadInst& I);
        void visitStoreInst(llvm::StoreInst& I);


        //////////////////////////////////////////////////////////////////////////
        struct ElementNode
        {
            enum Flags {
                kRegisterIsolatedFlag = 1,
                kPHIIsolatedFlag = 2
            };
            ElementNode(llvm::Value* _value) :
                value(_value), rank(0)
            {
                parent.setPointer(this);
            }

            ~ElementNode()
            {
            }

            ElementNode* getLeader();

            // Fields:
            llvm::PointerIntPair<ElementNode*, 2> parent;
            llvm::Value* value;
            unsigned rank;
        };

        //////////////////////////////////////////////////////////////////////////
        struct CCTuple
        {
            CCTuple() :
                leftBound(0),
                rightBound(0),
                hasNonHomogeneousElements(false),
                rootInst(nullptr)
            {
            }

            int leftBound;
            int rightBound;


            int GetLeftBound() const
            {
                return leftBound;
            }

            int GetRightBound() const
            {
                return rightBound;
            }


            //cannot be safely extended left/right (used for non-homogeneous payload modeling)
            bool hasNonHomogeneousElements;

            llvm::Instruction* rootInst;

            inline bool HasNonHomogeneousElements() const
            {
                return hasNonHomogeneousElements;
            }

            inline void SetHasNonHomogeneousElements(llvm::Instruction* _rootInst)
            {
                IGC_ASSERT(rootInst == nullptr);
                rootInst = _rootInst;
                hasNonHomogeneousElements = true;
            }

            inline llvm::Instruction* GetRoot() const
            {
                return rootInst;
            }


            inline uint GetNumElements() const
            {
                IGC_ASSERT(rightBound >= leftBound);
                return rightBound - leftBound + 1;
            }

            inline void InitializeIndexWithCCRoot(int index, ElementNode* elNode)
            {
                OffsetToCCMap[index] = elNode;

                ResizeBounds(index);
            }

            inline void ResizeBounds(int index)
            {
                if (index < leftBound)
                {
                    leftBound = index;
                }

                if (index > rightBound)
                {
                    rightBound = index;
                }
            }

            inline void CheckIndexForNonInitializedSlot(int index)
            {
                //if (OffsetToCCMap.count(index) == 0)
                {
                    ResizeBounds(index);
                }
            }


            ElementNode* GetCCNodeWithIndex(int index)
            {
                return OffsetToCCMap[index];
            }

            void AttachNodeAtIndex(int index, ElementNode* node, CoalescingEngine& CE)
            {
                if (OffsetToCCMap.count(index) == 0 || OffsetToCCMap[index] == NULL)
                {
                    IGC_ASSERT(node->value == CE.getRegRoot(node->value));

                    CE.NodeCCTupleMap[node] = this;
                    CE.NodeOffsetMap[node] = index;

                    InitializeIndexWithCCRoot(index, node);
                    CE.CurrentDominatingParent[node->value] = node->value;
                    CE.ImmediateDominatingParent[node->value] = NULL;
                }
                else
                {
                    if (OffsetToCCMap[index] == node)
                    {
                        //Do nothing, it is already there.
                    }
                    else
                    {
                        //Here comes a logic that will attach a new node to CC.
                        IGC_ASSERT(OffsetToCCMap.count(index));
                        IGC_ASSERT(OffsetToCCMap[index]);

                        llvm::Value* ccRootValue = OffsetToCCMap[index]->value;

                        CE.unionRegs(ccRootValue, node->value);

                        llvm::Value* NewParent = CE.GetActualDominatingParent(
                            ccRootValue,
                            llvm::dyn_cast<llvm::Instruction>(node->value));

                        CE.ImmediateDominatingParent[node->value] = NewParent;
                        CE.CurrentDominatingParent[ccRootValue] = node->value;
                    }
                }
            }

            //print in human readable form
            void print(llvm::raw_ostream& OS, const llvm::Module* = 0) const;

            void dump() const;

            //FIXME: not sure whether this is the best choice
        protected:
            llvm::DenseMap<int, ElementNode*> OffsetToCCMap;

            friend class CoalescingEngine;
        };

        friend struct CCTuple;

        ///returns non-null CCtuple pointer if there is at least
        // one value that is 'coalesced' into the tuple.
        // It returns one of those values (e.g. for type insepction)
        // if the condition is true.
        CCTuple* IsAnyValueCoalescedInCCTuple(
            llvm::Instruction* inst,
            const uint numOperands,
            int& zeroBasedPayloadElementOffset,
            llvm::Value*& val);

        ///
        bool IsPayloadCovered(
            llvm::Instruction* inst,
            CCTuple* ccTuple,
            const uint numOperands,
            const int payloadToCCTupleRelativeOffset);


        //FIXME: do a filter over relevant (TGI) instructions
        uint DetermineWeight(llvm::Value* val)
        {
            if (ValueWeightMap.count(val)) {
                return ValueWeightMap[val];
            }
            else {
                uint numUsers = 0;
                {
                    llvm::SmallPtrSet<llvm::User*, 8> touchedUsers;
                    for (llvm::Value::user_iterator i = val->user_begin(), e = val->user_end(); i != e; ++i) {
                        llvm::User* user = *i;
                        if (llvm::isa<llvm::Instruction>(user)) {
                            if (!touchedUsers.count(user))
                            {
                                numUsers++;
                                touchedUsers.insert(user);
                            }
                        }
                    }
                }
                ValueWeightMap[val] = numUsers;
                return numUsers;
            }
        }

        //FIXME: this might not be the most effective way if called multiple times
        bool IsolationFilter(llvm::Value* val) const
        {
            if (isCoalescedByDeSSA(val)) {
                return true;
            }
            if (llvm::dyn_cast<llvm::PHINode>(val)) {
                return true;
            }
            else if (llvm::dyn_cast<llvm::ExtractElementInst>(val)) {
                return true;
            }
            else {
                for (llvm::Value::user_iterator i = val->user_begin(), e = val->user_end(); i != e; ++i)
                {
                    if (llvm::dyn_cast<llvm::PHINode>(*i)) {
                        return true;
                    }
                }
            }

            return false;
        }

        bool IsValIsolated(llvm::Value* val)
        {
            return IsolationFilter(val) ||
                isUniform(val) ||
                llvm::isa<llvm::Argument>(val);
        }

        inline bool IsValConstOrIsolated(llvm::Value* val) const
        {
            return llvm::isa<llvm::Constant>(val) ||
                IsolationFilter(val) ||
                isUniform(val) ||
                llvm::isa<llvm::Argument>(val);
        }


        void IncrementalCoalesce(llvm::BasicBlock*);
        void PrepareTuple(
            const uint numOperands,
            llvm::Instruction* tupleGeneratingInstruction,
            llvm::SmallPtrSet<CCTuple*, 8> & touchedTuplesSet,
            llvm::SmallVector<CCTuple*, 8> & touchedTuples,
            bool& isAnyNodeAnchored,
            bool& isAnyNodeCoalescable);

        void DecideSplit(llvm::Instruction* tupleGeneratingInstruction);

        void CreateTuple(
            const uint numOperands,
            llvm::Instruction* tupleGeneratingInstruction);

        void DetermineAnchor(
            const uint numOperands,
            const llvm::Instruction* tupleGeneratingInstruction,
            CCTuple*& ccTuple,
            int& rootTupleStartOffset,
            int& thisTupleStartOffset);

        //Return true if it is ok to continue, false if interference is detected
        bool EvictOrStop(
            CCTuple* ccTuple,
            const int index,
            llvm::Instruction* tupleGeneratingInstruction,
            bool const forceEviction,
            //out:
            bool& interferes)
        {
            if (!IsInsertionSlotAvailable(ccTuple, index, tupleGeneratingInstruction)) {
                if (forceEviction) {
                    PrepareInsertionSlot(ccTuple, index, tupleGeneratingInstruction);
                    return true; //we can continue
                }
                else {
                    interferes = true;
                    return false; //abort whole 'transaction'
                }
            }
            return true;
        }

        class ProcessInterferencesElementFunctor;

        bool InterferenceCheck(
            const uint numOperands,
            llvm::Instruction* tupleGeneratingInstruction,
            const int offsetDiff,
            CCTuple* ccTuple,
            //out:
            ProcessInterferencesElementFunctor* interferencesFunctor);

        /// \brief return true if element slot is safe for copying-in
        /// canExtend - if true, it is assumed that ccTuple can be 'still' extended
        ///
        ///
        bool IsInsertionSlotAvailable(
            CCTuple* ccTuple,
            const int index,
            llvm::Instruction* tupleGeneratingInstruction,
            const bool canExtend = true);

        void PrepareInsertionSlot(
            CCTuple* ccTuple,
            const int index,
            llvm::Instruction* tupleGeneratingInstruction,
            const bool evictFullCongruenceClass = false);

        bool CheckIntersectionForNonHomogeneous(
            const uint numOperands,
            llvm::Instruction* tupleGeneratingInstruction,
            const int offsetDiff,
            CCTuple* ccTuple);

        void ProcessTuple(llvm::Instruction* tupleGeneratingInstruction);
        void GreedyHeuristic(llvm::Instruction* tupleGeneratingInstruction);

        std::vector<CCTuple*>& GetCCTupleList()
        {
            return m_CCTupleList;
        }

        /// Get the union-root of a register. The root is 0 if the register has been
        /// isolated.
        llvm::Value* getRegRoot(llvm::Value*) const;

        ///Given the currentInstruction and root identifier of CC, find the element
        ///that belongs to CC and is a proper dominator of the currentInstruction.
        ///In straight-line codes and in separate payload and de-ssa phases, this
        ///actually should always give the results in one iteration.
        // Pop registers from the stack represented by ImmediateDominatingParent
        // until we find a parent that dominates the current instruction.
        inline llvm::Value* GetActualDominatingParent(llvm::Value* RootV, llvm::Instruction* currentInstruction)
        {
            llvm::Value* NewParent = CurrentDominatingParent[RootV];

            while (NewParent) {
                if (getRegRoot(NewParent)) {
                    //Fixme: here it does not apply.
                    // we have added the another condition because the domination-test
                    // does not work between two phi-node. See the following comments
                    // from the DT::dominates:
                    // " It is not possible to determine dominance between two PHI nodes
                    //   based on their ordering
                    //  if (isa<PHINode>(A) && isa<PHINode>(B))
                    //    return false;"
                    if (llvm::isa<llvm::Argument>(NewParent)) {
                        break;
                    }
                    else if (DT->dominates(llvm::cast<llvm::Instruction>(NewParent), currentInstruction)) {
                        break;
                    } /* else if (cast<llvm::Instruction>(NewParent)->getParent() == MBB &&
                        isa<PHINode>(DefMI) && isa<PHINode>(NewParent)) {
                            break;
                    } */
                }
                NewParent = ImmediateDominatingParent[NewParent];
            }

            return NewParent;
        }

        //Here we test the interference between the
        //Algorithm:
        //Starting from the currentDominatingParent, walk the congruence class
        //dominance tree upward, until an element that dominates the currentInstruction
        //is found.
        //Since this method could be called on the non-dominance traversal (e.g.
        //currentInstruction dominates some elements in the tree)
        // Say we have a dominance tree that is already constructed (lifetime goes
        // downwards):
        // CC dominance tree
        //    v67
        //    ^
        //    |
        //   v121 (dominating)
        //    ^
        //    |    -----   v181
        //    |
        //   v190 <- (dominated)
        //
        // Want to check the interference with v181, which dominates v190, but is dominated
        // by v121. if we would just look for a dominating element for v181, we would find
        // out that v121 is dominator of v181 and (say) it is not interfering with v181, thus
        // leading to conclusion that there is no interference between v181 and CC dominance tree.

        inline void SymmetricInterferenceTest(
            llvm::Value* RootV,
            llvm::Instruction* currentInstruction,
            llvm::Value*& dominating, //in-out
            llvm::Value*& dominated)
        {
            llvm::Value* NewParent = CurrentDominatingParent[RootV];
            dominating = nullptr;
            dominated = nullptr;

            while (NewParent)
            {
                if (getRegRoot(NewParent)) //not isolated
                {
                    if (llvm::isa<llvm::Argument>(NewParent))
                    {
                        dominating = NewParent;
                        break;
                    }
                    else if (DT->dominates(llvm::cast<llvm::Instruction>(NewParent), currentInstruction))
                    {
                        dominating = NewParent;
                        break;
                    }
                    dominated = NewParent;
                }
                NewParent = ImmediateDominatingParent[NewParent];
            }
        }

        inline CCTuple* GetValueCCTupleMapping(llvm::Value* val)
        {
            llvm::Value* RootV = getRegRoot(val);
            if (!RootV) {
                return NULL;
            }

            IGC_ASSERT(ValueNodeMap.count(RootV));
            auto RI = ValueNodeMap.find(RootV);
            ElementNode* Node = RI->second;

            auto CCI = NodeCCTupleMap.find(Node);
            if (CCI != NodeCCTupleMap.end()) {
                return CCI->second;
            }
            else {
                return NULL;
            }
        }

        /// Caller is responsible for assuring that value is not isolated
        // e.g. by calling GetCalueCCTupleMapping previously.
        inline int GetValueOffsetInCCTuple(llvm::Value* val)
        {
            llvm::Value* RootV = getRegRoot(val);
            IGC_ASSERT(nullptr != RootV);
            IGC_ASSERT(ValueNodeMap.count(RootV));

            auto RI = ValueNodeMap.find(RootV);
            ElementNode* Node = RI->second;

            auto CCI = NodeOffsetMap.find(Node);
            IGC_ASSERT(CCI != NodeOffsetMap.end());
            return CCI->second;
        }

        //////////////////////////////////////////////////////////////////////////
        class ElementFunctor {
        public:
            virtual void SetIndex(int index) = 0;
            virtual bool visitCopy() = 0;
            virtual bool visitConstant() = 0;
            virtual bool visitArgument() = 0;
            virtual bool visitIsolated() = 0;
            virtual bool visitAnchored() = 0;
            virtual bool visitInterfering(llvm::Value* val, const bool evictFullCongruenceClass) = 0;
            virtual bool visitPackedNonInterfering(llvm::Value* val) = 0;
            virtual ~ElementFunctor() {}
        };

        //////////////////////////////////////////////////////////////////////////
        class GatherWeightElementFunctor : public ElementFunctor
        {
        public:
            GatherWeightElementFunctor() :
                nAlignedAnchors(0),
                nInsertionSlotRequired(0),
                nNeedsDisplacement(0)
            {
            }

            virtual void SetIndex(int index)
            {
                IGC_UNUSED(index);
            }

            virtual bool visitCopy()
            {
                nInsertionSlotRequired++;
                return true;
            }

            virtual bool visitConstant()
            {
                nInsertionSlotRequired++;
                return true;
            }

            ///Not used yet, but is here in an interface
            ///for completeness.
            virtual bool visitArgument()
            {
                return true;
            }

            virtual bool visitIsolated()
            {
                nInsertionSlotRequired++;
                return true;
            }

            ///Visits constrained (anchored) element.
            virtual bool visitAnchored()
            {
                nAlignedAnchors++;
                return true;
            }

            ///Visits a value in a tuple that interferes with some (non-isolated)
            ///element in a CC class that occupies the same slot.
            virtual bool visitInterfering(
                llvm::Value* val,
                const bool evictFullCongruenceClass)
            {
                IGC_UNUSED(val);
                IGC_UNUSED(evictFullCongruenceClass);
                nNeedsDisplacement++;
                return true;
            }

            virtual bool visitPackedNonInterfering(llvm::Value* val)
            {
                IGC_UNUSED(val);
                return true;
            }

            ///Gets the number of 'anchored' elements in a tuple.
            inline int GetNumAlignedAnchors() const
            {
                return nAlignedAnchors;
            }

            inline int GetNumInsertionSlotsRequired() const
            {
                return nInsertionSlotRequired;
            }

            ///Gets the number of values in a tuple
            inline int GetNumNeedsDisplacement() const
            {
                return nNeedsDisplacement;
            }

        private:
            int nAlignedAnchors;
            int nInsertionSlotRequired;
            int nNeedsDisplacement;
        };

        //////////////////////////////////////////////////////////////////////////
        class ProcessInterferencesElementFunctor : public ElementFunctor
        {
        private:
            bool m_forceEviction;
            bool m_interferes;
            llvm::Instruction* m_tupleInst;
            const int m_offsetDiff;
            CCTuple* m_ccTuple;
            CoalescingEngine* m_CE;
            int m_index;
            llvm::SmallPtrSet<llvm::Value*, 8> m_valuesForIsolation;

        public:
            ProcessInterferencesElementFunctor(
                bool forceEviction,
                llvm::Instruction* inst,
                const int offsetDiff,
                CCTuple* ccTuple,
                CoalescingEngine* CE) :
                m_forceEviction(forceEviction),
                m_interferes(false),
                m_tupleInst(inst),
                m_offsetDiff(offsetDiff),
                m_ccTuple(ccTuple),
                m_CE(CE),
                m_index(0)
            {

            }

            llvm::SmallPtrSet<llvm::Value*, 8> & GetComputedValuesForIsolation()
            {
                return m_valuesForIsolation;
            }

            inline void SetForceEviction(bool force)
            {
                m_forceEviction = force;
            }

            inline bool IsInterfering() const
            {
                return m_interferes;
            }

            virtual void SetIndex(int index)
            {
                m_index = index;
            }

            virtual bool visitCopy()
            {
                return m_CE->EvictOrStop(
                    m_ccTuple,
                    m_index + m_offsetDiff,
                    m_tupleInst,
                    m_forceEviction,
                    m_interferes);
            }
            virtual bool visitConstant()
            {
                return m_CE->EvictOrStop(
                    m_ccTuple,
                    m_index + m_offsetDiff,
                    m_tupleInst,
                    m_forceEviction,
                    m_interferes);
            }
            virtual bool visitIsolated()
            {
                return m_CE->EvictOrStop(
                    m_ccTuple,
                    m_index + m_offsetDiff,
                    m_tupleInst,
                    m_forceEviction,
                    m_interferes);
            }

            virtual bool visitArgument()
            {
                return m_CE->EvictOrStop(
                    m_ccTuple,
                    m_index + m_offsetDiff,
                    m_tupleInst,
                    m_forceEviction,
                    m_interferes);
            }

            virtual bool visitAnchored()
            {
                return true;
            }

            virtual bool visitInterfering(llvm::Value* val, const bool evictFullCongruenceClass)
            {
                IGC_UNUSED(evictFullCongruenceClass);
                if (m_forceEviction) {

                    // HEURISTIC:
                    if (m_CE->DetermineWeight(val) < 2) {

                        m_CE->PrepareInsertionSlot(
                            m_ccTuple,
                            m_index + m_offsetDiff,
                            m_tupleInst,
                            false //evictFullCongruenceClass
                        );

                        m_valuesForIsolation.insert(val);
                    }
                    else
                    {
                        m_CE->PrepareInsertionSlot(
                            m_ccTuple,
                            m_index + m_offsetDiff,
                            m_tupleInst,
                            true //evictFullCongruenceClass
                        );

                    }
                    return true;
                }
                else {
                    m_interferes = true;
                    return false;
                }

                return true;
            }

            virtual bool visitPackedNonInterfering(llvm::Value* val)
            {
                if (m_CE->DetermineWeight(val) < 2) {
                    m_valuesForIsolation.insert(val);
                }

                return true;
            }
        };

        void ProcessElements(
            const uint numOperands,
            llvm::Instruction* tupleInst,
            const int offsetDiff,
            CCTuple* ccTuple,
            ElementFunctor* functor);

    public:

        uint GetNumPayloadElements(llvm::Instruction* inst)
        {
            if (currentPart_ == 0)
            {
                auto iter = splitPoint_.find(inst);
                if (iter == splitPoint_.end())
                {
                    //means we have no split point, can
                    return m_PayloadMapping.GetNumPayloadElements(inst);
                }
                else
                {
                    IGC_ASSERT((*iter).second > 0);
                    return (*iter).second;
                }
                //return splitPoint_
            }
            else
            {
                IGC_ASSERT(currentPart_ == 1);
                auto iter = splitPoint_.find(inst);
                IGC_ASSERT(iter != splitPoint_.end());
                return m_PayloadMapping.GetNumPayloadElements(inst) - (*iter).second;
            }
        }
        //uint GetNonAdjustedNumPayloadElements_Sample(const SampleIntrinsic *inst)
        //{
        //    return m_PayloadMapping.GetNonAdjustedNumPayloadElements_Sample(inst);
        //}

        int GetNumPayloadElements_Sample(const llvm::SampleIntrinsic* inst)
        {
            return m_PayloadMapping.GetNumPayloadElements_Sample(inst);
        }

        /// Get the mapping from the payload element (at position index)
        /// to intrinsic argument value. Indexing is zero based.
        llvm::Value* GetPayloadElementToValueMapping(const llvm::Instruction* inst, uint index)
        {
            return m_PayloadMapping.GetPayloadElementToValueMapping(inst, currentLowBound_ + index);
        }
        llvm::Value* GetPayloadElementToValueMapping_sample(const llvm::SampleIntrinsic* inst, const uint index)
        {
            return m_PayloadMapping.GetPayloadElementToValueMapping_sample(inst, index);
        }
        llvm::Value* GetNonAdjustedPayloadElementToValueMapping_sample(const llvm::SampleIntrinsic* inst, const uint index)
        {
            return m_PayloadMapping.GetNonAdjustedPayloadElementToValueMapping_sample(inst, index);
        }

        bool HasNonHomogeneousPayloadElements(const llvm::Instruction* inst)
        {
            return m_PayloadMapping.HasNonHomogeneousPayloadElements(inst);
        }
        int GetLeftReservedOffset(const llvm::Instruction* inst, SIMDMode simdMode)
        {
            return m_PayloadMapping.GetLeftReservedOffset(inst, simdMode);
        }

        int GetRightReservedOffset(const llvm::Instruction* inst, SIMDMode simdMode)
        {
            return m_PayloadMapping.GetRightReservedOffset(inst, simdMode);
        }
        const llvm::Instruction* GetSupremumOfNonHomogeneousPart(
            const llvm::Instruction* inst1,
            const llvm::Instruction* inst2)
        {
            return m_PayloadMapping.GetSupremumOfNonHomogeneousPart(inst1, inst2);
        }

        uint GetNumSplitParts(llvm::Instruction* inst)
        {
            auto iter = splitPoint_.find(inst);
            if (iter != splitPoint_.end())
            {
                uint splitIndex = (*iter).second;
                return splitIndex > 0 ? 2 : 1;
            }
            else
            {
                return 1;
            }
        }

        void SetCurrentPart(llvm::Instruction* inst, unsigned int partNum)
        {
            if (partNum == 0)
            {
                currentLowBound_ = 0;
                currentPart_ = partNum;
                //            currentUpperBound_ = splitPoint_[inst];
            }
            else
            {
                IGC_ASSERT(partNum == 1);
                currentLowBound_ = splitPoint_[inst];
                IGC_ASSERT(currentLowBound_ > 0);
                currentPart_ = partNum;
            }
        }

    private:

        CPlatform m_Platform;
        PayloadMapping m_PayloadMapping;
        std::vector<CCTuple*> m_CCTupleList;
        llvm::DominatorTree* DT;
        LiveVars* LV;
        WIAnalysis* WIA;
        DeSSA* m_DeSSA;
        CodeGenPatternMatch* CG;
        llvm::DenseMap<llvm::Value*, ElementNode*> ValueNodeMap;
        llvm::DenseMap<ElementNode*, CCTuple*> NodeCCTupleMap;
        //Mapping root element node to its offset in cc tuple:
        llvm::DenseMap<ElementNode*, int> NodeOffsetMap;
        llvm::DenseMap<llvm::Value*, uint> ValueWeightMap;
        ModuleMetaData* m_ModuleMetadata;
        CodeGenContext* m_CodeGenContext;
        //Maps a basic block to a list of instruction defs to be processed for coalescing (in dominance order)
        llvm::DenseMap<llvm::BasicBlock*, std::vector<llvm::Instruction*> > BBProcessingDefs;


        /* Taken from strong DE SSA */
        // Perform a depth-first traversal of the dominator tree, splitting
        // interferences amongst PHI-congruence classes.

        llvm::BumpPtrAllocator Allocator;

        llvm::DenseMap<llvm::Value*, llvm::Value*> CurrentDominatingParent;
        llvm::DenseMap<llvm::Value*, llvm::Value*> ImmediateDominatingParent;

        llvm::DenseMap<llvm::Instruction*, uint> splitPoint_;
        unsigned currentLowBound_;
        //unsigned currentUpperBound_;
        unsigned currentPart_;

        /// Get the union-root of a PHI. The root of a PHI is 0 if the PHI has been
        /// isolated. Otherwise, it is the original root of its destination and
        /// all of its operands (before they were isolated, if they were).
        llvm::Value* getPHIRoot(llvm::Instruction*) const;

        void unionRegs(llvm::Value*, llvm::Value*);

        bool isUniform(llvm::Value* v) const {
            return (WIA->isUniform(v));
        }

        // Isolate a register.
        void isolateReg(llvm::Value* Val) {
            ElementNode* Node = ValueNodeMap[Val];
            Node->parent.setInt(Node->parent.getInt() | ElementNode::kRegisterIsolatedFlag);
        }
        /* Taken from strong DE SSA */



        struct MIIndexCompare {
            MIIndexCompare(LiveVars* _lv) : LV(_lv) { }

            bool operator()(const llvm::Instruction* LHS, const llvm::Instruction* RHS) const {
                return LV->getDistance(LHS) < LV->getDistance(RHS);
            }

            LiveVars* LV;
        };

        bool isCoalescedByDeSSA(llvm::Value* V) const;
    };

} //namespace IGC