summaryrefslogtreecommitdiff
path: root/backend/src/llvm/llvm_gen_backend.cpp
blob: cbda45ccea86a7ca2e8102c1f8c4bee25f5e20c1 (plain)
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
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
/* 
 * Copyright © 2012 Intel Corporation
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library. If not, see <http://www.gnu.org/licenses/>.
 *
 * Author: Benjamin Segovia <benjamin.segovia@intel.com>
 */

/**
 * \file llvm_gen_backend.cpp
 * \author Benjamin Segovia <benjamin.segovia@intel.com>
 *
 * Transform the LLVM IR code into Gen IR code
 */
#include "llvm/CallingConv.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Module.h"
#include "llvm/Instructions.h"
#include "llvm/Pass.h"
#include "llvm/PassManager.h"
#include "llvm/Intrinsics.h"
#include "llvm/IntrinsicInst.h"
#include "llvm/InlineAsm.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Analysis/ConstantsScanner.h"
#include "llvm/Analysis/FindUsedTypes.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/IntrinsicLowering.h"
#include "llvm/Target/Mangler.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCObjectFileInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Support/CallSite.h"
#include "llvm/Support/CFG.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/GetElementPtrTypeIterator.h"
#include "llvm/Support/InstVisitor.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Config/config.h"

#include "llvm/llvm_gen_backend.hpp"
#include "ir/context.hpp"
#include "ir/unit.hpp"
#include "sys/map.hpp"
#include "sys/set.hpp"
#include <algorithm>

using namespace llvm;

namespace gbe
{
  /*! Gen IR manipulates only scalar types */
  static bool isScalarType(const Type *type)
  {
    return type->isFloatTy()   ||
           type->isIntegerTy() ||
           type->isDoubleTy()  ||
           type->isPointerTy();
  }

  /*! LLVM IR Type to Gen IR type translation */
  static ir::Type getType(const ir::Context &ctx, const Type *type)
  {
    GBE_ASSERT(isScalarType(type));
    if (type->isFloatTy() == true)
      return ir::TYPE_FLOAT;
    if (type->isDoubleTy() == true)
      return ir::TYPE_DOUBLE;
    if (type->isPointerTy() == true) {
      if (ctx.getPointerSize() == ir::POINTER_32_BITS)
        return ir::TYPE_U32;
      else
        return ir::TYPE_U64;
    }
    GBE_ASSERT(type->isIntegerTy() == true);
    if (type == Type::getInt1Ty(type->getContext()))
      return ir::TYPE_BOOL;
    if (type == Type::getInt8Ty(type->getContext()))
      return ir::TYPE_S8;
    if (type == Type::getInt16Ty(type->getContext()))
      return ir::TYPE_S16;
    if (type == Type::getInt32Ty(type->getContext()))
      return ir::TYPE_S32;
    if (type == Type::getInt64Ty(type->getContext()))
      return ir::TYPE_S64;
    GBE_ASSERT(0);
    return ir::TYPE_S64;
  }

  /*! Type to register family translation */
  static ir::RegisterFamily getFamily(const ir::Context &ctx, const Type *type)
  {
    GBE_ASSERT(isScalarType(type) == true); 
    if (type == Type::getInt1Ty(type->getContext()))
      return ir::FAMILY_BOOL;
    if (type == Type::getInt8Ty(type->getContext()))
      return ir::FAMILY_BYTE;
    if (type == Type::getInt16Ty(type->getContext()))
      return ir::FAMILY_WORD;
    if (type == Type::getInt32Ty(type->getContext()) || type->isFloatTy())
      return ir::FAMILY_DWORD;
    if (type == Type::getInt64Ty(type->getContext()) || type->isDoubleTy())
      return ir::FAMILY_QWORD;
    if (type->isPointerTy())
      return ctx.getPointerFamily();
    GBE_ASSERT(0);
    return ir::FAMILY_BOOL;
  }

  /*! Get number of element to process dealing either with a vector or a scalar
   *  value
   */
  static ir::Type getVectorInfo(const ir::Context &ctx, Type *llvmType, Value *value, uint32_t &elemNum)
  {
    ir::Type type;
    if (llvmType->isVectorTy() == true) {
      VectorType *vectorType = cast<VectorType>(llvmType);
      Type *elementType = vectorType->getElementType();
      elemNum = vectorType->getNumElements();
      type = getType(ctx, elementType);
    } else {
      elemNum = 1;
      type = getType(ctx, llvmType);
    }
    return type;
  }

  /*! OCL to Gen-IR address type */
  static INLINE ir::AddressSpace addressSpaceLLVMToGen(unsigned llvmMemSpace) {
    switch (llvmMemSpace) {
      case 0: return ir::MEM_PRIVATE;
      case 1: return ir::MEM_GLOBAL;
      case 2: return ir::MEM_CONSTANT;
      case 4: return ir::MEM_LOCAL;
    }
    GBE_ASSERT(false);
    return ir::MEM_GLOBAL;
  }

  /*! Handle the LLVM IR Value to Gen IR register translation. This has 2 roles:
   *  - Split the LLVM vector into several scalar values
   *  - Handle the transparent copies (bitcast or use of intrincics functions
   *    like get_local_id / get_global_id
   */
  class RegisterTranslator
  {
  public:
    RegisterTranslator(ir::Context &ctx) : ctx(ctx) {}

    /*! Empty the maps */
    void clear(void) {
      valueMap.clear();
      scalarMap.clear();
    }
    /*! Some values will not be allocated. For example, a bit-cast destination
     *  like: %fake = bitcast %real or a vector insertion since we do not have
     *  vectors in Gen-IR
     */
    void newValueProxy(Value *real,
                       Value *fake,
                       uint32_t realIndex = 0u,
                       uint32_t fakeIndex = 0u) {
      const ValueIndex key(fake, fakeIndex);
      const ValueIndex value(real, realIndex);
      GBE_ASSERT(valueMap.find(key) == valueMap.end()); // Do not insert twice
      valueMap[key] = value;
    }
    /*! Mostly used for the preallocated registers (lids, gids) */
    void newScalarProxy(ir::Register reg, Value *value, uint32_t index = 0u) {
      const ValueIndex key(value, index);
      GBE_ASSERT(scalarMap.find(key) == scalarMap.end());
      scalarMap[key] = reg;
    }
    /*! Allocate a new scalar register */
    ir::Register newScalar(Value *value, uint32_t index = 0u)
    {
      GBE_ASSERT(dyn_cast<Constant>(value) == NULL);
      Type *type = value->getType();
      auto typeID = type->getTypeID();
      switch (typeID) {
        case Type::IntegerTyID:
        case Type::FloatTyID:
        case Type::DoubleTyID:
        case Type::PointerTyID:
          GBE_ASSERT(index == 0);
          return this->newScalar(value, type, index);
          break;
        case Type::VectorTyID:
        {
          auto vectorType = cast<VectorType>(type);
          auto elementType = vectorType->getElementType();
          auto elementTypeID = elementType->getTypeID();
          if (elementTypeID != Type::IntegerTyID &&
              elementTypeID != Type::FloatTyID &&
              elementTypeID != Type::DoubleTyID)
            GBE_ASSERTM(false, "Vectors of elements are not supported");
            return this->newScalar(value, elementType, index);
          break;
        }
        default: NOT_SUPPORTED;
      };
      return ir::Register();
    }
    /*! Get the register from the given value at given index possibly iterating
     *  in the value map to get the final real register
     */
    ir::Register getScalar(Value *value, uint32_t index = 0u) {
      auto end = valueMap.end();
      for (;;) {
        auto it = valueMap.find(std::make_pair(value, index));
        if (it == end)
          break;
        else {
          value = it->second.first;
          index = it->second.second;
        }
      }
      const auto key = std::make_pair(value, index);
      GBE_ASSERT(scalarMap.find(key) != scalarMap.end());
      return scalarMap[key];
    }
    /*! Insert a given register at given Value position */
    void insertRegister(const ir::Register &reg, Value *value, uint32_t index) {
      const auto key = std::make_pair(value, index);
      GBE_ASSERT(scalarMap.find(key) == scalarMap.end());
      scalarMap[key] = reg;
    }
  private:
    /*! This creates a scalar register for a Value (index is the vector index when
     *  the value is a vector of scalars)
     */
    ir::Register newScalar(Value *value, Type *type, uint32_t index) {
      const ir::RegisterFamily family = getFamily(ctx, type);
      const ir::Register reg = ctx.reg(family);
      this->insertRegister(reg, value, index);
      return reg;
    }
    /*! Indices will be zero for scalar values */
    typedef std::pair<Value*, uint32_t> ValueIndex;
    /*! Map value to ir::Register */
    map<ValueIndex, ir::Register> scalarMap;
    /*! Map values to values when this is only a translation (eq bitcast) */
    map<ValueIndex, ValueIndex> valueMap;
    /*! Actually allocates the registers */
    ir::Context &ctx;
  };

  class CBEMCAsmInfo : public MCAsmInfo {
  public:
    CBEMCAsmInfo() {
      GlobalPrefix = "";
      PrivateGlobalPrefix = "";
    }
  };

  /*! Translate LLVM IR code to Gen IR code */
  class GenWriter : public FunctionPass, public InstVisitor<GenWriter>
  {
    /*! Unit to compute */
    ir::Unit &unit;
    /*! Helper structure to compute the unit */
    ir::Context ctx;
    /*! Make the LLVM-to-Gen translation */
    RegisterTranslator regTranslator;
    /*! Map target basic block to its ir::LabelIndex */
    map<const BasicBlock*, ir::LabelIndex> labelMap;
    /*! Condition inversion can simplify branch code. We store here all the
     *  compare instructions we need to invert to decrease branch complexity
     */
    set<const Value*> conditionSet;
    /*! We visit each function twice. Once to allocate the registers and once to
     *  emit the Gen IR instructions 
     */
    enum Pass {
      PASS_EMIT_REGISTERS = 0,
      PASS_EMIT_INSTRUCTIONS = 1
    } pass;

    Mangler *Mang;
    LoopInfo *LI;
    const Module *TheModule;
    const TargetData* TD;
    const MCAsmInfo* TAsm;
    const MCRegisterInfo *MRI;
    MCContext *TCtx;

  public:
    static char ID;
    explicit GenWriter(ir::Unit &unit)
      : FunctionPass(ID),
        unit(unit),
        ctx(unit),
        regTranslator(ctx),
        Mang(0), LI(0),
        TheModule(0), TD(0)
    {
      initializeLoopInfoPass(*PassRegistry::getPassRegistry());
      pass = PASS_EMIT_REGISTERS;
    }

    virtual const char *getPassName() const { return "Gen Back-End"; }

    void getAnalysisUsage(AnalysisUsage &AU) const {
      AU.addRequired<LoopInfo>();
      AU.setPreservesAll();
    }

    virtual bool doInitialization(Module &M);

    bool runOnFunction(Function &F) {
     // Do not codegen any 'available_externally' functions at all, they have
     // definitions outside the translation unit.
     if (F.hasAvailableExternallyLinkage())
       return false;

      LI = &getAnalysis<LoopInfo>();

      emitFunction(F);
      return false;
    }

    virtual bool doFinalization(Module &M) {
      delete TD;
      delete TAsm;
      delete Mang;
      delete TCtx;
      delete MRI;
      return false;
    }

    /*! Emit the complete function code and declaration */
    void emitFunction(Function &F);
    /*! Handle input and output function parameters */
    void emitFunctionPrototype(Function &F);
    /*! Emit the code for a basic block */
    void emitBasicBlock(BasicBlock *BB);
    /*! Each block end may require to emit MOVs for further PHIs */
    void emitMovForPHI(BasicBlock *curr, BasicBlock *succ);
    /*! Alocate one or several registers (if vector) for the value */
    INLINE void newRegister(Value *value);
    /*! Return a valid register from an operand (can use LOADI to make one) */
    INLINE ir::Register getRegister(Value *value, uint32_t index = 0);
    /*! Create a new immediate from a constant */
    ir::ImmediateIndex newImmediate(Constant *CPV, uint32_t index = 0);
    /*! Insert a new label index when this is a scalar value */
    INLINE void newLabelIndex(const BasicBlock *bb);
    /*! Inspect the terminator instruction and try to see if we should invert
     *  the value to simplify the code
     */
    INLINE void simplifyTerminator(BasicBlock *bb);
    /*! Helper function to emit loads and stores */
    template <bool isLoad, typename T> void emitLoadOrStore(T &I);

    // Currently supported instructions
#define DECL_VISIT_FN(NAME, TYPE) \
    void regAllocate##NAME(TYPE &I); \
    void emit##NAME(TYPE &I); \
    void visit##NAME(TYPE &I) { \
      if (pass == PASS_EMIT_INSTRUCTIONS) \
        emit##NAME(I); \
      else \
        regAllocate##NAME(I); \
    }
    DECL_VISIT_FN(BinaryOperator, Instruction);
    DECL_VISIT_FN(CastInst, CastInst);
    DECL_VISIT_FN(ReturnInst, ReturnInst);
    DECL_VISIT_FN(LoadInst, LoadInst);
    DECL_VISIT_FN(StoreInst, StoreInst);
    DECL_VISIT_FN(CallInst, CallInst);
    DECL_VISIT_FN(ICmpInst, ICmpInst);
    DECL_VISIT_FN(FCmpInst, FCmpInst);
    DECL_VISIT_FN(InsertElement, InsertElementInst);
    DECL_VISIT_FN(ExtractElement, ExtractElementInst);
    DECL_VISIT_FN(ShuffleVectorInst, ShuffleVectorInst);
    DECL_VISIT_FN(SelectInst, SelectInst);
    DECL_VISIT_FN(BranchInst, BranchInst);
    DECL_VISIT_FN(PHINode, PHINode);
    DECL_VISIT_FN(AllocaInst, AllocaInst);
#undef DECL_VISIT_FN

    // These instructions are not supported at all
    void visitVAArgInst(VAArgInst &I) {NOT_SUPPORTED;}
    void visitSwitchInst(SwitchInst &I) {NOT_SUPPORTED;}
    void visitInvokeInst(InvokeInst &I) {NOT_SUPPORTED;}
    void visitUnwindInst(UnwindInst &I) {NOT_SUPPORTED;}
    void visitResumeInst(ResumeInst &I) {NOT_SUPPORTED;}
    void visitInlineAsm(CallInst &I) {NOT_SUPPORTED;}
    void visitIndirectBrInst(IndirectBrInst &I) {NOT_SUPPORTED;}
    void visitUnreachableInst(UnreachableInst &I) {NOT_SUPPORTED;}
    void visitGetElementPtrInst(GetElementPtrInst &I) {NOT_SUPPORTED;}
    void visitInsertValueInst(InsertValueInst &I) {NOT_SUPPORTED;}
    void visitExtractValueInst(ExtractValueInst &I) {NOT_SUPPORTED;}
    template <bool isLoad, typename T> void visitLoadOrStore(T &I);

    void visitInstruction(Instruction &I) {NOT_SUPPORTED;}
  };

  char GenWriter::ID = 0;

  bool GenWriter::doInitialization(Module &M) {
    FunctionPass::doInitialization(M);

    // Initialize
    TheModule = &M;

    TAsm = new CBEMCAsmInfo();
    TD = new TargetData(&M);
    MRI  = new MCRegisterInfo();
    TCtx = new MCContext(*TAsm, *MRI, NULL);
    Mang = new Mangler(*TCtx, *TD);

    return false;
  }

  template <typename U, typename T>
  static U processConstant(Constant *CPV, T doIt, uint32_t index = 0u)
  {
    if (dyn_cast<ConstantExpr>(CPV))
      GBE_ASSERTM(false, "Unsupported constant expression");
    else if (isa<UndefValue>(CPV) && CPV->getType()->isSingleValueType())
      GBE_ASSERTM(false, "Unsupported constant expression");

    if (ConstantVector *CV = dyn_cast<ConstantVector>(CPV)) {
      const uint32_t elemNum = CV->getNumOperands();
      GBE_ASSERTM(index < elemNum, "Out-of-bound constant vector access");
      CPV = cast<Constant>(CV->getOperand(index));
    }

    // Integers
    if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
      Type* Ty = CI->getType();
      if (Ty == Type::getInt1Ty(CPV->getContext())) {
        const bool b = CI->getZExtValue();
        return doIt(b);
      } else if (Ty == Type::getInt8Ty(CPV->getContext())) {
        const uint8_t u8 = CI->getZExtValue();
        return doIt(u8);
      } else if (Ty == Type::getInt16Ty(CPV->getContext())) {
        const uint16_t u16 = CI->getZExtValue();
        return doIt(u16);
      } else if (Ty == Type::getInt32Ty(CPV->getContext())) {
        const uint32_t u32 = CI->getZExtValue();
        return doIt(u32);
      } else if (Ty == Type::getInt64Ty(CPV->getContext())) {
        const uint64_t u64 = CI->getZExtValue();
        return doIt(u64);
      } else {
        GBE_ASSERTM(false, "Unsupported integer size");
        return doIt(uint64_t(0));
      }
    }

    // Floats and doubles
    switch (CPV->getType()->getTypeID()) {
      case Type::FloatTyID:
      case Type::DoubleTyID:
      {
        ConstantFP *FPC = cast<ConstantFP>(CPV);
        if (FPC->getType() == Type::getFloatTy(CPV->getContext())) {
          const float f32 = FPC->getValueAPF().convertToFloat();
          return doIt(f32);
        } else {
          const double f64 = FPC->getValueAPF().convertToDouble();
          return doIt(f64);
        }
      }
      break;
      default:
        GBE_ASSERTM(false, "Unsupported constant type");
    }
    const uint64_t imm(8);
    return doIt(imm);
  }

  /*! Pfff. I cannot use a lambda, since it is templated. Congratulation c++ */
  struct NewImmediateFunctor
  {
    NewImmediateFunctor(ir::Context &ctx) : ctx(ctx) {}
    template <typename T> ir::ImmediateIndex operator() (const T &t) {
      return ctx.newImmediate(t);
    }
    ir::Context &ctx;
  };

  ir::ImmediateIndex GenWriter::newImmediate(Constant *CPV, uint32_t index) {
    return processConstant<ir::ImmediateIndex>(CPV, NewImmediateFunctor(ctx), index);
  }

  void GenWriter::newRegister(Value *value) {
    auto type = value->getType();
    auto typeID = type->getTypeID();
    switch (typeID) {
      case Type::IntegerTyID:
      case Type::FloatTyID:
      case Type::DoubleTyID:
      case Type::PointerTyID:
        regTranslator.newScalar(value);
        break;
      case Type::VectorTyID:
      {
        auto vectorType = cast<VectorType>(type);
        const uint32_t elemNum = vectorType->getNumElements();
        for (uint32_t elemID = 0; elemID < elemNum; ++elemID)
          regTranslator.newScalar(value, elemID);
        break;
      }
      default: NOT_SUPPORTED;
    };
  }

  ir::Register GenWriter::getRegister(Value *value, uint32_t elemID) {
    Constant *CPV = dyn_cast<Constant>(value);
    if (CPV) {
      GBE_ASSERT(isa<GlobalValue>(CPV) == false);
      const ir::ImmediateIndex immIndex = this->newImmediate(CPV, elemID);
      const ir::Immediate imm = ctx.getImmediate(immIndex);
      const ir::Register reg = ctx.reg(getFamily(imm.type));
      ctx.LOADI(imm.type, reg, immIndex);
      return reg;
    }
    else
      return regTranslator.getScalar(value, elemID);
  }

  void GenWriter::newLabelIndex(const BasicBlock *bb) {
    if (labelMap.find(bb) == labelMap.end()) {
      const ir::LabelIndex label = ctx.label();
      labelMap[bb] = label;
    }
  }

  void GenWriter::simplifyTerminator(BasicBlock *bb) {
    Value *value = --bb->end();
    BranchInst *I = NULL;
    if ((I = dyn_cast<BranchInst>(value)) != NULL) {
      if (I->isConditional() == false)
        return;
      // If the "taken" successor is the next block, we try to invert the
      // branch.
      BasicBlock *succ = I->getSuccessor(0);
      if (llvm::next(Function::iterator(bb)) != Function::iterator(succ))
        return;

      // More than one use is too complicated: we skip it
      Value *condition = I->getCondition();
      if (condition->hasOneUse() == false)
        return;

      // Right now, we only invert comparison instruction
      ICmpInst *CI = dyn_cast<ICmpInst>(condition);
      if (CI != NULL) {
        GBE_ASSERT(conditionSet.find(CI) == conditionSet.end());
        conditionSet.insert(CI);
        return;
      }
    }
  }

  void GenWriter::emitBasicBlock(BasicBlock *BB) {
    GBE_ASSERT(labelMap.find(BB) != labelMap.end());
    ctx.LABEL(labelMap[BB]);
    for (auto II = BB->begin(), E = BB->end(); II != E; ++II) visit(*II);
  }

  void GenWriter::emitMovForPHI(BasicBlock *curr, BasicBlock *succ) {
    for (BasicBlock::iterator I = succ->begin(); isa<PHINode>(I); ++I) {
      PHINode *PN = cast<PHINode>(I);
      Value *IV = PN->getIncomingValueForBlock(curr);
      if (!isa<UndefValue>(IV)) {
        uint32_t elemNum;
        Type *llvmType = PN->getType();
        const ir::Type type = getVectorInfo(ctx, llvmType, PN, elemNum);

        // Emit the MOV required by the PHI function. We do it simple and do not
        // try to optimize them. A next data flow analysis pass on the Gen IR
        // will remove them
        for (uint32_t elemID = 0; elemID < elemNum; ++elemID) {
          const ir::Register dst = this->getRegister(PN, elemID);
          const ir::Register src = this->getRegister(IV, elemID);
          ctx.MOV(type, dst, src);
        }
      }
    }
  }

  void GenWriter::emitFunctionPrototype(Function &F)
  {
    GBE_ASSERTM(F.hasStructRetAttr() == false,
                "Returned value for kernel functions is forbidden");
    // Loop over the arguments and output registers for them
    if (!F.arg_empty()) {
      Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
      const AttrListPtr &PAL = F.getAttributes();

      // Insert a new register for each function argument
      uint32_t argID = 1; // Start at one actually
      for (; I != E; ++I, ++argID) {
        Type *type = I->getType();
        GBE_ASSERT(isScalarType(type) == true);
        const ir::Register reg = regTranslator.newScalar(I);
        if (type->isPointerTy() == false)
          ctx.input(ir::FunctionArgument::VALUE, reg, getTypeByteSize(unit, type));
        else {
          PointerType *pointerType = dyn_cast<PointerType>(type);
          // By value structure
          if (PAL.paramHasAttr(argID, Attribute::ByVal)) {
            Type *pointed = pointerType->getElementType();
            const size_t structSize = getTypeByteSize(unit, pointed);
            ctx.input(ir::FunctionArgument::STRUCTURE, reg, structSize);
          }
          // Regular user provided pointer (global, local or constant)
          else {
            const uint32_t addr = pointerType->getAddressSpace();
            const ir::AddressSpace addrSpace = addressSpaceLLVMToGen(addr);
            const uint32_t ptrSize = getTypeByteSize(unit, type);
              switch (addrSpace) {
              case ir::MEM_GLOBAL:
                ctx.input(ir::FunctionArgument::GLOBAL_POINTER, reg, ptrSize);
              break;
              case ir::MEM_LOCAL:
                ctx.input(ir::FunctionArgument::LOCAL_POINTER, reg, ptrSize);
              break;
              case ir::MEM_CONSTANT:
                ctx.input(ir::FunctionArgument::CONSTANT_POINTER, reg, ptrSize);
              break;
              default: GBE_ASSERT(addrSpace != ir::MEM_PRIVATE);
            }
          }
        }
      }
    }

    // When returning a structure, first input register is the pointer to the
    // structure
    const Type *type = F.getReturnType();
    GBE_ASSERTM(type->isVoidTy() == true,
                "Returned value for kernel functions is forbidden");

#if GBE_DEBUG
    // Variable number of arguments is not supported
    FunctionType *FT = cast<FunctionType>(F.getFunctionType());
    GBE_ASSERT(FT->isVarArg() == false);
#endif /* GBE_DEBUG */
  }

  static inline bool isFPIntBitCast(const Instruction &I) {
    if (!isa<BitCastInst>(I))
      return false;
    Type *SrcTy = I.getOperand(0)->getType();
    Type *DstTy = I.getType();
    return (SrcTy->isFloatingPointTy() && DstTy->isIntegerTy()) ||
           (DstTy->isFloatingPointTy() && SrcTy->isIntegerTy());
  }

  void GenWriter::emitFunction(Function &F)
  {
    switch (F.getCallingConv()) {
      case CallingConv::PTX_Device: // we do not emit device function
        return;
      case CallingConv::PTX_Kernel:
        break;
      default: GBE_ASSERTM(false, "Unsupported calling convention");
    }

    ctx.startFunction(F.getName());
    this->regTranslator.clear();
    this->labelMap.clear();
    this->emitFunctionPrototype(F);

    // Visit all the instructions and emit the IR registers or the value to
    // value mapping when a new register is not needed
    pass = PASS_EMIT_REGISTERS;
    for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I)
      visit(*I);

    // First create all the labels (one per block) ...
    for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
      this->newLabelIndex(BB);

    // Then, for all branch instructions that have conditions, see if we can
    // simplify the code by inverting condition code
    for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
      this->simplifyTerminator(BB);

    // ... then, emit the instructions for all basic blocks
    pass = PASS_EMIT_INSTRUCTIONS;
    for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
      emitBasicBlock(BB);
    ctx.endFunction();
  }

  void GenWriter::regAllocateReturnInst(ReturnInst &I) {}

  void GenWriter::emitReturnInst(ReturnInst &I) {
    const ir::Function &fn = ctx.getFunction();
    GBE_ASSERTM(fn.outputNum() <= 1, "no more than one value can be returned");
    if (fn.outputNum() == 1 && I.getNumOperands() > 0) {
      const ir::Register dst = fn.getOutput(0);
      const ir::Register src = this->getRegister(I.getOperand(0));
      const ir::RegisterFamily family = fn.getRegisterFamily(dst);
      ctx.MOV(ir::getType(family), dst, src);
    }
    ctx.RET();
  }

  void GenWriter::regAllocateBinaryOperator(Instruction &I) {
    this->newRegister(&I);
  }

  void GenWriter::emitBinaryOperator(Instruction &I) {
#if GBE_DEBUG
    GBE_ASSERT(I.getType()->isPointerTy() == false);
    // We accept logical operations on booleans
    switch (I.getOpcode()) {
      case Instruction::And:
      case Instruction::Or:
      case Instruction::Xor:
        break;
      default:
        GBE_ASSERT(I.getType() != Type::getInt1Ty(I.getContext()));
    }
#endif /* GBE_DEBUG */

    // Get the element type for a vector
    uint32_t elemNum;
    const ir::Type type = getVectorInfo(ctx, I.getType(), &I, elemNum);

    // Emit the instructions in a row
    for (uint32_t elemID = 0; elemID < elemNum; ++elemID) {
      const ir::Register dst = this->getRegister(&I, elemID);
      const ir::Register src0 = this->getRegister(I.getOperand(0), elemID);
      const ir::Register src1 = this->getRegister(I.getOperand(1), elemID);

      switch (I.getOpcode()) {
        case Instruction::Add:
        case Instruction::FAdd: ctx.ADD(type, dst, src0, src1); break;
        case Instruction::Sub:
        case Instruction::FSub: ctx.SUB(type, dst, src0, src1); break;
        case Instruction::Mul:
        case Instruction::FMul: ctx.MUL(type, dst, src0, src1); break;
        case Instruction::URem:
        case Instruction::SRem:
        case Instruction::FRem: ctx.REM(type, dst, src0, src1); break;
        case Instruction::UDiv:
        case Instruction::SDiv:
        case Instruction::FDiv: ctx.DIV(type, dst, src0, src1); break;
        case Instruction::And:  ctx.AND(type, dst, src0, src1); break;
        case Instruction::Or:   ctx.OR(type, dst, src0, src1); break;
        case Instruction::Xor:  ctx.XOR(type, dst, src0, src1); break;
        case Instruction::Shl:  ctx.SHL(type, dst, src0, src1); break;
        case Instruction::LShr: ctx.SHR(type, dst, src0, src1); break;
        case Instruction::AShr: ctx.ASR(type, dst, src0, src1); break;
        default: NOT_SUPPORTED;
      }
    }
  }

  void GenWriter::regAllocateICmpInst(ICmpInst &I) {
    this->newRegister(&I);
  }

  static ir::Type makeTypeSigned(const ir::Type &type) {
    if (type == ir::TYPE_U8) return ir::TYPE_S8;
    else if (type == ir::TYPE_U16) return ir::TYPE_S16;
    else if (type == ir::TYPE_U32) return ir::TYPE_S32;
    else if (type == ir::TYPE_U64) return ir::TYPE_S64;
    return type;
  }

  static ir::Type makeTypeUnsigned(const ir::Type &type) {
    if (type == ir::TYPE_S8) return ir::TYPE_U8;
    else if (type == ir::TYPE_S16) return ir::TYPE_U16;
    else if (type == ir::TYPE_S32) return ir::TYPE_U32;
    else if (type == ir::TYPE_S64) return ir::TYPE_U64;
    return type;
  }

  void GenWriter::emitICmpInst(ICmpInst &I) {
    GBE_ASSERT(I.getOperand(0)->getType() != Type::getInt1Ty(I.getContext()));

    // Get the element type and the number of elements
    uint32_t elemNum;
    Type *operandType = I.getOperand(0)->getType();
    const ir::Type type = getVectorInfo(ctx, operandType, &I, elemNum);
    const ir::Type signedType = makeTypeSigned(type);
    const ir::Type unsignedType = makeTypeUnsigned(type);

    // Emit the instructions in a row
    for (uint32_t elemID = 0; elemID < elemNum; ++elemID) {
      const ir::Register dst = this->getRegister(&I, elemID);
      const ir::Register src0 = this->getRegister(I.getOperand(0), elemID);
      const ir::Register src1 = this->getRegister(I.getOperand(1), elemID);

      // We must invert the condition to simplify the branch code
      if (conditionSet.find(&I) != conditionSet.end()) {
        switch (I.getPredicate()) {
          case ICmpInst::ICMP_EQ:  ctx.NE(type, dst, src0, src1); break;
          case ICmpInst::ICMP_NE:  ctx.EQ(type, dst, src0, src1); break;
          case ICmpInst::ICMP_ULE: ctx.GT((unsignedType), dst, src0, src1); break;
          case ICmpInst::ICMP_SLE: ctx.GT(signedType, dst, src0, src1); break;
          case ICmpInst::ICMP_UGE: ctx.LT(unsignedType, dst, src0, src1); break;
          case ICmpInst::ICMP_SGE: ctx.LT(signedType, dst, src0, src1); break;
          case ICmpInst::ICMP_ULT: ctx.GE(unsignedType, dst, src0, src1); break;
          case ICmpInst::ICMP_SLT: ctx.GE(signedType, dst, src0, src1); break;
          case ICmpInst::ICMP_UGT: ctx.LE(unsignedType, dst, src0, src1); break;
          case ICmpInst::ICMP_SGT: ctx.LE(signedType, dst, src0, src1); break;
          default: NOT_SUPPORTED;
        }
      }
      // Nothing special to do
      else {
        switch (I.getPredicate()) {
          case ICmpInst::ICMP_EQ:  ctx.EQ(type, dst, src0, src1); break;
          case ICmpInst::ICMP_NE:  ctx.NE(type, dst, src0, src1); break;
          case ICmpInst::ICMP_ULE: ctx.LE((unsignedType), dst, src0, src1); break;
          case ICmpInst::ICMP_SLE: ctx.LE(signedType, dst, src0, src1); break;
          case ICmpInst::ICMP_UGE: ctx.GE(unsignedType, dst, src0, src1); break;
          case ICmpInst::ICMP_SGE: ctx.GE(signedType, dst, src0, src1); break;
          case ICmpInst::ICMP_ULT: ctx.LT(unsignedType, dst, src0, src1); break;
          case ICmpInst::ICMP_SLT: ctx.LT(signedType, dst, src0, src1); break;
          case ICmpInst::ICMP_UGT: ctx.GT(unsignedType, dst, src0, src1); break;
          case ICmpInst::ICMP_SGT: ctx.GT(signedType, dst, src0, src1); break;
          default: NOT_SUPPORTED;
        }
      }
    }
  }

  void GenWriter::regAllocateFCmpInst(FCmpInst &I) {
    this->newRegister(&I);
  }

  void GenWriter::emitFCmpInst(FCmpInst &I) {

    // Get the element type and the number of elements
    uint32_t elemNum;
    Type *operandType = I.getOperand(0)->getType();
    const ir::Type type = getVectorInfo(ctx, operandType, &I, elemNum);

    // Emit the instructions in a row
    for (uint32_t elemID = 0; elemID < elemNum; ++elemID) {
      const ir::Register dst = this->getRegister(&I, elemID);
      const ir::Register src0 = this->getRegister(I.getOperand(0), elemID);
      const ir::Register src1 = this->getRegister(I.getOperand(1), elemID);

      switch (I.getPredicate()) {
        case ICmpInst::FCMP_OEQ:
        case ICmpInst::FCMP_UEQ: ctx.EQ(type, dst, src0, src1); break;
        case ICmpInst::FCMP_ONE:
        case ICmpInst::FCMP_UNE: ctx.NE(type, dst, src0, src1); break;
        case ICmpInst::FCMP_OLE:
        case ICmpInst::FCMP_ULE: ctx.LE(type, dst, src0, src1); break;
        case ICmpInst::FCMP_OGE:
        case ICmpInst::FCMP_UGE: ctx.GE(type, dst, src0, src1); break;
        case ICmpInst::FCMP_OLT:
        case ICmpInst::FCMP_ULT: ctx.LT(type, dst, src0, src1); break;
        case ICmpInst::FCMP_OGT:
        case ICmpInst::FCMP_UGT: ctx.GT(type, dst, src0, src1); break;
        default: NOT_SUPPORTED;
      }
    }
  }

  void GenWriter::regAllocateCastInst(CastInst &I) {
    Value *dstValue = &I;
    Value *srcValue = I.getOperand(0);
    const auto op = I.getOpcode();

    switch (op)
    {
      // When casting pointer to integers, be aware with integers
      case Instruction::PtrToInt:
      case Instruction::IntToPtr:
      {
        Constant *CPV = dyn_cast<Constant>(srcValue);
        if (CPV == NULL) {
          Type *dstType = dstValue->getType();
          Type *srcType = srcValue->getType();
          GBE_ASSERT(getTypeByteSize(unit, dstType) == getTypeByteSize(unit, srcType));
          regTranslator.newValueProxy(srcValue, dstValue);
        } else
          this->newRegister(dstValue);
      }
      break;
      // Bitcast just forward registers
      case Instruction::BitCast:
      {
        uint32_t elemNum;
        getVectorInfo(ctx, I.getType(), &I, elemNum);
        for (uint32_t elemID = 0; elemID < elemNum; ++elemID)
          regTranslator.newValueProxy(srcValue, dstValue, elemID, elemID);
      }
      break;
      // Various conversion operations -> just allocate registers for them
      case Instruction::FPToUI:
      case Instruction::FPToSI:
      case Instruction::SIToFP:
      case Instruction::UIToFP:
      case Instruction::SExt:
      case Instruction::ZExt:
      case Instruction::FPExt:
      case Instruction::FPTrunc:
      case Instruction::Trunc:
        this->newRegister(&I);
      break;
      default: NOT_SUPPORTED;
    }
  }

  void GenWriter::emitCastInst(CastInst &I) {
    switch (I.getOpcode())
    {
      case Instruction::PtrToInt:
      case Instruction::IntToPtr:
      {
        Value *dstValue = &I;
        Value *srcValue = I.getOperand(0);
        Constant *CPV = dyn_cast<Constant>(srcValue);
        if (CPV != NULL) {
          const ir::ImmediateIndex index = ctx.newImmediate(CPV);
          const ir::Immediate imm = ctx.getImmediate(index);
          const ir::Register reg = this->getRegister(dstValue);
          ctx.LOADI(imm.type, reg, index);
        }
      }
      break;
      case Instruction::BitCast: break; // nothing to emit here
      case Instruction::FPToUI:
      case Instruction::FPToSI:
      case Instruction::SIToFP:
      case Instruction::UIToFP:
      case Instruction::SExt:
      case Instruction::ZExt:
      case Instruction::FPExt:
      case Instruction::FPTrunc:
      case Instruction::Trunc:
      {
        // Get the element type for a vector
        uint32_t elemNum;
        Type *llvmDstType = I.getType();
        Type *llvmSrcType = I.getOperand(0)->getType();
        const ir::Type dstType = getVectorInfo(ctx, llvmDstType, &I, elemNum);
        const ir::Type srcType = getVectorInfo(ctx, llvmSrcType, &I, elemNum);

        // We use a select (0,1) not a convert when the destination is a boolean
        if (srcType == ir::TYPE_BOOL) {
          const ir::RegisterFamily family = getFamily(dstType);
          const ir::ImmediateIndex zero = ctx.newIntegerImmediate(0, dstType);
          const ir::ImmediateIndex one = ctx.newIntegerImmediate(1, dstType);
          const ir::Register zeroReg = ctx.reg(family);
          const ir::Register oneReg = ctx.reg(family);
          ctx.LOADI(dstType, zeroReg, zero);
          ctx.LOADI(dstType, oneReg, one);
          for (uint32_t elemID = 0; elemID < elemNum; ++elemID) {
            const ir::Register dst = this->getRegister(&I, elemID);
            const ir::Register src = this->getRegister(I.getOperand(0), elemID);
            ctx.SEL(dstType, dst, src, oneReg, zeroReg);
          }
        }
        // Use a convert for the other cases
        else {
          for (uint32_t elemID = 0; elemID < elemNum; ++elemID) {
            const ir::Register dst = this->getRegister(&I, elemID);
            const ir::Register src = this->getRegister(I.getOperand(0), elemID);
            ctx.CVT(dstType, srcType, dst, src);
          }
        }
      }
      break;
      default: NOT_SUPPORTED;
    }
  }

  /*! Once again, it is a templated functor. No lambda */
  struct InsertExtractFunctor {
    InsertExtractFunctor(ir::Context &ctx) : ctx(ctx) {}
    template <typename T> ir::Immediate operator() (const T &t) {
      return ir::Immediate(t);
    }
    ir::Context &ctx;
  };

  void GenWriter::regAllocateInsertElement(InsertElementInst &I) {
    Value *modified = I.getOperand(0);
    Value *toInsert = I.getOperand(1);
    Value *index = I.getOperand(2);
    GBE_ASSERTM(!isa<Constant>(modified) || isa<UndefValue>(modified),
                "TODO SUPPORT constant vector for insert");
    Constant *CPV = dyn_cast<Constant>(index);
    GBE_ASSERTM(CPV != NULL, "only constant indices when inserting values");
    auto x = processConstant<ir::Immediate>(CPV, InsertExtractFunctor(ctx));
    GBE_ASSERTM(x.type == ir::TYPE_U32 || x.type == ir::TYPE_S32,
                "Invalid index type for InsertElement");

    // Crash on overrun
    VectorType *vectorType = cast<VectorType>(modified->getType());
    const uint32_t elemNum = vectorType->getNumElements();
    const uint32_t modifiedID = x.data.u32;
    GBE_ASSERTM(modifiedID < elemNum, "Out-of-bound index for InsertElement");

    // Non modified values are just proxies
    for (uint32_t elemID = 0; elemID < elemNum; ++elemID)
      if (elemID != modifiedID)
        regTranslator.newValueProxy(modified, &I, elemID, elemID);

    // If the element to insert is an immediate we will generate a LOADI.
    // Otherwise, the value is just a proxy of the inserted value
    if (dyn_cast<Constant>(toInsert) != NULL) {
      const ir::Type type = getType(ctx, toInsert->getType());
      const ir::Register reg = ctx.reg(getFamily(type));
      regTranslator.insertRegister(reg, &I, modifiedID);
    } else
      regTranslator.newValueProxy(toInsert, &I, 0, modifiedID);
  }

  void GenWriter::emitInsertElement(InsertElementInst &I) {
    // Note that we check everything in regAllocateInsertElement
    Value *toInsert = I.getOperand(1);
    Value *index = I.getOperand(2);

    // If this is not a constant, we just use a proxy
    if (dyn_cast<Constant>(toInsert) == NULL)
      return;

    // We need a LOADI if we insert a immediate
    Constant *indexCPV = dyn_cast<Constant>(index);
    Constant *toInsertCPV = dyn_cast<Constant>(toInsert);
    auto x = processConstant<ir::Immediate>(indexCPV, InsertExtractFunctor(ctx));
    const uint32_t modifiedID = x.data.u32;
    const ir::ImmediateIndex immIndex = this->newImmediate(toInsertCPV);
    const ir::Immediate imm = ctx.getImmediate(immIndex);
    const ir::Register reg = regTranslator.getScalar(&I, modifiedID);
    ctx.LOADI(imm.type, reg, immIndex);
  }

  void GenWriter::regAllocateExtractElement(ExtractElementInst &I) {
    Value *extracted = I.getOperand(0);
    Value *index = I.getOperand(1);
    GBE_ASSERTM(isa<Constant>(extracted) == false,
                "TODO SUPPORT constant vector for extract");
    Constant *CPV = dyn_cast<Constant>(index);
    GBE_ASSERTM(CPV != NULL, "only constant indices when inserting values");
    auto x = processConstant<ir::Immediate>(CPV, InsertExtractFunctor(ctx));
    GBE_ASSERTM(x.type == ir::TYPE_U32 || x.type == ir::TYPE_S32,
                "Invalid index type for InsertElement");

    // Crash on overrun
    VectorType *vectorType = cast<VectorType>(extracted->getType());
    const uint32_t elemNum = vectorType->getNumElements();
    const uint32_t extractedID = x.data.u32;
    GBE_ASSERTM(extractedID < elemNum, "Out-of-bound index for InsertElement");

    // Easy when the vector is not immediate
    regTranslator.newValueProxy(extracted, &I, extractedID, 0);
  }

  void GenWriter::emitExtractElement(ExtractElementInst &I) {
    // TODO -> insert LOADI when the extracted vector is constant
  }

  void GenWriter::regAllocateShuffleVectorInst(ShuffleVectorInst &I) {
    Value *first = I.getOperand(0);
    Value *second = I.getOperand(1);
    GBE_ASSERTM(!isa<Constant>(first) || isa<UndefValue>(first),
                "TODO support constant vector for shuffle");
    GBE_ASSERTM(!isa<Constant>(second) || isa<UndefValue>(second),
                "TODO support constant vector for shuffle");
    VectorType *dstType = cast<VectorType>(I.getType());
    VectorType *srcType = cast<VectorType>(first->getType());
    const uint32_t dstElemNum = dstType->getNumElements();
    const uint32_t srcElemNum = srcType->getNumElements();
    for (uint32_t elemID = 0; elemID < dstElemNum; ++elemID) {
      uint32_t srcID = I.getMaskValue(elemID);
      Value *src = first;
      if (srcID >= srcElemNum) {
        srcID -= srcElemNum;
        src = second;
      }
      regTranslator.newValueProxy(src, &I, srcID, elemID);
    }
  }

  void GenWriter::emitShuffleVectorInst(ShuffleVectorInst &I) {}

  void GenWriter::regAllocateSelectInst(SelectInst &I) {
    this->newRegister(&I);
  }

  void GenWriter::emitSelectInst(SelectInst &I) {
    // Get the element type for a vector
    uint32_t elemNum;
    const ir::Type type = getVectorInfo(ctx, I.getType(), &I, elemNum);

    // Condition can be either a vector or a scalar
    Type *condType = I.getOperand(0)->getType();
    const bool isVectorCond = isa<VectorType>(condType);

    // Emit the instructions in a row
    for (uint32_t elemID = 0; elemID < elemNum; ++elemID) {
      const ir::Register dst = this->getRegister(&I, elemID);
      const uint32_t condID = isVectorCond ? elemID : 0;
      const ir::Register cond = this->getRegister(I.getOperand(0), condID);
      const ir::Register src0 = this->getRegister(I.getOperand(1), elemID);
      const ir::Register src1 = this->getRegister(I.getOperand(2), elemID);
      ctx.SEL(type, dst, cond, src0, src1);
    }
  }

  void GenWriter::regAllocatePHINode(PHINode &I) { this->newRegister(&I); }
  void GenWriter::emitPHINode(PHINode &I) {}

  void GenWriter::regAllocateBranchInst(BranchInst &I) {}

  void GenWriter::emitBranchInst(BranchInst &I) {
    // Emit MOVs if required
    BasicBlock *bb = I.getParent();
    this->emitMovForPHI(bb, I.getSuccessor(0));
    if (I.isConditional())
      this->emitMovForPHI(bb, I.getSuccessor(1));

    // Inconditional branch. Just check that we jump to a block which is not our
    // successor
    if (I.isConditional() == false) {
      BasicBlock *target = I.getSuccessor(0);
      if (llvm::next(Function::iterator(bb)) != Function::iterator(target)) {
        GBE_ASSERT(labelMap.find(target) != labelMap.end());
        const ir::LabelIndex labelIndex = labelMap[target];
        ctx.BRA(labelIndex);
      }
    }
    // The LLVM branch has two targets
    else {
      BasicBlock *taken = NULL, *nonTaken = NULL;
      Value *condition = I.getCondition();

      // We may inverted the branch condition to simplify the branching code
      const bool inverted = conditionSet.find(condition) != conditionSet.end();
      taken = inverted ? I.getSuccessor(1) : I.getSuccessor(0);
      nonTaken = inverted ? I.getSuccessor(0) : I.getSuccessor(1);

      // Get both taken label and predicate register
      GBE_ASSERT(labelMap.find(taken) != labelMap.end());
      const ir::LabelIndex index = labelMap[taken];
      const ir::Register reg = this->getRegister(condition);
      ctx.BRA(index, reg);

      // If non-taken target is the next block, there is nothing to do
      BasicBlock *bb = I.getParent();
      if (llvm::next(Function::iterator(bb)) == Function::iterator(nonTaken))
        return;

      // This is slightly more complicated here. We need to issue one more
      // branch for the non-taken condition.
      GBE_ASSERT(labelMap.find(nonTaken) != labelMap.end());
      const ir::LabelIndex untakenIndex = ctx.label();
      ctx.LABEL(untakenIndex);
      ctx.BRA(labelMap[nonTaken]);
    }
  }

  void GenWriter::regAllocateCallInst(CallInst &I) {
    Value *dst = &I;
    Value *Callee = I.getCalledValue();
    GBE_ASSERT(ctx.getFunction().getProfile() == ir::PROFILE_OCL);
    GBE_ASSERT(isa<InlineAsm>(I.getCalledValue()) == false);
    GBE_ASSERT(I.hasStructRetAttr() == false);

    // We only support a small number of intrinsics right now
    if (Function *F = I.getCalledFunction()) {
      if (F->getIntrinsicID() != 0) {
        switch (F->getIntrinsicID()) {
          case Intrinsic::stacksave:
            this->newRegister(&I);
          break;
          case Intrinsic::stackrestore:
          break;
          default: NOT_IMPLEMENTED;
        }
        return;
      }
    }

    // With OCL there is no side effect for any called functions. So do nothing
    // when there is no returned value
    if (I.getType() == Type::getVoidTy(I.getContext()))
      NOT_SUPPORTED;

    // Get the name of the called function and handle it. We should use a hash
    // map later
    const std::string fnName = Callee->getName();
    if (fnName == "__gen_ocl_get_group_id0")
      regTranslator.newScalarProxy(ir::ocl::groupid0, dst);
    else if (fnName == "__gen_ocl_get_group_id1")
      regTranslator.newScalarProxy(ir::ocl::groupid1, dst);
    else if (fnName == "__gen_ocl_get_group_id2")
      regTranslator.newScalarProxy(ir::ocl::groupid2, dst);
    else if (fnName == "__gen_ocl_get_local_id0")
      regTranslator.newScalarProxy(ir::ocl::lid0, dst);
    else if (fnName == "__gen_ocl_get_local_id1")
      regTranslator.newScalarProxy(ir::ocl::lid1, dst);
    else if (fnName == "__gen_ocl_get_local_id2")
      regTranslator.newScalarProxy(ir::ocl::lid2, dst);
    else if (fnName == "__gen_ocl_get_num_groups0")
      regTranslator.newScalarProxy(ir::ocl::numgroup0, dst);
    else if (fnName == "__gen_ocl_get_num_groups1")
      regTranslator.newScalarProxy(ir::ocl::numgroup1, dst);
    else if (fnName == "__gen_ocl_get_num_groups2")
      regTranslator.newScalarProxy(ir::ocl::numgroup2, dst);
    else if (fnName == "__gen_ocl_get_local_size0")
      regTranslator.newScalarProxy(ir::ocl::lsize0, dst);
    else if (fnName == "__gen_ocl_get_local_size1")
      regTranslator.newScalarProxy(ir::ocl::lsize1, dst);
    else if (fnName == "__gen_ocl_get_local_size2")
      regTranslator.newScalarProxy(ir::ocl::lsize2, dst);
    else if (fnName == "__gen_ocl_get_global_size0")
      regTranslator.newScalarProxy(ir::ocl::gsize0, dst);
    else if (fnName == "__gen_ocl_get_global_size1")
      regTranslator.newScalarProxy(ir::ocl::gsize1, dst);
    else if (fnName == "__gen_ocl_get_global_size2")
      regTranslator.newScalarProxy(ir::ocl::gsize2, dst);
    else if (fnName == "__gen_ocl_get_global_offset0")
      regTranslator.newScalarProxy(ir::ocl::goffset0, dst);
    else if (fnName == "__gen_ocl_get_global_offset1")
      regTranslator.newScalarProxy(ir::ocl::goffset1, dst);
    else if (fnName == "__gen_ocl_get_global_offset2")
      regTranslator.newScalarProxy(ir::ocl::goffset2, dst);
    else
      NOT_SUPPORTED;
  }

  void GenWriter::emitCallInst(CallInst &I) {
    if (Function *F = I.getCalledFunction()) {
      if (F->getIntrinsicID() != 0) {
        const ir::Function &fn = ctx.getFunction();
        switch (F->getIntrinsicID()) {
          case Intrinsic::stacksave:
          {
            const ir::Register dst = this->getRegister(&I);
            const ir::Register src = ir::ocl::stackptr;
            const ir::RegisterFamily family = fn.getRegisterFamily(dst);
            ctx.MOV(ir::getType(family), dst, src);
          }
          break;
          case Intrinsic::stackrestore:
          {
            const ir::Register dst = ir::ocl::stackptr;
            const ir::Register src = this->getRegister(I.getOperand(0));
            const ir::RegisterFamily family = fn.getRegisterFamily(dst);
            ctx.MOV(ir::getType(family), dst, src);
          }
          break;
          default: NOT_IMPLEMENTED;
        }
      }
    }
  }

  struct AllocaSizeFunctor
  {
    AllocaSizeFunctor(ir::Context &ctx) : ctx(ctx) {}
    template <typename T> INLINE uint64_t operator() (const T &t) {
      return uint64_t(t);
    }
    ir::Context &ctx;
  };


  void GenWriter::regAllocateAllocaInst(AllocaInst &I) {
    this->newRegister(&I);
  }
  void GenWriter::emitAllocaInst(AllocaInst &I) {
    Value *src = I.getOperand(0);
    Type *elemType = I.getType()->getElementType();
    ir::ImmediateIndex immIndex;
    bool needMultiply = true;

    // Be aware, we manipulate pointers
    if (ctx.getPointerSize() == ir::POINTER_32_BITS)
      immIndex = ctx.newImmediate(uint32_t(getTypeByteSize(unit, elemType)));
    else
      immIndex = ctx.newImmediate(uint64_t(getTypeByteSize(unit, elemType)));

    // OK, we try to see if we know compile time the size we need to allocate
    if (I.isArrayAllocation() == false) // one element allocated only
      needMultiply = false;
    else {
      Constant *CPV = dyn_cast<Constant>(src);
      if (CPV) {
        const uint64_t elemNum = processConstant<uint64_t>(CPV, AllocaSizeFunctor(ctx));
        ir::Immediate imm = ctx.getImmediate(immIndex);
        imm.data.u64 = ALIGN(imm.data.u64 * elemNum, 4);
        ctx.setImmediate(immIndex, imm);
        needMultiply = false;
      } else {
        // Brutal but cheap way to get arrays aligned on 4 bytes: we just align
        // the element on 4 bytes!
        ir::Immediate imm = ctx.getImmediate(immIndex);
        imm.data.u64 = ALIGN(imm.data.u64, 4);
        ctx.setImmediate(immIndex, imm);
      }
    }

    // Now emit the stream of instructions to get the allocated pointer
    const ir::RegisterFamily pointerFamily = ctx.getPointerFamily();
    const ir::Register dst = this->getRegister(&I);
    const ir::Register stack = ir::ocl::stackptr;
    const ir::Register reg = ctx.reg(pointerFamily);
    const ir::Immediate imm = ctx.getImmediate(immIndex);

    // Easy case, we just increment the stack pointer
    if (needMultiply == false) {
      ctx.LOADI(imm.type, reg, immIndex);
      ctx.ADD(imm.type, dst, stack, reg);
    }
    // Harder case (variable length array) that requires a multiply
    else {
      ctx.LOADI(imm.type, reg, immIndex);
      ctx.MUL(imm.type, reg, this->getRegister(src), reg);
      ctx.ADD(imm.type, dst, stack, reg);
    }
  }

  static INLINE Value *getLoadOrStoreValue(LoadInst &I) {
    return &I;
  }
  static INLINE Value *getLoadOrStoreValue(StoreInst &I) {
    return I.getValueOperand();
  }
  void GenWriter::regAllocateLoadInst(LoadInst &I) {
    this->newRegister(&I);
  }
  void GenWriter::regAllocateStoreInst(StoreInst &I) {}

  template <bool isLoad, typename T>
  INLINE void GenWriter::emitLoadOrStore(T &I)
  {
    GBE_ASSERTM(I.isVolatile() == false, "Volatile pointer is not supported");
    unsigned int llvmSpace = I.getPointerAddressSpace();
    Value *llvmPtr = I.getPointerOperand();
    Value *llvmValues = getLoadOrStoreValue(I);
    Type *llvmType = llvmValues->getType();
    const bool dwAligned = (I.getAlignment() % 4) == 0;
    const ir::AddressSpace addrSpace = addressSpaceLLVMToGen(llvmSpace);
    const ir::Register ptr = this->getRegister(llvmPtr);

    // Scalar is easy. We neednot build register tuples
    if (isScalarType(llvmType) == true) {
      const ir::Type type = getType(ctx, llvmType);
      const ir::Register values = this->getRegister(llvmValues);
      if (isLoad)
        ctx.LOAD(type, ptr, addrSpace, dwAligned, values);
      else
        ctx.STORE(type, ptr, addrSpace, dwAligned, values);
    }
    // A vector type requires to build a tuple
    else {
      VectorType *vectorType = cast<VectorType>(llvmType);
      Type *elemType = vectorType->getElementType();

      // Build the tuple data in the vector
      vector<ir::Register> tupleData; // put registers here
      const uint32_t elemNum = vectorType->getNumElements();
      for (uint32_t elemID = 0; elemID < elemNum; ++elemID) {
        const ir::Register reg = this->getRegister(llvmValues, elemID);
        tupleData.push_back(reg);
      }
      const ir::Tuple tuple = ctx.arrayTuple(&tupleData[0], elemNum);

      // Emit the instruction
      const ir::Type type = getType(ctx, elemType);
      if (isLoad)
        ctx.LOAD(type, tuple, ptr, addrSpace, elemNum, dwAligned);
      else
        ctx.STORE(type, tuple, ptr, addrSpace, elemNum, dwAligned);
    }
  }

  void GenWriter::emitLoadInst(LoadInst &I) {
    this->emitLoadOrStore<true>(I);
  }

  void GenWriter::emitStoreInst(StoreInst &I) {
    this->emitLoadOrStore<false>(I);
  }

  llvm::FunctionPass *createGenPass(ir::Unit &unit) {
    return new GenWriter(unit);
  }
} /* namespace gbe */