1 //===- llvm/unittest/IR/ConstantsTest.cpp - Constants unit tests ----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/IR/Constants.h"
10 #include "llvm-c/Core.h"
11 #include "llvm/AsmParser/Parser.h"
12 #include "llvm/IR/ConstantFold.h"
13 #include "llvm/IR/DerivedTypes.h"
14 #include "llvm/IR/InstrTypes.h"
15 #include "llvm/IR/Instruction.h"
16 #include "llvm/IR/LLVMContext.h"
17 #include "llvm/IR/Module.h"
18 #include "llvm/Support/SourceMgr.h"
19 #include "gtest/gtest.h"
20 
21 namespace llvm {
22 namespace {
23 
24 TEST(ConstantsTest, Integer_i1) {
25   LLVMContext Context;
26   IntegerType *Int1 = IntegerType::get(Context, 1);
27   Constant *One = ConstantInt::get(Int1, 1, true);
28   Constant *Zero = ConstantInt::get(Int1, 0);
29   Constant *NegOne = ConstantInt::get(Int1, static_cast<uint64_t>(-1), true);
30   EXPECT_EQ(NegOne, ConstantInt::getSigned(Int1, -1));
31   Constant *Poison = PoisonValue::get(Int1);
32 
33   // Input:  @b = constant i1 add(i1 1 , i1 1)
34   // Output: @b = constant i1 false
35   EXPECT_EQ(Zero, ConstantExpr::getAdd(One, One));
36 
37   // @c = constant i1 add(i1 -1, i1 1)
38   // @c = constant i1 false
39   EXPECT_EQ(Zero, ConstantExpr::getAdd(NegOne, One));
40 
41   // @d = constant i1 add(i1 -1, i1 -1)
42   // @d = constant i1 false
43   EXPECT_EQ(Zero, ConstantExpr::getAdd(NegOne, NegOne));
44 
45   // @e = constant i1 sub(i1 -1, i1 1)
46   // @e = constant i1 false
47   EXPECT_EQ(Zero, ConstantExpr::getSub(NegOne, One));
48 
49   // @f = constant i1 sub(i1 1 , i1 -1)
50   // @f = constant i1 false
51   EXPECT_EQ(Zero, ConstantExpr::getSub(One, NegOne));
52 
53   // @g = constant i1 sub(i1 1 , i1 1)
54   // @g = constant i1 false
55   EXPECT_EQ(Zero, ConstantExpr::getSub(One, One));
56 
57   // @h = constant i1 shl(i1 1 , i1 1)  ; poison
58   // @h = constant i1 poison
59   EXPECT_EQ(Poison, ConstantExpr::getShl(One, One));
60 
61   // @i = constant i1 shl(i1 1 , i1 0)
62   // @i = constant i1 true
63   EXPECT_EQ(One, ConstantExpr::getShl(One, Zero));
64 
65   // @j = constant i1 lshr(i1 1, i1 1)  ; poison
66   // @j = constant i1 poison
67   EXPECT_EQ(Poison, ConstantExpr::getLShr(One, One));
68 
69   // @m = constant i1 ashr(i1 1, i1 1)  ; poison
70   // @m = constant i1 poison
71   EXPECT_EQ(Poison, ConstantExpr::getAShr(One, One));
72 
73   // @n = constant i1 mul(i1 -1, i1 1)
74   // @n = constant i1 true
75   EXPECT_EQ(One, ConstantExpr::getMul(NegOne, One));
76 
77   // @o = constant i1 sdiv(i1 -1, i1 1) ; overflow
78   // @o = constant i1 true
79   EXPECT_EQ(One, ConstantFoldBinaryInstruction(Instruction::SDiv, NegOne, One));
80 
81   // @p = constant i1 sdiv(i1 1 , i1 -1); overflow
82   // @p = constant i1 true
83   EXPECT_EQ(One, ConstantFoldBinaryInstruction(Instruction::SDiv, One, NegOne));
84 
85   // @q = constant i1 udiv(i1 -1, i1 1)
86   // @q = constant i1 true
87   EXPECT_EQ(One, ConstantFoldBinaryInstruction(Instruction::UDiv, NegOne, One));
88 
89   // @r = constant i1 udiv(i1 1, i1 -1)
90   // @r = constant i1 true
91   EXPECT_EQ(One, ConstantFoldBinaryInstruction(Instruction::UDiv, One, NegOne));
92 
93   // @s = constant i1 srem(i1 -1, i1 1) ; overflow
94   // @s = constant i1 false
95   EXPECT_EQ(Zero,
96             ConstantFoldBinaryInstruction(Instruction::SRem, NegOne, One));
97 
98   // @u = constant i1 srem(i1  1, i1 -1) ; overflow
99   // @u = constant i1 false
100   EXPECT_EQ(Zero,
101             ConstantFoldBinaryInstruction(Instruction::SRem, One, NegOne));
102 }
103 
104 TEST(ConstantsTest, IntSigns) {
105   LLVMContext Context;
106   IntegerType *Int8Ty = Type::getInt8Ty(Context);
107   EXPECT_EQ(100, ConstantInt::get(Int8Ty, 100, false)->getSExtValue());
108   EXPECT_EQ(100, ConstantInt::get(Int8Ty, 100, true)->getSExtValue());
109   EXPECT_EQ(100, ConstantInt::getSigned(Int8Ty, 100)->getSExtValue());
110   EXPECT_EQ(-50, ConstantInt::get(Int8Ty, 206)->getSExtValue());
111   EXPECT_EQ(-50, ConstantInt::getSigned(Int8Ty, -50)->getSExtValue());
112   EXPECT_EQ(206U, ConstantInt::getSigned(Int8Ty, -50)->getZExtValue());
113 
114   // Overflow is handled by truncation.
115   EXPECT_EQ(0x3b, ConstantInt::get(Int8Ty, 0x13b)->getSExtValue());
116 }
117 
118 TEST(ConstantsTest, FP128Test) {
119   LLVMContext Context;
120   Type *FP128Ty = Type::getFP128Ty(Context);
121 
122   IntegerType *Int128Ty = Type::getIntNTy(Context, 128);
123   Constant *Zero128 = Constant::getNullValue(Int128Ty);
124   Constant *X = ConstantExpr::getUIToFP(Zero128, FP128Ty);
125   EXPECT_TRUE(isa<ConstantFP>(X));
126 }
127 
128 TEST(ConstantsTest, PointerCast) {
129   LLVMContext C;
130   Type *Int8PtrTy = Type::getInt8PtrTy(C);
131   Type *Int32PtrTy = Type::getInt32PtrTy(C);
132   Type *Int64Ty = Type::getInt64Ty(C);
133   VectorType *Int8PtrVecTy = FixedVectorType::get(Int8PtrTy, 4);
134   VectorType *Int32PtrVecTy = FixedVectorType::get(Int32PtrTy, 4);
135   VectorType *Int64VecTy = FixedVectorType::get(Int64Ty, 4);
136   VectorType *Int8PtrScalableVecTy = ScalableVectorType::get(Int8PtrTy, 4);
137   VectorType *Int32PtrScalableVecTy = ScalableVectorType::get(Int32PtrTy, 4);
138   VectorType *Int64ScalableVecTy = ScalableVectorType::get(Int64Ty, 4);
139 
140   // ptrtoint i8* to i64
141   EXPECT_EQ(
142       Constant::getNullValue(Int64Ty),
143       ConstantExpr::getPointerCast(Constant::getNullValue(Int8PtrTy), Int64Ty));
144 
145   // bitcast i8* to i32*
146   EXPECT_EQ(Constant::getNullValue(Int32PtrTy),
147             ConstantExpr::getPointerCast(Constant::getNullValue(Int8PtrTy),
148                                          Int32PtrTy));
149 
150   // ptrtoint <4 x i8*> to <4 x i64>
151   EXPECT_EQ(Constant::getNullValue(Int64VecTy),
152             ConstantExpr::getPointerCast(Constant::getNullValue(Int8PtrVecTy),
153                                          Int64VecTy));
154 
155   // ptrtoint <vscale x 4 x i8*> to <vscale x 4 x i64>
156   EXPECT_EQ(
157       Constant::getNullValue(Int64ScalableVecTy),
158       ConstantExpr::getPointerCast(Constant::getNullValue(Int8PtrScalableVecTy),
159                                    Int64ScalableVecTy));
160 
161   // bitcast <4 x i8*> to <4 x i32*>
162   EXPECT_EQ(Constant::getNullValue(Int32PtrVecTy),
163             ConstantExpr::getPointerCast(Constant::getNullValue(Int8PtrVecTy),
164                                          Int32PtrVecTy));
165 
166   // bitcast <vscale x 4 x i8*> to <vscale x 4 x i32*>
167   EXPECT_EQ(
168       Constant::getNullValue(Int32PtrScalableVecTy),
169       ConstantExpr::getPointerCast(Constant::getNullValue(Int8PtrScalableVecTy),
170                                    Int32PtrScalableVecTy));
171 
172   Type *Int32Ptr1Ty = Type::getInt32PtrTy(C, 1);
173   ConstantInt *K = ConstantInt::get(Type::getInt64Ty(C), 1234);
174 
175   // Make sure that addrspacecast of inttoptr is not folded away.
176   EXPECT_NE(K, ConstantExpr::getAddrSpaceCast(
177                    ConstantExpr::getIntToPtr(K, Int32PtrTy), Int32Ptr1Ty));
178   EXPECT_NE(K, ConstantExpr::getAddrSpaceCast(
179                    ConstantExpr::getIntToPtr(K, Int32Ptr1Ty), Int32PtrTy));
180 
181   Constant *NullInt32Ptr0 = Constant::getNullValue(Int32PtrTy);
182   Constant *NullInt32Ptr1 = Constant::getNullValue(Int32Ptr1Ty);
183 
184   // Make sure that addrspacecast of null is not folded away.
185   EXPECT_NE(Constant::getNullValue(Int32PtrTy),
186             ConstantExpr::getAddrSpaceCast(NullInt32Ptr0, Int32Ptr1Ty));
187 
188   EXPECT_NE(Constant::getNullValue(Int32Ptr1Ty),
189             ConstantExpr::getAddrSpaceCast(NullInt32Ptr1, Int32PtrTy));
190 }
191 
192 #define CHECK(x, y)                                                            \
193   {                                                                            \
194     std::string __s;                                                           \
195     raw_string_ostream __o(__s);                                               \
196     Instruction *__I = cast<ConstantExpr>(x)->getAsInstruction();              \
197     __I->print(__o);                                                           \
198     __I->deleteValue();                                                        \
199     __o.flush();                                                               \
200     EXPECT_EQ(std::string("  <badref> = " y), __s);                            \
201   }
202 
203 TEST(ConstantsTest, AsInstructionsTest) {
204   LLVMContext Context;
205   std::unique_ptr<Module> M(new Module("MyModule", Context));
206 
207   Type *Int64Ty = Type::getInt64Ty(Context);
208   Type *Int32Ty = Type::getInt32Ty(Context);
209   Type *Int16Ty = Type::getInt16Ty(Context);
210   Type *Int1Ty = Type::getInt1Ty(Context);
211   Type *FloatTy = Type::getFloatTy(Context);
212   Type *DoubleTy = Type::getDoubleTy(Context);
213 
214   Constant *Global =
215       M->getOrInsertGlobal("dummy", PointerType::getUnqual(Int32Ty));
216   Constant *Global2 =
217       M->getOrInsertGlobal("dummy2", PointerType::getUnqual(Int32Ty));
218 
219   Constant *P0 = ConstantExpr::getPtrToInt(Global, Int32Ty);
220   Constant *P1 = ConstantExpr::getUIToFP(P0, FloatTy);
221   Constant *P2 = ConstantExpr::getUIToFP(P0, DoubleTy);
222   Constant *P3 = ConstantExpr::getTrunc(P0, Int1Ty);
223   Constant *P4 = ConstantExpr::getPtrToInt(Global2, Int32Ty);
224   Constant *P5 = ConstantExpr::getUIToFP(P4, FloatTy);
225   Constant *P6 = ConstantExpr::getBitCast(P4, FixedVectorType::get(Int16Ty, 2));
226 
227   Constant *One = ConstantInt::get(Int32Ty, 1);
228   Constant *Two = ConstantInt::get(Int64Ty, 2);
229   Constant *Big = ConstantInt::get(Context, APInt{256, uint64_t(-1), true});
230   Constant *Elt = ConstantInt::get(Int16Ty, 2015);
231   Constant *Poison16 = PoisonValue::get(Int16Ty);
232   Constant *Undef64 = UndefValue::get(Int64Ty);
233   Constant *PoisonV16 = PoisonValue::get(P6->getType());
234 
235 #define P0STR "ptrtoint (ptr @dummy to i32)"
236 #define P1STR "uitofp (i32 ptrtoint (ptr @dummy to i32) to float)"
237 #define P2STR "uitofp (i32 ptrtoint (ptr @dummy to i32) to double)"
238 #define P3STR "ptrtoint (ptr @dummy to i1)"
239 #define P4STR "ptrtoint (ptr @dummy2 to i32)"
240 #define P5STR "uitofp (i32 ptrtoint (ptr @dummy2 to i32) to float)"
241 #define P6STR "bitcast (i32 ptrtoint (ptr @dummy2 to i32) to <2 x i16>)"
242 
243   CHECK(ConstantExpr::getNeg(P0), "sub i32 0, " P0STR);
244   CHECK(ConstantExpr::getFNeg(P1), "fneg float " P1STR);
245   CHECK(ConstantExpr::getNot(P0), "xor i32 " P0STR ", -1");
246   CHECK(ConstantExpr::getAdd(P0, P0), "add i32 " P0STR ", " P0STR);
247   CHECK(ConstantExpr::getAdd(P0, P0, false, true),
248         "add nsw i32 " P0STR ", " P0STR);
249   CHECK(ConstantExpr::getAdd(P0, P0, true, true),
250         "add nuw nsw i32 " P0STR ", " P0STR);
251   CHECK(ConstantExpr::getFAdd(P1, P1), "fadd float " P1STR ", " P1STR);
252   CHECK(ConstantExpr::getSub(P0, P0), "sub i32 " P0STR ", " P0STR);
253   CHECK(ConstantExpr::getFSub(P1, P1), "fsub float " P1STR ", " P1STR);
254   CHECK(ConstantExpr::getMul(P0, P0), "mul i32 " P0STR ", " P0STR);
255   CHECK(ConstantExpr::getFMul(P1, P1), "fmul float " P1STR ", " P1STR);
256   CHECK(ConstantExpr::getFDiv(P1, P1), "fdiv float " P1STR ", " P1STR);
257   CHECK(ConstantExpr::getFRem(P1, P1), "frem float " P1STR ", " P1STR);
258   CHECK(ConstantExpr::getAnd(P0, P0), "and i32 " P0STR ", " P0STR);
259   CHECK(ConstantExpr::getOr(P0, P0), "or i32 " P0STR ", " P0STR);
260   CHECK(ConstantExpr::getXor(P0, P0), "xor i32 " P0STR ", " P0STR);
261   CHECK(ConstantExpr::getShl(P0, P0), "shl i32 " P0STR ", " P0STR);
262   CHECK(ConstantExpr::getShl(P0, P0, true), "shl nuw i32 " P0STR ", " P0STR);
263   CHECK(ConstantExpr::getShl(P0, P0, false, true),
264         "shl nsw i32 " P0STR ", " P0STR);
265   CHECK(ConstantExpr::getLShr(P0, P0, false), "lshr i32 " P0STR ", " P0STR);
266   CHECK(ConstantExpr::getLShr(P0, P0, true),
267         "lshr exact i32 " P0STR ", " P0STR);
268   CHECK(ConstantExpr::getAShr(P0, P0, false), "ashr i32 " P0STR ", " P0STR);
269   CHECK(ConstantExpr::getAShr(P0, P0, true),
270         "ashr exact i32 " P0STR ", " P0STR);
271 
272   CHECK(ConstantExpr::getSExt(P0, Int64Ty), "sext i32 " P0STR " to i64");
273   CHECK(ConstantExpr::getZExt(P0, Int64Ty), "zext i32 " P0STR " to i64");
274   CHECK(ConstantExpr::getFPTrunc(P2, FloatTy),
275         "fptrunc double " P2STR " to float");
276   CHECK(ConstantExpr::getFPExtend(P1, DoubleTy),
277         "fpext float " P1STR " to double");
278 
279   CHECK(ConstantExpr::getSelect(P3, P0, P4),
280         "select i1 " P3STR ", i32 " P0STR ", i32 " P4STR);
281   CHECK(ConstantExpr::getICmp(CmpInst::ICMP_EQ, P0, P4),
282         "icmp eq i32 " P0STR ", " P4STR);
283   CHECK(ConstantExpr::getFCmp(CmpInst::FCMP_ULT, P1, P5),
284         "fcmp ult float " P1STR ", " P5STR);
285 
286   std::vector<Constant *> V;
287   V.push_back(One);
288   // FIXME: getGetElementPtr() actually creates an inbounds ConstantGEP,
289   //        not a normal one!
290   // CHECK(ConstantExpr::getGetElementPtr(Global, V, false),
291   //      "getelementptr i32*, i32** @dummy, i32 1");
292   CHECK(ConstantExpr::getInBoundsGetElementPtr(PointerType::getUnqual(Int32Ty),
293                                                Global, V),
294         "getelementptr inbounds ptr, ptr @dummy, i32 1");
295 
296   CHECK(ConstantExpr::getExtractElement(P6, One),
297         "extractelement <2 x i16> " P6STR ", i32 1");
298 
299   EXPECT_EQ(Poison16, ConstantExpr::getExtractElement(P6, Two));
300   EXPECT_EQ(Poison16, ConstantExpr::getExtractElement(P6, Big));
301   EXPECT_EQ(Poison16, ConstantExpr::getExtractElement(P6, Undef64));
302 
303   EXPECT_EQ(Elt, ConstantExpr::getExtractElement(
304                  ConstantExpr::getInsertElement(P6, Elt, One), One));
305   EXPECT_EQ(PoisonV16, ConstantExpr::getInsertElement(P6, Elt, Two));
306   EXPECT_EQ(PoisonV16, ConstantExpr::getInsertElement(P6, Elt, Big));
307   EXPECT_EQ(PoisonV16, ConstantExpr::getInsertElement(P6, Elt, Undef64));
308 }
309 
310 #ifdef GTEST_HAS_DEATH_TEST
311 #ifndef NDEBUG
312 TEST(ConstantsTest, ReplaceWithConstantTest) {
313   LLVMContext Context;
314   std::unique_ptr<Module> M(new Module("MyModule", Context));
315 
316   Type *Int32Ty = Type::getInt32Ty(Context);
317   Constant *One = ConstantInt::get(Int32Ty, 1);
318 
319   Constant *Global =
320       M->getOrInsertGlobal("dummy", PointerType::getUnqual(Int32Ty));
321   Constant *GEP = ConstantExpr::getGetElementPtr(
322       PointerType::getUnqual(Int32Ty), Global, One);
323   EXPECT_DEATH(Global->replaceAllUsesWith(GEP),
324                "this->replaceAllUsesWith\\(expr\\(this\\)\\) is NOT valid!");
325 }
326 
327 #endif
328 #endif
329 
330 #undef CHECK
331 
332 TEST(ConstantsTest, ConstantArrayReplaceWithConstant) {
333   LLVMContext Context;
334   std::unique_ptr<Module> M(new Module("MyModule", Context));
335 
336   Type *IntTy = Type::getInt8Ty(Context);
337   ArrayType *ArrayTy = ArrayType::get(IntTy, 2);
338   Constant *A01Vals[2] = {ConstantInt::get(IntTy, 0),
339                           ConstantInt::get(IntTy, 1)};
340   Constant *A01 = ConstantArray::get(ArrayTy, A01Vals);
341 
342   Constant *Global = new GlobalVariable(*M, IntTy, false,
343                                         GlobalValue::ExternalLinkage, nullptr);
344   Constant *GlobalInt = ConstantExpr::getPtrToInt(Global, IntTy);
345   Constant *A0GVals[2] = {ConstantInt::get(IntTy, 0), GlobalInt};
346   Constant *A0G = ConstantArray::get(ArrayTy, A0GVals);
347   ASSERT_NE(A01, A0G);
348 
349   GlobalVariable *RefArray =
350       new GlobalVariable(*M, ArrayTy, false, GlobalValue::ExternalLinkage, A0G);
351   ASSERT_EQ(A0G, RefArray->getInitializer());
352 
353   GlobalInt->replaceAllUsesWith(ConstantInt::get(IntTy, 1));
354   ASSERT_EQ(A01, RefArray->getInitializer());
355 }
356 
357 TEST(ConstantsTest, ConstantExprReplaceWithConstant) {
358   LLVMContext Context;
359   std::unique_ptr<Module> M(new Module("MyModule", Context));
360 
361   Type *IntTy = Type::getInt8Ty(Context);
362   Constant *G1 = new GlobalVariable(*M, IntTy, false,
363                                     GlobalValue::ExternalLinkage, nullptr);
364   Constant *G2 = new GlobalVariable(*M, IntTy, false,
365                                     GlobalValue::ExternalLinkage, nullptr);
366   ASSERT_NE(G1, G2);
367 
368   Constant *Int1 = ConstantExpr::getPtrToInt(G1, IntTy);
369   Constant *Int2 = ConstantExpr::getPtrToInt(G2, IntTy);
370   ASSERT_NE(Int1, Int2);
371 
372   GlobalVariable *Ref =
373       new GlobalVariable(*M, IntTy, false, GlobalValue::ExternalLinkage, Int1);
374   ASSERT_EQ(Int1, Ref->getInitializer());
375 
376   G1->replaceAllUsesWith(G2);
377   ASSERT_EQ(Int2, Ref->getInitializer());
378 }
379 
380 TEST(ConstantsTest, GEPReplaceWithConstant) {
381   LLVMContext Context;
382   std::unique_ptr<Module> M(new Module("MyModule", Context));
383 
384   Type *IntTy = Type::getInt32Ty(Context);
385   Type *PtrTy = PointerType::get(IntTy, 0);
386   auto *C1 = ConstantInt::get(IntTy, 1);
387   auto *Placeholder = new GlobalVariable(
388       *M, IntTy, false, GlobalValue::ExternalWeakLinkage, nullptr);
389   auto *GEP = ConstantExpr::getGetElementPtr(IntTy, Placeholder, C1);
390   ASSERT_EQ(GEP->getOperand(0), Placeholder);
391 
392   auto *Ref =
393       new GlobalVariable(*M, PtrTy, false, GlobalValue::ExternalLinkage, GEP);
394   ASSERT_EQ(GEP, Ref->getInitializer());
395 
396   auto *Global = new GlobalVariable(*M, IntTy, false,
397                                     GlobalValue::ExternalLinkage, nullptr);
398   auto *Alias = GlobalAlias::create(IntTy, 0, GlobalValue::ExternalLinkage,
399                                     "alias", Global, M.get());
400   Placeholder->replaceAllUsesWith(Alias);
401   ASSERT_EQ(GEP, Ref->getInitializer());
402   ASSERT_EQ(GEP->getOperand(0), Alias);
403 }
404 
405 TEST(ConstantsTest, AliasCAPI) {
406   LLVMContext Context;
407   SMDiagnostic Error;
408   std::unique_ptr<Module> M =
409       parseAssemblyString("@g = global i32 42", Error, Context);
410   GlobalVariable *G = M->getGlobalVariable("g");
411   Type *I16Ty = Type::getInt16Ty(Context);
412   Type *I16PTy = PointerType::get(I16Ty, 0);
413   Constant *Aliasee = ConstantExpr::getBitCast(G, I16PTy);
414   LLVMValueRef AliasRef =
415       LLVMAddAlias2(wrap(M.get()), wrap(I16Ty), 0, wrap(Aliasee), "a");
416   ASSERT_EQ(unwrap<GlobalAlias>(AliasRef)->getAliasee(), Aliasee);
417 }
418 
419 static std::string getNameOfType(Type *T) {
420   std::string S;
421   raw_string_ostream RSOS(S);
422   T->print(RSOS);
423   return S;
424 }
425 
426 TEST(ConstantsTest, BuildConstantDataArrays) {
427   LLVMContext Context;
428 
429   for (Type *T : {Type::getInt8Ty(Context), Type::getInt16Ty(Context),
430                   Type::getInt32Ty(Context), Type::getInt64Ty(Context)}) {
431     ArrayType *ArrayTy = ArrayType::get(T, 2);
432     Constant *Vals[] = {ConstantInt::get(T, 0), ConstantInt::get(T, 1)};
433     Constant *CA = ConstantArray::get(ArrayTy, Vals);
434     ASSERT_TRUE(isa<ConstantDataArray>(CA)) << " T = " << getNameOfType(T);
435     auto *CDA = cast<ConstantDataArray>(CA);
436     Constant *CA2 = ConstantDataArray::getRaw(
437         CDA->getRawDataValues(), CDA->getNumElements(), CDA->getElementType());
438     ASSERT_TRUE(CA == CA2) << " T = " << getNameOfType(T);
439   }
440 
441   for (Type *T : {Type::getHalfTy(Context), Type::getBFloatTy(Context),
442                   Type::getFloatTy(Context), Type::getDoubleTy(Context)}) {
443     ArrayType *ArrayTy = ArrayType::get(T, 2);
444     Constant *Vals[] = {ConstantFP::get(T, 0), ConstantFP::get(T, 1)};
445     Constant *CA = ConstantArray::get(ArrayTy, Vals);
446     ASSERT_TRUE(isa<ConstantDataArray>(CA)) << " T = " << getNameOfType(T);
447     auto *CDA = cast<ConstantDataArray>(CA);
448     Constant *CA2 = ConstantDataArray::getRaw(
449         CDA->getRawDataValues(), CDA->getNumElements(), CDA->getElementType());
450     ASSERT_TRUE(CA == CA2) << " T = " << getNameOfType(T);
451   }
452 }
453 
454 TEST(ConstantsTest, BuildConstantDataVectors) {
455   LLVMContext Context;
456 
457   for (Type *T : {Type::getInt8Ty(Context), Type::getInt16Ty(Context),
458                   Type::getInt32Ty(Context), Type::getInt64Ty(Context)}) {
459     Constant *Vals[] = {ConstantInt::get(T, 0), ConstantInt::get(T, 1)};
460     Constant *CV = ConstantVector::get(Vals);
461     ASSERT_TRUE(isa<ConstantDataVector>(CV)) << " T = " << getNameOfType(T);
462     auto *CDV = cast<ConstantDataVector>(CV);
463     Constant *CV2 = ConstantDataVector::getRaw(
464         CDV->getRawDataValues(), CDV->getNumElements(), CDV->getElementType());
465     ASSERT_TRUE(CV == CV2) << " T = " << getNameOfType(T);
466   }
467 
468   for (Type *T : {Type::getHalfTy(Context), Type::getBFloatTy(Context),
469                   Type::getFloatTy(Context), Type::getDoubleTy(Context)}) {
470     Constant *Vals[] = {ConstantFP::get(T, 0), ConstantFP::get(T, 1)};
471     Constant *CV = ConstantVector::get(Vals);
472     ASSERT_TRUE(isa<ConstantDataVector>(CV)) << " T = " << getNameOfType(T);
473     auto *CDV = cast<ConstantDataVector>(CV);
474     Constant *CV2 = ConstantDataVector::getRaw(
475         CDV->getRawDataValues(), CDV->getNumElements(), CDV->getElementType());
476     ASSERT_TRUE(CV == CV2) << " T = " << getNameOfType(T);
477   }
478 }
479 
480 void bitcastToGEPHelper(bool useOpaquePointers) {
481   LLVMContext Context;
482   Context.setOpaquePointers(useOpaquePointers);
483   std::unique_ptr<Module> M(new Module("MyModule", Context));
484 
485   auto *i32 = Type::getInt32Ty(Context);
486   auto *U = StructType::create(Context, "Unsized");
487   Type *EltTys[] = {i32, U};
488   auto *S = StructType::create(EltTys);
489 
490   auto *G =
491       new GlobalVariable(*M, S, false, GlobalValue::ExternalLinkage, nullptr);
492   auto *PtrTy = PointerType::get(i32, 0);
493   auto *C = ConstantExpr::getBitCast(G, PtrTy);
494   if (Context.supportsTypedPointers()) {
495     EXPECT_EQ(cast<ConstantExpr>(C)->getOpcode(), Instruction::BitCast);
496   } else {
497     /* With opaque pointers, no cast is necessary. */
498     EXPECT_EQ(C, G);
499   }
500 }
501 
502 TEST(ConstantsTest, BitcastToGEP) {
503   bitcastToGEPHelper(true);
504   bitcastToGEPHelper(false);
505 }
506 
507 bool foldFuncPtrAndConstToNull(LLVMContext &Context, Module *TheModule,
508                                uint64_t AndValue,
509                                MaybeAlign FunctionAlign = llvm::None) {
510   Type *VoidType(Type::getVoidTy(Context));
511   FunctionType *FuncType(FunctionType::get(VoidType, false));
512   Function *Func(
513       Function::Create(FuncType, GlobalValue::ExternalLinkage, "", TheModule));
514 
515   if (FunctionAlign)
516     Func->setAlignment(*FunctionAlign);
517 
518   IntegerType *ConstantIntType(Type::getInt32Ty(Context));
519   ConstantInt *TheConstant(ConstantInt::get(ConstantIntType, AndValue));
520 
521   Constant *TheConstantExpr(ConstantExpr::getPtrToInt(Func, ConstantIntType));
522 
523   bool Result =
524       ConstantExpr::get(Instruction::And, TheConstantExpr, TheConstant)
525           ->isNullValue();
526 
527   if (!TheModule) {
528     // If the Module exists then it will delete the Function.
529     delete Func;
530   }
531 
532   return Result;
533 }
534 
535 TEST(ConstantsTest, FoldFunctionPtrAlignUnknownAnd2) {
536   LLVMContext Context;
537   Module TheModule("TestModule", Context);
538   // When the DataLayout doesn't specify a function pointer alignment we
539   // assume in this case that it is 4 byte aligned. This is a bug but we can't
540   // fix it directly because it causes a code size regression on X86.
541   // FIXME: This test should be changed once existing targets have
542   // appropriate defaults. See associated FIXME in ConstantFoldBinaryInstruction
543   ASSERT_TRUE(foldFuncPtrAndConstToNull(Context, &TheModule, 2));
544 }
545 
546 TEST(ConstantsTest, DontFoldFunctionPtrAlignUnknownAnd4) {
547   LLVMContext Context;
548   Module TheModule("TestModule", Context);
549   ASSERT_FALSE(foldFuncPtrAndConstToNull(Context, &TheModule, 4));
550 }
551 
552 TEST(ConstantsTest, FoldFunctionPtrAlign4) {
553   LLVMContext Context;
554   Module TheModule("TestModule", Context);
555   const char *AlignmentStrings[] = {"Fi32", "Fn32"};
556 
557   for (unsigned AndValue = 1; AndValue <= 2; ++AndValue) {
558     for (const char *AlignmentString : AlignmentStrings) {
559       TheModule.setDataLayout(AlignmentString);
560       ASSERT_TRUE(foldFuncPtrAndConstToNull(Context, &TheModule, AndValue));
561     }
562   }
563 }
564 
565 TEST(ConstantsTest, DontFoldFunctionPtrAlign1) {
566   LLVMContext Context;
567   Module TheModule("TestModule", Context);
568   const char *AlignmentStrings[] = {"Fi8", "Fn8"};
569 
570   for (const char *AlignmentString : AlignmentStrings) {
571     TheModule.setDataLayout(AlignmentString);
572     ASSERT_FALSE(foldFuncPtrAndConstToNull(Context, &TheModule, 2));
573   }
574 }
575 
576 TEST(ConstantsTest, FoldFunctionAlign4PtrAlignMultiple) {
577   LLVMContext Context;
578   Module TheModule("TestModule", Context);
579   TheModule.setDataLayout("Fn8");
580   ASSERT_TRUE(foldFuncPtrAndConstToNull(Context, &TheModule, 2, Align(4)));
581 }
582 
583 TEST(ConstantsTest, DontFoldFunctionAlign4PtrAlignIndependent) {
584   LLVMContext Context;
585   Module TheModule("TestModule", Context);
586   TheModule.setDataLayout("Fi8");
587   ASSERT_FALSE(foldFuncPtrAndConstToNull(Context, &TheModule, 2, Align(4)));
588 }
589 
590 TEST(ConstantsTest, DontFoldFunctionPtrIfNoModule) {
591   LLVMContext Context;
592   // Even though the function is explicitly 4 byte aligned, in the absence of a
593   // DataLayout we can't assume that the function pointer is aligned.
594   ASSERT_FALSE(foldFuncPtrAndConstToNull(Context, nullptr, 2, Align(4)));
595 }
596 
597 TEST(ConstantsTest, FoldGlobalVariablePtr) {
598   LLVMContext Context;
599 
600   IntegerType *IntType(Type::getInt32Ty(Context));
601 
602   std::unique_ptr<GlobalVariable> Global(
603       new GlobalVariable(IntType, true, GlobalValue::ExternalLinkage));
604 
605   Global->setAlignment(Align(4));
606 
607   ConstantInt *TheConstant(ConstantInt::get(IntType, 2));
608 
609   Constant *TheConstantExpr(ConstantExpr::getPtrToInt(Global.get(), IntType));
610 
611   ASSERT_TRUE(ConstantExpr::get(Instruction::And, TheConstantExpr, TheConstant)
612                   ->isNullValue());
613 }
614 
615 // Check that containsUndefOrPoisonElement and containsPoisonElement is working
616 // great
617 
618 TEST(ConstantsTest, containsUndefElemTest) {
619   LLVMContext Context;
620 
621   Type *Int32Ty = Type::getInt32Ty(Context);
622   Constant *CU = UndefValue::get(Int32Ty);
623   Constant *CP = PoisonValue::get(Int32Ty);
624   Constant *C1 = ConstantInt::get(Int32Ty, 1);
625   Constant *C2 = ConstantInt::get(Int32Ty, 2);
626 
627   {
628     Constant *V1 = ConstantVector::get({C1, C2});
629     EXPECT_FALSE(V1->containsUndefOrPoisonElement());
630     EXPECT_FALSE(V1->containsPoisonElement());
631   }
632 
633   {
634     Constant *V2 = ConstantVector::get({C1, CU});
635     EXPECT_TRUE(V2->containsUndefOrPoisonElement());
636     EXPECT_FALSE(V2->containsPoisonElement());
637   }
638 
639   {
640     Constant *V3 = ConstantVector::get({C1, CP});
641     EXPECT_TRUE(V3->containsUndefOrPoisonElement());
642     EXPECT_TRUE(V3->containsPoisonElement());
643   }
644 
645   {
646     Constant *V4 = ConstantVector::get({CU, CP});
647     EXPECT_TRUE(V4->containsUndefOrPoisonElement());
648     EXPECT_TRUE(V4->containsPoisonElement());
649   }
650 }
651 
652 // Check that undefined elements in vector constants are matched
653 // correctly for both integer and floating-point types. Just don't
654 // crash on vectors of pointers (could be handled?).
655 
656 TEST(ConstantsTest, isElementWiseEqual) {
657   LLVMContext Context;
658 
659   Type *Int32Ty = Type::getInt32Ty(Context);
660   Constant *CU = UndefValue::get(Int32Ty);
661   Constant *C1 = ConstantInt::get(Int32Ty, 1);
662   Constant *C2 = ConstantInt::get(Int32Ty, 2);
663 
664   Constant *C1211 = ConstantVector::get({C1, C2, C1, C1});
665   Constant *C12U1 = ConstantVector::get({C1, C2, CU, C1});
666   Constant *C12U2 = ConstantVector::get({C1, C2, CU, C2});
667   Constant *C12U21 = ConstantVector::get({C1, C2, CU, C2, C1});
668 
669   EXPECT_TRUE(C1211->isElementWiseEqual(C12U1));
670   EXPECT_TRUE(C12U1->isElementWiseEqual(C1211));
671   EXPECT_FALSE(C12U2->isElementWiseEqual(C12U1));
672   EXPECT_FALSE(C12U1->isElementWiseEqual(C12U2));
673   EXPECT_FALSE(C12U21->isElementWiseEqual(C12U2));
674 
675   Type *FltTy = Type::getFloatTy(Context);
676   Constant *CFU = UndefValue::get(FltTy);
677   Constant *CF1 = ConstantFP::get(FltTy, 1.0);
678   Constant *CF2 = ConstantFP::get(FltTy, 2.0);
679 
680   Constant *CF1211 = ConstantVector::get({CF1, CF2, CF1, CF1});
681   Constant *CF12U1 = ConstantVector::get({CF1, CF2, CFU, CF1});
682   Constant *CF12U2 = ConstantVector::get({CF1, CF2, CFU, CF2});
683   Constant *CFUU1U = ConstantVector::get({CFU, CFU, CF1, CFU});
684 
685   EXPECT_TRUE(CF1211->isElementWiseEqual(CF12U1));
686   EXPECT_TRUE(CF12U1->isElementWiseEqual(CF1211));
687   EXPECT_TRUE(CFUU1U->isElementWiseEqual(CF12U1));
688   EXPECT_FALSE(CF12U2->isElementWiseEqual(CF12U1));
689   EXPECT_FALSE(CF12U1->isElementWiseEqual(CF12U2));
690 
691   PointerType *PtrTy = Type::getInt8PtrTy(Context);
692   Constant *CPU = UndefValue::get(PtrTy);
693   Constant *CP0 = ConstantPointerNull::get(PtrTy);
694 
695   Constant *CP0000 = ConstantVector::get({CP0, CP0, CP0, CP0});
696   Constant *CP00U0 = ConstantVector::get({CP0, CP0, CPU, CP0});
697   Constant *CP00U = ConstantVector::get({CP0, CP0, CPU});
698 
699   EXPECT_FALSE(CP0000->isElementWiseEqual(CP00U0));
700   EXPECT_FALSE(CP00U0->isElementWiseEqual(CP0000));
701   EXPECT_FALSE(CP0000->isElementWiseEqual(CP00U));
702   EXPECT_FALSE(CP00U->isElementWiseEqual(CP00U0));
703 }
704 
705 // Check that vector/aggregate constants correctly store undef and poison
706 // elements.
707 
708 TEST(ConstantsTest, CheckElementWiseUndefPoison) {
709   LLVMContext Context;
710 
711   Type *Int32Ty = Type::getInt32Ty(Context);
712   StructType *STy = StructType::get(Int32Ty, Int32Ty);
713   ArrayType *ATy = ArrayType::get(Int32Ty, 2);
714   Constant *CU = UndefValue::get(Int32Ty);
715   Constant *CP = PoisonValue::get(Int32Ty);
716 
717   {
718     Constant *CUU = ConstantVector::get({CU, CU});
719     Constant *CPP = ConstantVector::get({CP, CP});
720     Constant *CUP = ConstantVector::get({CU, CP});
721     Constant *CPU = ConstantVector::get({CP, CU});
722     EXPECT_EQ(CUU, UndefValue::get(CUU->getType()));
723     EXPECT_EQ(CPP, PoisonValue::get(CPP->getType()));
724     EXPECT_NE(CUP, UndefValue::get(CUP->getType()));
725     EXPECT_NE(CPU, UndefValue::get(CPU->getType()));
726   }
727 
728   {
729     Constant *CUU = ConstantStruct::get(STy, {CU, CU});
730     Constant *CPP = ConstantStruct::get(STy, {CP, CP});
731     Constant *CUP = ConstantStruct::get(STy, {CU, CP});
732     Constant *CPU = ConstantStruct::get(STy, {CP, CU});
733     EXPECT_EQ(CUU, UndefValue::get(CUU->getType()));
734     EXPECT_EQ(CPP, PoisonValue::get(CPP->getType()));
735     EXPECT_NE(CUP, UndefValue::get(CUP->getType()));
736     EXPECT_NE(CPU, UndefValue::get(CPU->getType()));
737   }
738 
739   {
740     Constant *CUU = ConstantArray::get(ATy, {CU, CU});
741     Constant *CPP = ConstantArray::get(ATy, {CP, CP});
742     Constant *CUP = ConstantArray::get(ATy, {CU, CP});
743     Constant *CPU = ConstantArray::get(ATy, {CP, CU});
744     EXPECT_EQ(CUU, UndefValue::get(CUU->getType()));
745     EXPECT_EQ(CPP, PoisonValue::get(CPP->getType()));
746     EXPECT_NE(CUP, UndefValue::get(CUP->getType()));
747     EXPECT_NE(CPU, UndefValue::get(CPU->getType()));
748   }
749 }
750 
751 TEST(ConstantsTest, GetSplatValueRoundTrip) {
752   LLVMContext Context;
753 
754   Type *FloatTy = Type::getFloatTy(Context);
755   Type *Int32Ty = Type::getInt32Ty(Context);
756   Type *Int8Ty = Type::getInt8Ty(Context);
757 
758   for (unsigned Min : {1, 2, 8}) {
759     auto ScalableEC = ElementCount::getScalable(Min);
760     auto FixedEC = ElementCount::getFixed(Min);
761 
762     for (auto EC : {ScalableEC, FixedEC}) {
763       for (auto *Ty : {FloatTy, Int32Ty, Int8Ty}) {
764         Constant *Zero = Constant::getNullValue(Ty);
765         Constant *One = Constant::getAllOnesValue(Ty);
766 
767         for (auto *C : {Zero, One}) {
768           Constant *Splat = ConstantVector::getSplat(EC, C);
769           ASSERT_NE(nullptr, Splat);
770 
771           Constant *SplatVal = Splat->getSplatValue();
772           EXPECT_NE(nullptr, SplatVal);
773           EXPECT_EQ(SplatVal, C);
774         }
775       }
776     }
777   }
778 }
779 
780 TEST(ConstantsTest, ComdatUserTracking) {
781   LLVMContext Context;
782   Module M("MyModule", Context);
783 
784   Comdat *C = M.getOrInsertComdat("comdat");
785   const SmallPtrSetImpl<GlobalObject *> &Users = C->getUsers();
786   EXPECT_TRUE(Users.size() == 0);
787 
788   Type *Ty = Type::getInt8Ty(Context);
789   GlobalVariable *GV1 = cast<GlobalVariable>(M.getOrInsertGlobal("gv1", Ty));
790   GV1->setComdat(C);
791   EXPECT_TRUE(Users.size() == 1);
792   EXPECT_TRUE(Users.contains(GV1));
793 
794   GlobalVariable *GV2 = cast<GlobalVariable>(M.getOrInsertGlobal("gv2", Ty));
795   GV2->setComdat(C);
796   EXPECT_TRUE(Users.size() == 2);
797   EXPECT_TRUE(Users.contains(GV2));
798 
799   GV1->eraseFromParent();
800   EXPECT_TRUE(Users.size() == 1);
801   EXPECT_TRUE(Users.contains(GV2));
802 
803   GV2->eraseFromParent();
804   EXPECT_TRUE(Users.size() == 0);
805 }
806 
807 } // end anonymous namespace
808 } // end namespace llvm
809