forked from llvm-mirror/llvm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConstantFold.cpp
1786 lines (1666 loc) · 76.4 KB
/
ConstantFold.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===- ConstantFold.cpp - LLVM constant folder ----------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements folding of constants for LLVM. This implements the
// (internal) ConstantFold.h interface, which is used by the
// ConstantExpr::get* methods to automatically fold constants when possible.
//
// The current constant folding implementation is implemented in two pieces: the
// template-based folder for simple primitive constants like ConstantInt, and
// the special case hackery that we use to symbolically evaluate expressions
// that use ConstantExprs.
//
//===----------------------------------------------------------------------===//
#include "ConstantFold.h"
#include "llvm/Constants.h"
#include "llvm/Instructions.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Function.h"
#include "llvm/GlobalAlias.h"
#include "llvm/LLVMContext.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/GetElementPtrTypeIterator.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MathExtras.h"
#include <limits>
using namespace llvm;
//===----------------------------------------------------------------------===//
// ConstantFold*Instruction Implementations
//===----------------------------------------------------------------------===//
/// BitCastConstantVector - Convert the specified ConstantVector node to the
/// specified vector type. At this point, we know that the elements of the
/// input vector constant are all simple integer or FP values.
static Constant *BitCastConstantVector(LLVMContext &Context, ConstantVector *CV,
const VectorType *DstTy) {
// If this cast changes element count then we can't handle it here:
// doing so requires endianness information. This should be handled by
// Analysis/ConstantFolding.cpp
unsigned NumElts = DstTy->getNumElements();
if (NumElts != CV->getNumOperands())
return 0;
// Check to verify that all elements of the input are simple.
for (unsigned i = 0; i != NumElts; ++i) {
if (!isa<ConstantInt>(CV->getOperand(i)) &&
!isa<ConstantFP>(CV->getOperand(i)))
return 0;
}
// Bitcast each element now.
std::vector<Constant*> Result;
const Type *DstEltTy = DstTy->getElementType();
for (unsigned i = 0; i != NumElts; ++i)
Result.push_back(ConstantExpr::getBitCast(CV->getOperand(i),
DstEltTy));
return ConstantVector::get(Result);
}
/// This function determines which opcode to use to fold two constant cast
/// expressions together. It uses CastInst::isEliminableCastPair to determine
/// the opcode. Consequently its just a wrapper around that function.
/// @brief Determine if it is valid to fold a cast of a cast
static unsigned
foldConstantCastPair(
unsigned opc, ///< opcode of the second cast constant expression
const ConstantExpr*Op, ///< the first cast constant expression
const Type *DstTy ///< desintation type of the first cast
) {
assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
assert(CastInst::isCast(opc) && "Invalid cast opcode");
// The the types and opcodes for the two Cast constant expressions
const Type *SrcTy = Op->getOperand(0)->getType();
const Type *MidTy = Op->getType();
Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
Instruction::CastOps secondOp = Instruction::CastOps(opc);
// Let CastInst::isEliminableCastPair do the heavy lifting.
return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
Type::getInt64Ty(DstTy->getContext()));
}
static Constant *FoldBitCast(LLVMContext &Context,
Constant *V, const Type *DestTy) {
const Type *SrcTy = V->getType();
if (SrcTy == DestTy)
return V; // no-op cast
// Check to see if we are casting a pointer to an aggregate to a pointer to
// the first element. If so, return the appropriate GEP instruction.
if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
if (const PointerType *DPTy = dyn_cast<PointerType>(DestTy))
if (PTy->getAddressSpace() == DPTy->getAddressSpace()) {
SmallVector<Value*, 8> IdxList;
Value *Zero = Constant::getNullValue(Type::getInt32Ty(Context));
IdxList.push_back(Zero);
const Type *ElTy = PTy->getElementType();
while (ElTy != DPTy->getElementType()) {
if (const StructType *STy = dyn_cast<StructType>(ElTy)) {
if (STy->getNumElements() == 0) break;
ElTy = STy->getElementType(0);
IdxList.push_back(Zero);
} else if (const SequentialType *STy =
dyn_cast<SequentialType>(ElTy)) {
if (isa<PointerType>(ElTy)) break; // Can't index into pointers!
ElTy = STy->getElementType();
IdxList.push_back(Zero);
} else {
break;
}
}
if (ElTy == DPTy->getElementType())
// This GEP is inbounds because all indices are zero.
return ConstantExpr::getInBoundsGetElementPtr(V, &IdxList[0],
IdxList.size());
}
// Handle casts from one vector constant to another. We know that the src
// and dest type have the same size (otherwise its an illegal cast).
if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
if (const VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
"Not cast between same sized vectors!");
SrcTy = NULL;
// First, check for null. Undef is already handled.
if (isa<ConstantAggregateZero>(V))
return Constant::getNullValue(DestTy);
if (ConstantVector *CV = dyn_cast<ConstantVector>(V))
return BitCastConstantVector(Context, CV, DestPTy);
}
// Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
// This allows for other simplifications (although some of them
// can only be handled by Analysis/ConstantFolding.cpp).
if (isa<ConstantInt>(V) || isa<ConstantFP>(V))
return ConstantExpr::getBitCast(
ConstantVector::get(&V, 1), DestPTy);
}
// Finally, implement bitcast folding now. The code below doesn't handle
// bitcast right.
if (isa<ConstantPointerNull>(V)) // ptr->ptr cast.
return ConstantPointerNull::get(cast<PointerType>(DestTy));
// Handle integral constant input.
if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
if (DestTy->isInteger())
// Integral -> Integral. This is a no-op because the bit widths must
// be the same. Consequently, we just fold to V.
return V;
if (DestTy->isFloatingPoint())
return ConstantFP::get(Context, APFloat(CI->getValue(),
DestTy != Type::getPPC_FP128Ty(Context)));
// Otherwise, can't fold this (vector?)
return 0;
}
// Handle ConstantFP input.
if (const ConstantFP *FP = dyn_cast<ConstantFP>(V))
// FP -> Integral.
return ConstantInt::get(Context, FP->getValueAPF().bitcastToAPInt());
return 0;
}
Constant *llvm::ConstantFoldCastInstruction(LLVMContext &Context,
unsigned opc, const Constant *V,
const Type *DestTy) {
if (isa<UndefValue>(V)) {
// zext(undef) = 0, because the top bits will be zero.
// sext(undef) = 0, because the top bits will all be the same.
// [us]itofp(undef) = 0, because the result value is bounded.
if (opc == Instruction::ZExt || opc == Instruction::SExt ||
opc == Instruction::UIToFP || opc == Instruction::SIToFP)
return Constant::getNullValue(DestTy);
return UndefValue::get(DestTy);
}
// No compile-time operations on this type yet.
if (V->getType() == Type::getPPC_FP128Ty(Context) || DestTy == Type::getPPC_FP128Ty(Context))
return 0;
// If the cast operand is a constant expression, there's a few things we can
// do to try to simplify it.
if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
if (CE->isCast()) {
// Try hard to fold cast of cast because they are often eliminable.
if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
} else if (CE->getOpcode() == Instruction::GetElementPtr) {
// If all of the indexes in the GEP are null values, there is no pointer
// adjustment going on. We might as well cast the source pointer.
bool isAllNull = true;
for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
if (!CE->getOperand(i)->isNullValue()) {
isAllNull = false;
break;
}
if (isAllNull)
// This is casting one pointer type to another, always BitCast
return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
}
}
// If the cast operand is a constant vector, perform the cast by
// operating on each element. In the cast of bitcasts, the element
// count may be mismatched; don't attempt to handle that here.
if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
if (isa<VectorType>(DestTy) &&
cast<VectorType>(DestTy)->getNumElements() ==
CV->getType()->getNumElements()) {
std::vector<Constant*> res;
const VectorType *DestVecTy = cast<VectorType>(DestTy);
const Type *DstEltTy = DestVecTy->getElementType();
for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
res.push_back(ConstantExpr::getCast(opc,
CV->getOperand(i), DstEltTy));
return ConstantVector::get(DestVecTy, res);
}
// We actually have to do a cast now. Perform the cast according to the
// opcode specified.
switch (opc) {
case Instruction::FPTrunc:
case Instruction::FPExt:
if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
bool ignored;
APFloat Val = FPC->getValueAPF();
Val.convert(DestTy == Type::getFloatTy(Context) ? APFloat::IEEEsingle :
DestTy == Type::getDoubleTy(Context) ? APFloat::IEEEdouble :
DestTy == Type::getX86_FP80Ty(Context) ? APFloat::x87DoubleExtended :
DestTy == Type::getFP128Ty(Context) ? APFloat::IEEEquad :
APFloat::Bogus,
APFloat::rmNearestTiesToEven, &ignored);
return ConstantFP::get(Context, Val);
}
return 0; // Can't fold.
case Instruction::FPToUI:
case Instruction::FPToSI:
if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
const APFloat &V = FPC->getValueAPF();
bool ignored;
uint64_t x[2];
uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
(void) V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
APFloat::rmTowardZero, &ignored);
APInt Val(DestBitWidth, 2, x);
return ConstantInt::get(Context, Val);
}
return 0; // Can't fold.
case Instruction::IntToPtr: //always treated as unsigned
if (V->isNullValue()) // Is it an integral null value?
return ConstantPointerNull::get(cast<PointerType>(DestTy));
return 0; // Other pointer types cannot be casted
case Instruction::PtrToInt: // always treated as unsigned
if (V->isNullValue()) // is it a null pointer value?
return ConstantInt::get(DestTy, 0);
return 0; // Other pointer types cannot be casted
case Instruction::UIToFP:
case Instruction::SIToFP:
if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
APInt api = CI->getValue();
const uint64_t zero[] = {0, 0};
APFloat apf = APFloat(APInt(DestTy->getPrimitiveSizeInBits(),
2, zero));
(void)apf.convertFromAPInt(api,
opc==Instruction::SIToFP,
APFloat::rmNearestTiesToEven);
return ConstantFP::get(Context, apf);
}
return 0;
case Instruction::ZExt:
if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
APInt Result(CI->getValue());
Result.zext(BitWidth);
return ConstantInt::get(Context, Result);
}
return 0;
case Instruction::SExt:
if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
APInt Result(CI->getValue());
Result.sext(BitWidth);
return ConstantInt::get(Context, Result);
}
return 0;
case Instruction::Trunc:
if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
APInt Result(CI->getValue());
Result.trunc(BitWidth);
return ConstantInt::get(Context, Result);
}
return 0;
case Instruction::BitCast:
return FoldBitCast(Context, const_cast<Constant*>(V), DestTy);
default:
assert(!"Invalid CE CastInst opcode");
break;
}
llvm_unreachable("Failed to cast constant expression");
return 0;
}
Constant *llvm::ConstantFoldSelectInstruction(LLVMContext&,
const Constant *Cond,
const Constant *V1,
const Constant *V2) {
if (const ConstantInt *CB = dyn_cast<ConstantInt>(Cond))
return const_cast<Constant*>(CB->getZExtValue() ? V1 : V2);
if (isa<UndefValue>(V1)) return const_cast<Constant*>(V2);
if (isa<UndefValue>(V2)) return const_cast<Constant*>(V1);
if (isa<UndefValue>(Cond)) return const_cast<Constant*>(V1);
if (V1 == V2) return const_cast<Constant*>(V1);
return 0;
}
Constant *llvm::ConstantFoldExtractElementInstruction(LLVMContext &Context,
const Constant *Val,
const Constant *Idx) {
if (isa<UndefValue>(Val)) // ee(undef, x) -> undef
return UndefValue::get(cast<VectorType>(Val->getType())->getElementType());
if (Val->isNullValue()) // ee(zero, x) -> zero
return Constant::getNullValue(
cast<VectorType>(Val->getType())->getElementType());
if (const ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
return CVal->getOperand(CIdx->getZExtValue());
} else if (isa<UndefValue>(Idx)) {
// ee({w,x,y,z}, undef) -> w (an arbitrary value).
return CVal->getOperand(0);
}
}
return 0;
}
Constant *llvm::ConstantFoldInsertElementInstruction(LLVMContext &Context,
const Constant *Val,
const Constant *Elt,
const Constant *Idx) {
const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
if (!CIdx) return 0;
APInt idxVal = CIdx->getValue();
if (isa<UndefValue>(Val)) {
// Insertion of scalar constant into vector undef
// Optimize away insertion of undef
if (isa<UndefValue>(Elt))
return const_cast<Constant*>(Val);
// Otherwise break the aggregate undef into multiple undefs and do
// the insertion
unsigned numOps =
cast<VectorType>(Val->getType())->getNumElements();
std::vector<Constant*> Ops;
Ops.reserve(numOps);
for (unsigned i = 0; i < numOps; ++i) {
const Constant *Op =
(idxVal == i) ? Elt : UndefValue::get(Elt->getType());
Ops.push_back(const_cast<Constant*>(Op));
}
return ConstantVector::get(Ops);
}
if (isa<ConstantAggregateZero>(Val)) {
// Insertion of scalar constant into vector aggregate zero
// Optimize away insertion of zero
if (Elt->isNullValue())
return const_cast<Constant*>(Val);
// Otherwise break the aggregate zero into multiple zeros and do
// the insertion
unsigned numOps =
cast<VectorType>(Val->getType())->getNumElements();
std::vector<Constant*> Ops;
Ops.reserve(numOps);
for (unsigned i = 0; i < numOps; ++i) {
const Constant *Op =
(idxVal == i) ? Elt : Constant::getNullValue(Elt->getType());
Ops.push_back(const_cast<Constant*>(Op));
}
return ConstantVector::get(Ops);
}
if (const ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
// Insertion of scalar constant into vector constant
std::vector<Constant*> Ops;
Ops.reserve(CVal->getNumOperands());
for (unsigned i = 0; i < CVal->getNumOperands(); ++i) {
const Constant *Op =
(idxVal == i) ? Elt : cast<Constant>(CVal->getOperand(i));
Ops.push_back(const_cast<Constant*>(Op));
}
return ConstantVector::get(Ops);
}
return 0;
}
/// GetVectorElement - If C is a ConstantVector, ConstantAggregateZero or Undef
/// return the specified element value. Otherwise return null.
static Constant *GetVectorElement(LLVMContext &Context, const Constant *C,
unsigned EltNo) {
if (const ConstantVector *CV = dyn_cast<ConstantVector>(C))
return CV->getOperand(EltNo);
const Type *EltTy = cast<VectorType>(C->getType())->getElementType();
if (isa<ConstantAggregateZero>(C))
return Constant::getNullValue(EltTy);
if (isa<UndefValue>(C))
return UndefValue::get(EltTy);
return 0;
}
Constant *llvm::ConstantFoldShuffleVectorInstruction(LLVMContext &Context,
const Constant *V1,
const Constant *V2,
const Constant *Mask) {
// Undefined shuffle mask -> undefined value.
if (isa<UndefValue>(Mask)) return UndefValue::get(V1->getType());
unsigned MaskNumElts = cast<VectorType>(Mask->getType())->getNumElements();
unsigned SrcNumElts = cast<VectorType>(V1->getType())->getNumElements();
const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
// Loop over the shuffle mask, evaluating each element.
SmallVector<Constant*, 32> Result;
for (unsigned i = 0; i != MaskNumElts; ++i) {
Constant *InElt = GetVectorElement(Context, Mask, i);
if (InElt == 0) return 0;
if (isa<UndefValue>(InElt))
InElt = UndefValue::get(EltTy);
else if (ConstantInt *CI = dyn_cast<ConstantInt>(InElt)) {
unsigned Elt = CI->getZExtValue();
if (Elt >= SrcNumElts*2)
InElt = UndefValue::get(EltTy);
else if (Elt >= SrcNumElts)
InElt = GetVectorElement(Context, V2, Elt - SrcNumElts);
else
InElt = GetVectorElement(Context, V1, Elt);
if (InElt == 0) return 0;
} else {
// Unknown value.
return 0;
}
Result.push_back(InElt);
}
return ConstantVector::get(&Result[0], Result.size());
}
Constant *llvm::ConstantFoldExtractValueInstruction(LLVMContext &Context,
const Constant *Agg,
const unsigned *Idxs,
unsigned NumIdx) {
// Base case: no indices, so return the entire value.
if (NumIdx == 0)
return const_cast<Constant *>(Agg);
if (isa<UndefValue>(Agg)) // ev(undef, x) -> undef
return UndefValue::get(ExtractValueInst::getIndexedType(Agg->getType(),
Idxs,
Idxs + NumIdx));
if (isa<ConstantAggregateZero>(Agg)) // ev(0, x) -> 0
return
Constant::getNullValue(ExtractValueInst::getIndexedType(Agg->getType(),
Idxs,
Idxs + NumIdx));
// Otherwise recurse.
return ConstantFoldExtractValueInstruction(Context, Agg->getOperand(*Idxs),
Idxs+1, NumIdx-1);
}
Constant *llvm::ConstantFoldInsertValueInstruction(LLVMContext &Context,
const Constant *Agg,
const Constant *Val,
const unsigned *Idxs,
unsigned NumIdx) {
// Base case: no indices, so replace the entire value.
if (NumIdx == 0)
return const_cast<Constant *>(Val);
if (isa<UndefValue>(Agg)) {
// Insertion of constant into aggregate undef
// Optimize away insertion of undef
if (isa<UndefValue>(Val))
return const_cast<Constant*>(Agg);
// Otherwise break the aggregate undef into multiple undefs and do
// the insertion
const CompositeType *AggTy = cast<CompositeType>(Agg->getType());
unsigned numOps;
if (const ArrayType *AR = dyn_cast<ArrayType>(AggTy))
numOps = AR->getNumElements();
else
numOps = cast<StructType>(AggTy)->getNumElements();
std::vector<Constant*> Ops(numOps);
for (unsigned i = 0; i < numOps; ++i) {
const Type *MemberTy = AggTy->getTypeAtIndex(i);
const Constant *Op =
(*Idxs == i) ?
ConstantFoldInsertValueInstruction(Context, UndefValue::get(MemberTy),
Val, Idxs+1, NumIdx-1) :
UndefValue::get(MemberTy);
Ops[i] = const_cast<Constant*>(Op);
}
if (isa<StructType>(AggTy))
return ConstantStruct::get(Context, Ops);
else
return ConstantArray::get(cast<ArrayType>(AggTy), Ops);
}
if (isa<ConstantAggregateZero>(Agg)) {
// Insertion of constant into aggregate zero
// Optimize away insertion of zero
if (Val->isNullValue())
return const_cast<Constant*>(Agg);
// Otherwise break the aggregate zero into multiple zeros and do
// the insertion
const CompositeType *AggTy = cast<CompositeType>(Agg->getType());
unsigned numOps;
if (const ArrayType *AR = dyn_cast<ArrayType>(AggTy))
numOps = AR->getNumElements();
else
numOps = cast<StructType>(AggTy)->getNumElements();
std::vector<Constant*> Ops(numOps);
for (unsigned i = 0; i < numOps; ++i) {
const Type *MemberTy = AggTy->getTypeAtIndex(i);
const Constant *Op =
(*Idxs == i) ?
ConstantFoldInsertValueInstruction(Context,
Constant::getNullValue(MemberTy),
Val, Idxs+1, NumIdx-1) :
Constant::getNullValue(MemberTy);
Ops[i] = const_cast<Constant*>(Op);
}
if (isa<StructType>(AggTy))
return ConstantStruct::get(Context, Ops);
else
return ConstantArray::get(cast<ArrayType>(AggTy), Ops);
}
if (isa<ConstantStruct>(Agg) || isa<ConstantArray>(Agg)) {
// Insertion of constant into aggregate constant
std::vector<Constant*> Ops(Agg->getNumOperands());
for (unsigned i = 0; i < Agg->getNumOperands(); ++i) {
const Constant *Op =
(*Idxs == i) ?
ConstantFoldInsertValueInstruction(Context, Agg->getOperand(i),
Val, Idxs+1, NumIdx-1) :
Agg->getOperand(i);
Ops[i] = const_cast<Constant*>(Op);
}
Constant *C;
if (isa<StructType>(Agg->getType()))
C = ConstantStruct::get(Context, Ops);
else
C = ConstantArray::get(cast<ArrayType>(Agg->getType()), Ops);
return C;
}
return 0;
}
Constant *llvm::ConstantFoldBinaryInstruction(LLVMContext &Context,
unsigned Opcode,
const Constant *C1,
const Constant *C2) {
// No compile-time operations on this type yet.
if (C1->getType() == Type::getPPC_FP128Ty(Context))
return 0;
// Handle UndefValue up front
if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
switch (Opcode) {
case Instruction::Xor:
if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
// Handle undef ^ undef -> 0 special case. This is a common
// idiom (misuse).
return Constant::getNullValue(C1->getType());
// Fallthrough
case Instruction::Add:
case Instruction::Sub:
return UndefValue::get(C1->getType());
case Instruction::Mul:
case Instruction::And:
return Constant::getNullValue(C1->getType());
case Instruction::UDiv:
case Instruction::SDiv:
case Instruction::URem:
case Instruction::SRem:
if (!isa<UndefValue>(C2)) // undef / X -> 0
return Constant::getNullValue(C1->getType());
return const_cast<Constant*>(C2); // X / undef -> undef
case Instruction::Or: // X | undef -> -1
if (const VectorType *PTy = dyn_cast<VectorType>(C1->getType()))
return Constant::getAllOnesValue(PTy);
return Constant::getAllOnesValue(C1->getType());
case Instruction::LShr:
if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
return const_cast<Constant*>(C1); // undef lshr undef -> undef
return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
// undef lshr X -> 0
case Instruction::AShr:
if (!isa<UndefValue>(C2))
return const_cast<Constant*>(C1); // undef ashr X --> undef
else if (isa<UndefValue>(C1))
return const_cast<Constant*>(C1); // undef ashr undef -> undef
else
return const_cast<Constant*>(C1); // X ashr undef --> X
case Instruction::Shl:
// undef << X -> 0 or X << undef -> 0
return Constant::getNullValue(C1->getType());
}
}
// Handle simplifications when the RHS is a constant int.
if (const ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
switch (Opcode) {
case Instruction::Add:
if (CI2->equalsInt(0)) return const_cast<Constant*>(C1); // X + 0 == X
break;
case Instruction::Sub:
if (CI2->equalsInt(0)) return const_cast<Constant*>(C1); // X - 0 == X
break;
case Instruction::Mul:
if (CI2->equalsInt(0)) return const_cast<Constant*>(C2); // X * 0 == 0
if (CI2->equalsInt(1))
return const_cast<Constant*>(C1); // X * 1 == X
break;
case Instruction::UDiv:
case Instruction::SDiv:
if (CI2->equalsInt(1))
return const_cast<Constant*>(C1); // X / 1 == X
if (CI2->equalsInt(0))
return UndefValue::get(CI2->getType()); // X / 0 == undef
break;
case Instruction::URem:
case Instruction::SRem:
if (CI2->equalsInt(1))
return Constant::getNullValue(CI2->getType()); // X % 1 == 0
if (CI2->equalsInt(0))
return UndefValue::get(CI2->getType()); // X % 0 == undef
break;
case Instruction::And:
if (CI2->isZero()) return const_cast<Constant*>(C2); // X & 0 == 0
if (CI2->isAllOnesValue())
return const_cast<Constant*>(C1); // X & -1 == X
if (const ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
// (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
if (CE1->getOpcode() == Instruction::ZExt) {
unsigned DstWidth = CI2->getType()->getBitWidth();
unsigned SrcWidth =
CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
return const_cast<Constant*>(C1);
}
// If and'ing the address of a global with a constant, fold it.
if (CE1->getOpcode() == Instruction::PtrToInt &&
isa<GlobalValue>(CE1->getOperand(0))) {
GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
// Functions are at least 4-byte aligned.
unsigned GVAlign = GV->getAlignment();
if (isa<Function>(GV))
GVAlign = std::max(GVAlign, 4U);
if (GVAlign > 1) {
unsigned DstWidth = CI2->getType()->getBitWidth();
unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign));
APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
// If checking bits we know are clear, return zero.
if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
return Constant::getNullValue(CI2->getType());
}
}
}
break;
case Instruction::Or:
if (CI2->equalsInt(0)) return const_cast<Constant*>(C1); // X | 0 == X
if (CI2->isAllOnesValue())
return const_cast<Constant*>(C2); // X | -1 == -1
break;
case Instruction::Xor:
if (CI2->equalsInt(0)) return const_cast<Constant*>(C1); // X ^ 0 == X
break;
case Instruction::AShr:
// ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
if (const ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
if (CE1->getOpcode() == Instruction::ZExt) // Top bits known zero.
return ConstantExpr::getLShr(const_cast<Constant*>(C1),
const_cast<Constant*>(C2));
break;
}
}
// At this point we know neither constant is an UndefValue.
if (const ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
if (const ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
using namespace APIntOps;
const APInt &C1V = CI1->getValue();
const APInt &C2V = CI2->getValue();
switch (Opcode) {
default:
break;
case Instruction::Add:
return ConstantInt::get(Context, C1V + C2V);
case Instruction::Sub:
return ConstantInt::get(Context, C1V - C2V);
case Instruction::Mul:
return ConstantInt::get(Context, C1V * C2V);
case Instruction::UDiv:
assert(!CI2->isNullValue() && "Div by zero handled above");
return ConstantInt::get(Context, C1V.udiv(C2V));
case Instruction::SDiv:
assert(!CI2->isNullValue() && "Div by zero handled above");
if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
return UndefValue::get(CI1->getType()); // MIN_INT / -1 -> undef
return ConstantInt::get(Context, C1V.sdiv(C2V));
case Instruction::URem:
assert(!CI2->isNullValue() && "Div by zero handled above");
return ConstantInt::get(Context, C1V.urem(C2V));
case Instruction::SRem:
assert(!CI2->isNullValue() && "Div by zero handled above");
if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
return UndefValue::get(CI1->getType()); // MIN_INT % -1 -> undef
return ConstantInt::get(Context, C1V.srem(C2V));
case Instruction::And:
return ConstantInt::get(Context, C1V & C2V);
case Instruction::Or:
return ConstantInt::get(Context, C1V | C2V);
case Instruction::Xor:
return ConstantInt::get(Context, C1V ^ C2V);
case Instruction::Shl: {
uint32_t shiftAmt = C2V.getZExtValue();
if (shiftAmt < C1V.getBitWidth())
return ConstantInt::get(Context, C1V.shl(shiftAmt));
else
return UndefValue::get(C1->getType()); // too big shift is undef
}
case Instruction::LShr: {
uint32_t shiftAmt = C2V.getZExtValue();
if (shiftAmt < C1V.getBitWidth())
return ConstantInt::get(Context, C1V.lshr(shiftAmt));
else
return UndefValue::get(C1->getType()); // too big shift is undef
}
case Instruction::AShr: {
uint32_t shiftAmt = C2V.getZExtValue();
if (shiftAmt < C1V.getBitWidth())
return ConstantInt::get(Context, C1V.ashr(shiftAmt));
else
return UndefValue::get(C1->getType()); // too big shift is undef
}
}
}
switch (Opcode) {
case Instruction::SDiv:
case Instruction::UDiv:
case Instruction::URem:
case Instruction::SRem:
case Instruction::LShr:
case Instruction::AShr:
case Instruction::Shl:
if (CI1->equalsInt(0)) return const_cast<Constant*>(C1);
break;
default:
break;
}
} else if (const ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
if (const ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
APFloat C1V = CFP1->getValueAPF();
APFloat C2V = CFP2->getValueAPF();
APFloat C3V = C1V; // copy for modification
switch (Opcode) {
default:
break;
case Instruction::FAdd:
(void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
return ConstantFP::get(Context, C3V);
case Instruction::FSub:
(void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
return ConstantFP::get(Context, C3V);
case Instruction::FMul:
(void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
return ConstantFP::get(Context, C3V);
case Instruction::FDiv:
(void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
return ConstantFP::get(Context, C3V);
case Instruction::FRem:
(void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
return ConstantFP::get(Context, C3V);
}
}
} else if (const VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
const ConstantVector *CP1 = dyn_cast<ConstantVector>(C1);
const ConstantVector *CP2 = dyn_cast<ConstantVector>(C2);
if ((CP1 != NULL || isa<ConstantAggregateZero>(C1)) &&
(CP2 != NULL || isa<ConstantAggregateZero>(C2))) {
std::vector<Constant*> Res;
const Type* EltTy = VTy->getElementType();
const Constant *C1 = 0;
const Constant *C2 = 0;
switch (Opcode) {
default:
break;
case Instruction::Add:
for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Res.push_back(ConstantExpr::getAdd(const_cast<Constant*>(C1),
const_cast<Constant*>(C2)));
}
return ConstantVector::get(Res);
case Instruction::FAdd:
for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Res.push_back(ConstantExpr::getFAdd(const_cast<Constant*>(C1),
const_cast<Constant*>(C2)));
}
return ConstantVector::get(Res);
case Instruction::Sub:
for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Res.push_back(ConstantExpr::getSub(const_cast<Constant*>(C1),
const_cast<Constant*>(C2)));
}
return ConstantVector::get(Res);
case Instruction::FSub:
for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Res.push_back(ConstantExpr::getFSub(const_cast<Constant*>(C1),
const_cast<Constant*>(C2)));
}
return ConstantVector::get(Res);
case Instruction::Mul:
for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Res.push_back(ConstantExpr::getMul(const_cast<Constant*>(C1),
const_cast<Constant*>(C2)));
}
return ConstantVector::get(Res);
case Instruction::FMul:
for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Res.push_back(ConstantExpr::getFMul(const_cast<Constant*>(C1),
const_cast<Constant*>(C2)));
}
return ConstantVector::get(Res);
case Instruction::UDiv:
for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Res.push_back(ConstantExpr::getUDiv(const_cast<Constant*>(C1),
const_cast<Constant*>(C2)));
}
return ConstantVector::get(Res);
case Instruction::SDiv:
for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Res.push_back(ConstantExpr::getSDiv(const_cast<Constant*>(C1),
const_cast<Constant*>(C2)));
}
return ConstantVector::get(Res);
case Instruction::FDiv:
for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Res.push_back(ConstantExpr::getFDiv(const_cast<Constant*>(C1),
const_cast<Constant*>(C2)));
}
return ConstantVector::get(Res);
case Instruction::URem:
for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Res.push_back(ConstantExpr::getURem(const_cast<Constant*>(C1),
const_cast<Constant*>(C2)));
}
return ConstantVector::get(Res);
case Instruction::SRem:
for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Res.push_back(ConstantExpr::getSRem(const_cast<Constant*>(C1),
const_cast<Constant*>(C2)));
}
return ConstantVector::get(Res);
case Instruction::FRem:
for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Res.push_back(ConstantExpr::getFRem(const_cast<Constant*>(C1),
const_cast<Constant*>(C2)));
}
return ConstantVector::get(Res);
case Instruction::And:
for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Res.push_back(ConstantExpr::getAnd(const_cast<Constant*>(C1),
const_cast<Constant*>(C2)));
}
return ConstantVector::get(Res);
case Instruction::Or:
for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Res.push_back(ConstantExpr::getOr(const_cast<Constant*>(C1),
const_cast<Constant*>(C2)));
}
return ConstantVector::get(Res);
case Instruction::Xor:
for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Res.push_back(ConstantExpr::getXor(const_cast<Constant*>(C1),
const_cast<Constant*>(C2)));
}
return ConstantVector::get(Res);
case Instruction::LShr:
for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Res.push_back(ConstantExpr::getLShr(const_cast<Constant*>(C1),
const_cast<Constant*>(C2)));
}
return ConstantVector::get(Res);
case Instruction::AShr:
for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Res.push_back(ConstantExpr::getAShr(const_cast<Constant*>(C1),
const_cast<Constant*>(C2)));
}
return ConstantVector::get(Res);
case Instruction::Shl:
for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Res.push_back(ConstantExpr::getShl(const_cast<Constant*>(C1),
const_cast<Constant*>(C2)));
}
return ConstantVector::get(Res);
}
}
}
if (isa<ConstantExpr>(C1)) {
// There are many possible foldings we could do here. We should probably
// at least fold add of a pointer with an integer into the appropriate
// getelementptr. This will improve alias analysis a bit.
} else if (isa<ConstantExpr>(C2)) {
// If C2 is a constant expr and C1 isn't, flop them around and fold the
// other way if possible.
switch (Opcode) {
case Instruction::Add:
case Instruction::FAdd:
case Instruction::Mul:
case Instruction::FMul:
case Instruction::And:
case Instruction::Or:
case Instruction::Xor:
// No change of opcode required.
return ConstantFoldBinaryInstruction(Context, Opcode, C2, C1);
case Instruction::Shl:
case Instruction::LShr:
case Instruction::AShr:
case Instruction::Sub:
case Instruction::FSub:
case Instruction::SDiv:
case Instruction::UDiv:
case Instruction::FDiv: