IR: Rename replaceWithUniqued() tests from r233751
[oota-llvm.git] / unittests / IR / MetadataTest.cpp
1 //===- unittests/IR/MetadataTest.cpp - Metadata unit tests ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/ADT/STLExtras.h"
11 #include "llvm/IR/Constants.h"
12 #include "llvm/IR/DebugInfo.h"
13 #include "llvm/IR/DebugInfoMetadata.h"
14 #include "llvm/IR/Function.h"
15 #include "llvm/IR/Instructions.h"
16 #include "llvm/IR/LLVMContext.h"
17 #include "llvm/IR/Metadata.h"
18 #include "llvm/IR/Module.h"
19 #include "llvm/IR/Type.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include "gtest/gtest.h"
22 using namespace llvm;
23
24 namespace {
25
26 TEST(ContextAndReplaceableUsesTest, FromContext) {
27   LLVMContext Context;
28   ContextAndReplaceableUses CRU(Context);
29   EXPECT_EQ(&Context, &CRU.getContext());
30   EXPECT_FALSE(CRU.hasReplaceableUses());
31   EXPECT_FALSE(CRU.getReplaceableUses());
32 }
33
34 TEST(ContextAndReplaceableUsesTest, FromReplaceableUses) {
35   LLVMContext Context;
36   ContextAndReplaceableUses CRU(make_unique<ReplaceableMetadataImpl>(Context));
37   EXPECT_EQ(&Context, &CRU.getContext());
38   EXPECT_TRUE(CRU.hasReplaceableUses());
39   EXPECT_TRUE(CRU.getReplaceableUses());
40 }
41
42 TEST(ContextAndReplaceableUsesTest, makeReplaceable) {
43   LLVMContext Context;
44   ContextAndReplaceableUses CRU(Context);
45   CRU.makeReplaceable(make_unique<ReplaceableMetadataImpl>(Context));
46   EXPECT_EQ(&Context, &CRU.getContext());
47   EXPECT_TRUE(CRU.hasReplaceableUses());
48   EXPECT_TRUE(CRU.getReplaceableUses());
49 }
50
51 TEST(ContextAndReplaceableUsesTest, takeReplaceableUses) {
52   LLVMContext Context;
53   auto ReplaceableUses = make_unique<ReplaceableMetadataImpl>(Context);
54   auto *Ptr = ReplaceableUses.get();
55   ContextAndReplaceableUses CRU(std::move(ReplaceableUses));
56   ReplaceableUses = CRU.takeReplaceableUses();
57   EXPECT_EQ(&Context, &CRU.getContext());
58   EXPECT_FALSE(CRU.hasReplaceableUses());
59   EXPECT_FALSE(CRU.getReplaceableUses());
60   EXPECT_EQ(Ptr, ReplaceableUses.get());
61 }
62
63 class MetadataTest : public testing::Test {
64 public:
65   MetadataTest() : M("test", Context), Counter(0) {}
66
67 protected:
68   LLVMContext Context;
69   Module M;
70   int Counter;
71
72   MDNode *getNode() { return MDNode::get(Context, None); }
73   MDNode *getNode(Metadata *MD) { return MDNode::get(Context, MD); }
74   MDNode *getNode(Metadata *MD1, Metadata *MD2) {
75     Metadata *MDs[] = {MD1, MD2};
76     return MDNode::get(Context, MDs);
77   }
78
79   MDTuple *getTuple() { return MDTuple::getDistinct(Context, None); }
80   MDSubroutineType *getSubroutineType() {
81     return MDSubroutineType::getDistinct(Context, 0, getNode(nullptr));
82   }
83   MDSubprogram *getSubprogram() {
84     return MDSubprogram::getDistinct(Context, nullptr, "", "", nullptr, 0,
85                                      nullptr, false, false, 0, nullptr, 0, 0, 0,
86                                      0);
87   }
88   MDFile *getFile() {
89     return MDFile::getDistinct(Context, "file.c", "/path/to/dir");
90   }
91   MDBasicType *getBasicType(StringRef Name) {
92     return MDBasicType::get(Context, dwarf::DW_TAG_unspecified_type, Name);
93   }
94   MDDerivedType *getDerivedType() {
95     return MDDerivedType::getDistinct(Context, dwarf::DW_TAG_pointer_type, "",
96                                       nullptr, 0, nullptr,
97                                       getBasicType("basictype"), 1, 2, 0, 0);
98   }
99   ConstantAsMetadata *getConstantAsMetadata() {
100     return ConstantAsMetadata::get(
101         ConstantInt::get(Type::getInt32Ty(Context), Counter++));
102   }
103   MDCompositeType *getCompositeType() {
104     return MDCompositeType::getDistinct(
105         Context, dwarf::DW_TAG_structure_type, "", nullptr, 0, nullptr, nullptr,
106         32, 32, 0, 0, nullptr, 0, nullptr, nullptr, "");
107   }
108   ConstantAsMetadata *getFunctionAsMetadata(StringRef Name) {
109     return ConstantAsMetadata::get(M.getOrInsertFunction(
110         Name, FunctionType::get(Type::getVoidTy(Context), None, false)));
111   }
112 };
113 typedef MetadataTest MDStringTest;
114
115 // Test that construction of MDString with different value produces different
116 // MDString objects, even with the same string pointer and nulls in the string.
117 TEST_F(MDStringTest, CreateDifferent) {
118   char x[3] = { 'f', 0, 'A' };
119   MDString *s1 = MDString::get(Context, StringRef(&x[0], 3));
120   x[2] = 'B';
121   MDString *s2 = MDString::get(Context, StringRef(&x[0], 3));
122   EXPECT_NE(s1, s2);
123 }
124
125 // Test that creation of MDStrings with the same string contents produces the
126 // same MDString object, even with different pointers.
127 TEST_F(MDStringTest, CreateSame) {
128   char x[4] = { 'a', 'b', 'c', 'X' };
129   char y[4] = { 'a', 'b', 'c', 'Y' };
130
131   MDString *s1 = MDString::get(Context, StringRef(&x[0], 3));
132   MDString *s2 = MDString::get(Context, StringRef(&y[0], 3));
133   EXPECT_EQ(s1, s2);
134 }
135
136 // Test that MDString prints out the string we fed it.
137 TEST_F(MDStringTest, PrintingSimple) {
138   char *str = new char[13];
139   strncpy(str, "testing 1 2 3", 13);
140   MDString *s = MDString::get(Context, StringRef(str, 13));
141   strncpy(str, "aaaaaaaaaaaaa", 13);
142   delete[] str;
143
144   std::string Str;
145   raw_string_ostream oss(Str);
146   s->print(oss);
147   EXPECT_STREQ("!\"testing 1 2 3\"", oss.str().c_str());
148 }
149
150 // Test printing of MDString with non-printable characters.
151 TEST_F(MDStringTest, PrintingComplex) {
152   char str[5] = {0, '\n', '"', '\\', (char)-1};
153   MDString *s = MDString::get(Context, StringRef(str+0, 5));
154   std::string Str;
155   raw_string_ostream oss(Str);
156   s->print(oss);
157   EXPECT_STREQ("!\"\\00\\0A\\22\\5C\\FF\"", oss.str().c_str());
158 }
159
160 typedef MetadataTest MDNodeTest;
161
162 // Test the two constructors, and containing other Constants.
163 TEST_F(MDNodeTest, Simple) {
164   char x[3] = { 'a', 'b', 'c' };
165   char y[3] = { '1', '2', '3' };
166
167   MDString *s1 = MDString::get(Context, StringRef(&x[0], 3));
168   MDString *s2 = MDString::get(Context, StringRef(&y[0], 3));
169   ConstantAsMetadata *CI = ConstantAsMetadata::get(
170       ConstantInt::get(getGlobalContext(), APInt(8, 0)));
171
172   std::vector<Metadata *> V;
173   V.push_back(s1);
174   V.push_back(CI);
175   V.push_back(s2);
176
177   MDNode *n1 = MDNode::get(Context, V);
178   Metadata *const c1 = n1;
179   MDNode *n2 = MDNode::get(Context, c1);
180   Metadata *const c2 = n2;
181   MDNode *n3 = MDNode::get(Context, V);
182   MDNode *n4 = MDNode::getIfExists(Context, V);
183   MDNode *n5 = MDNode::getIfExists(Context, c1);
184   MDNode *n6 = MDNode::getIfExists(Context, c2);
185   EXPECT_NE(n1, n2);
186   EXPECT_EQ(n1, n3);
187   EXPECT_EQ(n4, n1);
188   EXPECT_EQ(n5, n2);
189   EXPECT_EQ(n6, (Metadata *)nullptr);
190
191   EXPECT_EQ(3u, n1->getNumOperands());
192   EXPECT_EQ(s1, n1->getOperand(0));
193   EXPECT_EQ(CI, n1->getOperand(1));
194   EXPECT_EQ(s2, n1->getOperand(2));
195
196   EXPECT_EQ(1u, n2->getNumOperands());
197   EXPECT_EQ(n1, n2->getOperand(0));
198 }
199
200 TEST_F(MDNodeTest, Delete) {
201   Constant *C = ConstantInt::get(Type::getInt32Ty(getGlobalContext()), 1);
202   Instruction *I = new BitCastInst(C, Type::getInt32Ty(getGlobalContext()));
203
204   Metadata *const V = LocalAsMetadata::get(I);
205   MDNode *n = MDNode::get(Context, V);
206   TrackingMDRef wvh(n);
207
208   EXPECT_EQ(n, wvh);
209
210   delete I;
211 }
212
213 TEST_F(MDNodeTest, SelfReference) {
214   // !0 = !{!0}
215   // !1 = !{!0}
216   {
217     auto Temp = MDNode::getTemporary(Context, None);
218     Metadata *Args[] = {Temp.get()};
219     MDNode *Self = MDNode::get(Context, Args);
220     Self->replaceOperandWith(0, Self);
221     ASSERT_EQ(Self, Self->getOperand(0));
222
223     // Self-references should be distinct, so MDNode::get() should grab a
224     // uniqued node that references Self, not Self.
225     Args[0] = Self;
226     MDNode *Ref1 = MDNode::get(Context, Args);
227     MDNode *Ref2 = MDNode::get(Context, Args);
228     EXPECT_NE(Self, Ref1);
229     EXPECT_EQ(Ref1, Ref2);
230   }
231
232   // !0 = !{!0, !{}}
233   // !1 = !{!0, !{}}
234   {
235     auto Temp = MDNode::getTemporary(Context, None);
236     Metadata *Args[] = {Temp.get(), MDNode::get(Context, None)};
237     MDNode *Self = MDNode::get(Context, Args);
238     Self->replaceOperandWith(0, Self);
239     ASSERT_EQ(Self, Self->getOperand(0));
240
241     // Self-references should be distinct, so MDNode::get() should grab a
242     // uniqued node that references Self, not Self itself.
243     Args[0] = Self;
244     MDNode *Ref1 = MDNode::get(Context, Args);
245     MDNode *Ref2 = MDNode::get(Context, Args);
246     EXPECT_NE(Self, Ref1);
247     EXPECT_EQ(Ref1, Ref2);
248   }
249 }
250
251 TEST_F(MDNodeTest, Print) {
252   Constant *C = ConstantInt::get(Type::getInt32Ty(Context), 7);
253   MDString *S = MDString::get(Context, "foo");
254   MDNode *N0 = getNode();
255   MDNode *N1 = getNode(N0);
256   MDNode *N2 = getNode(N0, N1);
257
258   Metadata *Args[] = {ConstantAsMetadata::get(C), S, nullptr, N0, N1, N2};
259   MDNode *N = MDNode::get(Context, Args);
260
261   std::string Expected;
262   {
263     raw_string_ostream OS(Expected);
264     OS << "<" << (void *)N << "> = !{";
265     C->printAsOperand(OS);
266     OS << ", ";
267     S->printAsOperand(OS);
268     OS << ", null";
269     MDNode *Nodes[] = {N0, N1, N2};
270     for (auto *Node : Nodes)
271       OS << ", <" << (void *)Node << ">";
272     OS << "}";
273   }
274
275   std::string Actual;
276   {
277     raw_string_ostream OS(Actual);
278     N->print(OS);
279   }
280
281   EXPECT_EQ(Expected, Actual);
282 }
283
284 #define EXPECT_PRINTER_EQ(EXPECTED, PRINT)                                     \
285   do {                                                                         \
286     std::string Actual_;                                                       \
287     raw_string_ostream OS(Actual_);                                            \
288     PRINT;                                                                     \
289     OS.flush();                                                                \
290     std::string Expected_(EXPECTED);                                           \
291     EXPECT_EQ(Expected_, Actual_);                                             \
292   } while (false)
293
294 TEST_F(MDNodeTest, PrintTemporary) {
295   MDNode *Arg = getNode();
296   TempMDNode Temp = MDNode::getTemporary(Context, Arg);
297   MDNode *N = getNode(Temp.get());
298   Module M("test", Context);
299   NamedMDNode *NMD = M.getOrInsertNamedMetadata("named");
300   NMD->addOperand(N);
301
302   EXPECT_PRINTER_EQ("!0 = !{!1}", N->print(OS, &M));
303   EXPECT_PRINTER_EQ("!1 = <temporary!> !{!2}", Temp->print(OS, &M));
304   EXPECT_PRINTER_EQ("!2 = !{}", Arg->print(OS, &M));
305
306   // Cleanup.
307   Temp->replaceAllUsesWith(Arg);
308 }
309
310 TEST_F(MDNodeTest, PrintFromModule) {
311   Constant *C = ConstantInt::get(Type::getInt32Ty(Context), 7);
312   MDString *S = MDString::get(Context, "foo");
313   MDNode *N0 = getNode();
314   MDNode *N1 = getNode(N0);
315   MDNode *N2 = getNode(N0, N1);
316
317   Metadata *Args[] = {ConstantAsMetadata::get(C), S, nullptr, N0, N1, N2};
318   MDNode *N = MDNode::get(Context, Args);
319   Module M("test", Context);
320   NamedMDNode *NMD = M.getOrInsertNamedMetadata("named");
321   NMD->addOperand(N);
322
323   std::string Expected;
324   {
325     raw_string_ostream OS(Expected);
326     OS << "!0 = !{";
327     C->printAsOperand(OS);
328     OS << ", ";
329     S->printAsOperand(OS);
330     OS << ", null, !1, !2, !3}";
331   }
332
333   EXPECT_PRINTER_EQ(Expected, N->print(OS, &M));
334 }
335
336 TEST_F(MDNodeTest, PrintFromFunction) {
337   Module M("test", Context);
338   auto *FTy = FunctionType::get(Type::getVoidTy(Context), false);
339   auto *F0 = Function::Create(FTy, GlobalValue::ExternalLinkage, "F0", &M);
340   auto *F1 = Function::Create(FTy, GlobalValue::ExternalLinkage, "F1", &M);
341   auto *BB0 = BasicBlock::Create(Context, "entry", F0);
342   auto *BB1 = BasicBlock::Create(Context, "entry", F1);
343   auto *R0 = ReturnInst::Create(Context, BB0);
344   auto *R1 = ReturnInst::Create(Context, BB1);
345   auto *N0 = MDNode::getDistinct(Context, None);
346   auto *N1 = MDNode::getDistinct(Context, None);
347   R0->setMetadata("md", N0);
348   R1->setMetadata("md", N1);
349
350   EXPECT_PRINTER_EQ("!0 = distinct !{}", N0->print(OS, &M));
351   EXPECT_PRINTER_EQ("!1 = distinct !{}", N1->print(OS, &M));
352 }
353
354 TEST_F(MDNodeTest, PrintFromMetadataAsValue) {
355   Module M("test", Context);
356
357   auto *Intrinsic =
358       Function::Create(FunctionType::get(Type::getVoidTy(Context),
359                                          Type::getMetadataTy(Context), false),
360                        GlobalValue::ExternalLinkage, "llvm.intrinsic", &M);
361
362   auto *FTy = FunctionType::get(Type::getVoidTy(Context), false);
363   auto *F0 = Function::Create(FTy, GlobalValue::ExternalLinkage, "F0", &M);
364   auto *F1 = Function::Create(FTy, GlobalValue::ExternalLinkage, "F1", &M);
365   auto *BB0 = BasicBlock::Create(Context, "entry", F0);
366   auto *BB1 = BasicBlock::Create(Context, "entry", F1);
367   auto *N0 = MDNode::getDistinct(Context, None);
368   auto *N1 = MDNode::getDistinct(Context, None);
369   auto *MAV0 = MetadataAsValue::get(Context, N0);
370   auto *MAV1 = MetadataAsValue::get(Context, N1);
371   CallInst::Create(Intrinsic, MAV0, "", BB0);
372   CallInst::Create(Intrinsic, MAV1, "", BB1);
373
374   EXPECT_PRINTER_EQ("!0 = distinct !{}", MAV0->print(OS));
375   EXPECT_PRINTER_EQ("!1 = distinct !{}", MAV1->print(OS));
376   EXPECT_PRINTER_EQ("!0", MAV0->printAsOperand(OS, false));
377   EXPECT_PRINTER_EQ("!1", MAV1->printAsOperand(OS, false));
378   EXPECT_PRINTER_EQ("metadata !0", MAV0->printAsOperand(OS, true));
379   EXPECT_PRINTER_EQ("metadata !1", MAV1->printAsOperand(OS, true));
380 }
381 #undef EXPECT_PRINTER_EQ
382
383 TEST_F(MDNodeTest, NullOperand) {
384   // metadata !{}
385   MDNode *Empty = MDNode::get(Context, None);
386
387   // metadata !{metadata !{}}
388   Metadata *Ops[] = {Empty};
389   MDNode *N = MDNode::get(Context, Ops);
390   ASSERT_EQ(Empty, N->getOperand(0));
391
392   // metadata !{metadata !{}} => metadata !{null}
393   N->replaceOperandWith(0, nullptr);
394   ASSERT_EQ(nullptr, N->getOperand(0));
395
396   // metadata !{null}
397   Ops[0] = nullptr;
398   MDNode *NullOp = MDNode::get(Context, Ops);
399   ASSERT_EQ(nullptr, NullOp->getOperand(0));
400   EXPECT_EQ(N, NullOp);
401 }
402
403 TEST_F(MDNodeTest, DistinctOnUniquingCollision) {
404   // !{}
405   MDNode *Empty = MDNode::get(Context, None);
406   ASSERT_TRUE(Empty->isResolved());
407   EXPECT_FALSE(Empty->isDistinct());
408
409   // !{!{}}
410   Metadata *Wrapped1Ops[] = {Empty};
411   MDNode *Wrapped1 = MDNode::get(Context, Wrapped1Ops);
412   ASSERT_EQ(Empty, Wrapped1->getOperand(0));
413   ASSERT_TRUE(Wrapped1->isResolved());
414   EXPECT_FALSE(Wrapped1->isDistinct());
415
416   // !{!{!{}}}
417   Metadata *Wrapped2Ops[] = {Wrapped1};
418   MDNode *Wrapped2 = MDNode::get(Context, Wrapped2Ops);
419   ASSERT_EQ(Wrapped1, Wrapped2->getOperand(0));
420   ASSERT_TRUE(Wrapped2->isResolved());
421   EXPECT_FALSE(Wrapped2->isDistinct());
422
423   // !{!{!{}}} => !{!{}}
424   Wrapped2->replaceOperandWith(0, Empty);
425   ASSERT_EQ(Empty, Wrapped2->getOperand(0));
426   EXPECT_TRUE(Wrapped2->isDistinct());
427   EXPECT_FALSE(Wrapped1->isDistinct());
428 }
429
430 TEST_F(MDNodeTest, getDistinct) {
431   // !{}
432   MDNode *Empty = MDNode::get(Context, None);
433   ASSERT_TRUE(Empty->isResolved());
434   ASSERT_FALSE(Empty->isDistinct());
435   ASSERT_EQ(Empty, MDNode::get(Context, None));
436
437   // distinct !{}
438   MDNode *Distinct1 = MDNode::getDistinct(Context, None);
439   MDNode *Distinct2 = MDNode::getDistinct(Context, None);
440   EXPECT_TRUE(Distinct1->isResolved());
441   EXPECT_TRUE(Distinct2->isDistinct());
442   EXPECT_NE(Empty, Distinct1);
443   EXPECT_NE(Empty, Distinct2);
444   EXPECT_NE(Distinct1, Distinct2);
445
446   // !{}
447   ASSERT_EQ(Empty, MDNode::get(Context, None));
448 }
449
450 TEST_F(MDNodeTest, isUniqued) {
451   MDNode *U = MDTuple::get(Context, None);
452   MDNode *D = MDTuple::getDistinct(Context, None);
453   auto T = MDTuple::getTemporary(Context, None);
454   EXPECT_TRUE(U->isUniqued());
455   EXPECT_FALSE(D->isUniqued());
456   EXPECT_FALSE(T->isUniqued());
457 }
458
459 TEST_F(MDNodeTest, isDistinct) {
460   MDNode *U = MDTuple::get(Context, None);
461   MDNode *D = MDTuple::getDistinct(Context, None);
462   auto T = MDTuple::getTemporary(Context, None);
463   EXPECT_FALSE(U->isDistinct());
464   EXPECT_TRUE(D->isDistinct());
465   EXPECT_FALSE(T->isDistinct());
466 }
467
468 TEST_F(MDNodeTest, isTemporary) {
469   MDNode *U = MDTuple::get(Context, None);
470   MDNode *D = MDTuple::getDistinct(Context, None);
471   auto T = MDTuple::getTemporary(Context, None);
472   EXPECT_FALSE(U->isTemporary());
473   EXPECT_FALSE(D->isTemporary());
474   EXPECT_TRUE(T->isTemporary());
475 }
476
477 TEST_F(MDNodeTest, getDistinctWithUnresolvedOperands) {
478   // temporary !{}
479   auto Temp = MDTuple::getTemporary(Context, None);
480   ASSERT_FALSE(Temp->isResolved());
481
482   // distinct !{temporary !{}}
483   Metadata *Ops[] = {Temp.get()};
484   MDNode *Distinct = MDNode::getDistinct(Context, Ops);
485   EXPECT_TRUE(Distinct->isResolved());
486   EXPECT_EQ(Temp.get(), Distinct->getOperand(0));
487
488   // temporary !{} => !{}
489   MDNode *Empty = MDNode::get(Context, None);
490   Temp->replaceAllUsesWith(Empty);
491   EXPECT_EQ(Empty, Distinct->getOperand(0));
492 }
493
494 TEST_F(MDNodeTest, handleChangedOperandRecursion) {
495   // !0 = !{}
496   MDNode *N0 = MDNode::get(Context, None);
497
498   // !1 = !{!3, null}
499   auto Temp3 = MDTuple::getTemporary(Context, None);
500   Metadata *Ops1[] = {Temp3.get(), nullptr};
501   MDNode *N1 = MDNode::get(Context, Ops1);
502
503   // !2 = !{!3, !0}
504   Metadata *Ops2[] = {Temp3.get(), N0};
505   MDNode *N2 = MDNode::get(Context, Ops2);
506
507   // !3 = !{!2}
508   Metadata *Ops3[] = {N2};
509   MDNode *N3 = MDNode::get(Context, Ops3);
510   Temp3->replaceAllUsesWith(N3);
511
512   // !4 = !{!1}
513   Metadata *Ops4[] = {N1};
514   MDNode *N4 = MDNode::get(Context, Ops4);
515
516   // Confirm that the cycle prevented RAUW from getting dropped.
517   EXPECT_TRUE(N0->isResolved());
518   EXPECT_FALSE(N1->isResolved());
519   EXPECT_FALSE(N2->isResolved());
520   EXPECT_FALSE(N3->isResolved());
521   EXPECT_FALSE(N4->isResolved());
522
523   // Create a couple of distinct nodes to observe what's going on.
524   //
525   // !5 = distinct !{!2}
526   // !6 = distinct !{!3}
527   Metadata *Ops5[] = {N2};
528   MDNode *N5 = MDNode::getDistinct(Context, Ops5);
529   Metadata *Ops6[] = {N3};
530   MDNode *N6 = MDNode::getDistinct(Context, Ops6);
531
532   // Mutate !2 to look like !1, causing a uniquing collision (and an RAUW).
533   // This will ripple up, with !3 colliding with !4, and RAUWing.  Since !2
534   // references !3, this can cause a re-entry of handleChangedOperand() when !3
535   // is not ready for it.
536   //
537   // !2->replaceOperandWith(1, nullptr)
538   // !2: !{!3, !0} => !{!3, null}
539   // !2->replaceAllUsesWith(!1)
540   // !3: !{!2] => !{!1}
541   // !3->replaceAllUsesWith(!4)
542   N2->replaceOperandWith(1, nullptr);
543
544   // If all has gone well, N2 and N3 will have been RAUW'ed and deleted from
545   // under us.  Just check that the other nodes are sane.
546   //
547   // !1 = !{!4, null}
548   // !4 = !{!1}
549   // !5 = distinct !{!1}
550   // !6 = distinct !{!4}
551   EXPECT_EQ(N4, N1->getOperand(0));
552   EXPECT_EQ(N1, N4->getOperand(0));
553   EXPECT_EQ(N1, N5->getOperand(0));
554   EXPECT_EQ(N4, N6->getOperand(0));
555 }
556
557 TEST_F(MDNodeTest, replaceResolvedOperand) {
558   // Check code for replacing one resolved operand with another.  If doing this
559   // directly (via replaceOperandWith()) becomes illegal, change the operand to
560   // a global value that gets RAUW'ed.
561   //
562   // Use a temporary node to keep N from being resolved.
563   auto Temp = MDTuple::getTemporary(Context, None);
564   Metadata *Ops[] = {nullptr, Temp.get()};
565
566   MDNode *Empty = MDTuple::get(Context, ArrayRef<Metadata *>());
567   MDNode *N = MDTuple::get(Context, Ops);
568   EXPECT_EQ(nullptr, N->getOperand(0));
569   ASSERT_FALSE(N->isResolved());
570
571   // Check code for replacing resolved nodes.
572   N->replaceOperandWith(0, Empty);
573   EXPECT_EQ(Empty, N->getOperand(0));
574
575   // Check code for adding another unresolved operand.
576   N->replaceOperandWith(0, Temp.get());
577   EXPECT_EQ(Temp.get(), N->getOperand(0));
578
579   // Remove the references to Temp; required for teardown.
580   Temp->replaceAllUsesWith(nullptr);
581 }
582
583 TEST_F(MDNodeTest, replaceWithUniqued) {
584   auto *Empty = MDTuple::get(Context, None);
585   MDTuple *FirstUniqued;
586   {
587     Metadata *Ops[] = {Empty};
588     auto Temp = MDTuple::getTemporary(Context, Ops);
589     EXPECT_TRUE(Temp->isTemporary());
590
591     // Don't expect a collision.
592     auto *Current = Temp.get();
593     FirstUniqued = MDNode::replaceWithUniqued(std::move(Temp));
594     EXPECT_TRUE(FirstUniqued->isUniqued());
595     EXPECT_TRUE(FirstUniqued->isResolved());
596     EXPECT_EQ(Current, FirstUniqued);
597   }
598   {
599     Metadata *Ops[] = {Empty};
600     auto Temp = MDTuple::getTemporary(Context, Ops);
601     EXPECT_TRUE(Temp->isTemporary());
602
603     // Should collide with Uniqued above this time.
604     auto *Uniqued = MDNode::replaceWithUniqued(std::move(Temp));
605     EXPECT_TRUE(Uniqued->isUniqued());
606     EXPECT_TRUE(Uniqued->isResolved());
607     EXPECT_EQ(FirstUniqued, Uniqued);
608   }
609   {
610     auto Unresolved = MDTuple::getTemporary(Context, None);
611     Metadata *Ops[] = {Unresolved.get()};
612     auto Temp = MDTuple::getTemporary(Context, Ops);
613     EXPECT_TRUE(Temp->isTemporary());
614
615     // Shouldn't be resolved.
616     auto *Uniqued = MDNode::replaceWithUniqued(std::move(Temp));
617     EXPECT_TRUE(Uniqued->isUniqued());
618     EXPECT_FALSE(Uniqued->isResolved());
619
620     // Should be a different node.
621     EXPECT_NE(FirstUniqued, Uniqued);
622
623     // Should resolve when we update its node (note: be careful to avoid a
624     // collision with any other nodes above).
625     Uniqued->replaceOperandWith(0, nullptr);
626     EXPECT_TRUE(Uniqued->isResolved());
627   }
628 }
629
630 TEST_F(MDNodeTest, replaceWithUniquedResolvingOperand) {
631   // temp !{}
632   MDTuple *Op = MDTuple::getTemporary(Context, None).release();
633   EXPECT_FALSE(Op->isResolved());
634
635   // temp !{temp !{}}
636   Metadata *Ops[] = {Op};
637   MDTuple *N = MDTuple::getTemporary(Context, Ops).release();
638   EXPECT_FALSE(N->isResolved());
639
640   // temp !{temp !{}} => !{temp !{}}
641   ASSERT_EQ(N, MDNode::replaceWithUniqued(TempMDTuple(N)));
642   EXPECT_FALSE(N->isResolved());
643
644   // !{temp !{}} => !{!{}}
645   ASSERT_EQ(Op, MDNode::replaceWithUniqued(TempMDTuple(Op)));
646   EXPECT_TRUE(Op->isResolved());
647   EXPECT_TRUE(N->isResolved());
648 }
649
650 TEST_F(MDNodeTest, replaceWithUniquedChangingOperand) {
651   // i1* @GV
652   Type *Ty = Type::getInt1PtrTy(Context);
653   std::unique_ptr<GlobalVariable> GV(
654       new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage));
655   ConstantAsMetadata *Op = ConstantAsMetadata::get(GV.get());
656
657   // temp !{i1* @GV}
658   Metadata *Ops[] = {Op};
659   MDTuple *N = MDTuple::getTemporary(Context, Ops).release();
660
661   // temp !{i1* @GV} => !{i1* @GV}
662   ASSERT_EQ(N, MDNode::replaceWithUniqued(TempMDTuple(N)));
663   ASSERT_TRUE(N->isUniqued());
664
665   // !{i1* @GV} => !{null}
666   GV.reset();
667   ASSERT_TRUE(N->isUniqued());
668   Metadata *NullOps[] = {nullptr};
669   ASSERT_EQ(N, MDTuple::get(Context, NullOps));
670 }
671
672 TEST_F(MDNodeTest, replaceWithDistinct) {
673   {
674     auto *Empty = MDTuple::get(Context, None);
675     Metadata *Ops[] = {Empty};
676     auto Temp = MDTuple::getTemporary(Context, Ops);
677     EXPECT_TRUE(Temp->isTemporary());
678
679     // Don't expect a collision.
680     auto *Current = Temp.get();
681     auto *Distinct = MDNode::replaceWithDistinct(std::move(Temp));
682     EXPECT_TRUE(Distinct->isDistinct());
683     EXPECT_TRUE(Distinct->isResolved());
684     EXPECT_EQ(Current, Distinct);
685   }
686   {
687     auto Unresolved = MDTuple::getTemporary(Context, None);
688     Metadata *Ops[] = {Unresolved.get()};
689     auto Temp = MDTuple::getTemporary(Context, Ops);
690     EXPECT_TRUE(Temp->isTemporary());
691
692     // Don't expect a collision.
693     auto *Current = Temp.get();
694     auto *Distinct = MDNode::replaceWithDistinct(std::move(Temp));
695     EXPECT_TRUE(Distinct->isDistinct());
696     EXPECT_TRUE(Distinct->isResolved());
697     EXPECT_EQ(Current, Distinct);
698
699     // Cleanup; required for teardown.
700     Unresolved->replaceAllUsesWith(nullptr);
701   }
702 }
703
704 TEST_F(MDNodeTest, replaceWithPermanent) {
705   Metadata *Ops[] = {nullptr};
706   auto Temp = MDTuple::getTemporary(Context, Ops);
707   auto *T = Temp.get();
708
709   // U is a normal, uniqued node that references T.
710   auto *U = MDTuple::get(Context, T);
711   EXPECT_TRUE(U->isUniqued());
712
713   // Make Temp self-referencing.
714   Temp->replaceOperandWith(0, T);
715
716   // Try to uniquify Temp.  This should, despite the name in the API, give a
717   // 'distinct' node, since self-references aren't allowed to be uniqued.
718   //
719   // Since it's distinct, N should have the same address as when it was a
720   // temporary (i.e., be equal to T not U).
721   auto *N = MDNode::replaceWithPermanent(std::move(Temp));
722   EXPECT_EQ(N, T);
723   EXPECT_TRUE(N->isDistinct());
724
725   // U should be the canonical unique node with N as the argument.
726   EXPECT_EQ(U, MDTuple::get(Context, N));
727   EXPECT_TRUE(U->isUniqued());
728
729   // This temporary should collide with U when replaced, but it should still be
730   // uniqued.
731   EXPECT_EQ(U, MDNode::replaceWithPermanent(MDTuple::getTemporary(Context, N)));
732   EXPECT_TRUE(U->isUniqued());
733
734   // This temporary should become a new uniqued node.
735   auto Temp2 = MDTuple::getTemporary(Context, U);
736   auto *V = Temp2.get();
737   EXPECT_EQ(V, MDNode::replaceWithPermanent(std::move(Temp2)));
738   EXPECT_TRUE(V->isUniqued());
739   EXPECT_EQ(U, V->getOperand(0));
740 }
741
742 TEST_F(MDNodeTest, deleteTemporaryWithTrackingRef) {
743   TrackingMDRef Ref;
744   EXPECT_EQ(nullptr, Ref.get());
745   {
746     auto Temp = MDTuple::getTemporary(Context, None);
747     Ref.reset(Temp.get());
748     EXPECT_EQ(Temp.get(), Ref.get());
749   }
750   EXPECT_EQ(nullptr, Ref.get());
751 }
752
753 typedef MetadataTest MDLocationTest;
754
755 TEST_F(MDLocationTest, Overflow) {
756   MDSubprogram *N = getSubprogram();
757   {
758     MDLocation *L = MDLocation::get(Context, 2, 7, N);
759     EXPECT_EQ(2u, L->getLine());
760     EXPECT_EQ(7u, L->getColumn());
761   }
762   unsigned U16 = 1u << 16;
763   {
764     MDLocation *L = MDLocation::get(Context, UINT32_MAX, U16 - 1, N);
765     EXPECT_EQ(UINT32_MAX, L->getLine());
766     EXPECT_EQ(U16 - 1, L->getColumn());
767   }
768   {
769     MDLocation *L = MDLocation::get(Context, UINT32_MAX, U16, N);
770     EXPECT_EQ(UINT32_MAX, L->getLine());
771     EXPECT_EQ(0u, L->getColumn());
772   }
773   {
774     MDLocation *L = MDLocation::get(Context, UINT32_MAX, U16 + 1, N);
775     EXPECT_EQ(UINT32_MAX, L->getLine());
776     EXPECT_EQ(0u, L->getColumn());
777   }
778 }
779
780 TEST_F(MDLocationTest, getDistinct) {
781   MDNode *N = getSubprogram();
782   MDLocation *L0 = MDLocation::getDistinct(Context, 2, 7, N);
783   EXPECT_TRUE(L0->isDistinct());
784   MDLocation *L1 = MDLocation::get(Context, 2, 7, N);
785   EXPECT_FALSE(L1->isDistinct());
786   EXPECT_EQ(L1, MDLocation::get(Context, 2, 7, N));
787 }
788
789 TEST_F(MDLocationTest, getTemporary) {
790   MDNode *N = MDNode::get(Context, None);
791   auto L = MDLocation::getTemporary(Context, 2, 7, N);
792   EXPECT_TRUE(L->isTemporary());
793   EXPECT_FALSE(L->isResolved());
794 }
795
796 typedef MetadataTest GenericDebugNodeTest;
797
798 TEST_F(GenericDebugNodeTest, get) {
799   StringRef Header = "header";
800   auto *Empty = MDNode::get(Context, None);
801   Metadata *Ops1[] = {Empty};
802   auto *N = GenericDebugNode::get(Context, 15, Header, Ops1);
803   EXPECT_EQ(15u, N->getTag());
804   EXPECT_EQ(2u, N->getNumOperands());
805   EXPECT_EQ(Header, N->getHeader());
806   EXPECT_EQ(MDString::get(Context, Header), N->getOperand(0));
807   EXPECT_EQ(1u, N->getNumDwarfOperands());
808   EXPECT_EQ(Empty, N->getDwarfOperand(0));
809   EXPECT_EQ(Empty, N->getOperand(1));
810   ASSERT_TRUE(N->isUniqued());
811
812   EXPECT_EQ(N, GenericDebugNode::get(Context, 15, Header, Ops1));
813
814   N->replaceOperandWith(1, nullptr);
815   EXPECT_EQ(15u, N->getTag());
816   EXPECT_EQ(Header, N->getHeader());
817   EXPECT_EQ(nullptr, N->getDwarfOperand(0));
818   ASSERT_TRUE(N->isUniqued());
819
820   Metadata *Ops2[] = {nullptr};
821   EXPECT_EQ(N, GenericDebugNode::get(Context, 15, Header, Ops2));
822
823   N->replaceDwarfOperandWith(0, Empty);
824   EXPECT_EQ(15u, N->getTag());
825   EXPECT_EQ(Header, N->getHeader());
826   EXPECT_EQ(Empty, N->getDwarfOperand(0));
827   ASSERT_TRUE(N->isUniqued());
828   EXPECT_EQ(N, GenericDebugNode::get(Context, 15, Header, Ops1));
829
830   TempGenericDebugNode Temp = N->clone();
831   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
832 }
833
834 TEST_F(GenericDebugNodeTest, getEmptyHeader) {
835   // Canonicalize !"" to null.
836   auto *N = GenericDebugNode::get(Context, 15, StringRef(), None);
837   EXPECT_EQ(StringRef(), N->getHeader());
838   EXPECT_EQ(nullptr, N->getOperand(0));
839 }
840
841 typedef MetadataTest MDSubrangeTest;
842
843 TEST_F(MDSubrangeTest, get) {
844   auto *N = MDSubrange::get(Context, 5, 7);
845   EXPECT_EQ(dwarf::DW_TAG_subrange_type, N->getTag());
846   EXPECT_EQ(5, N->getCount());
847   EXPECT_EQ(7, N->getLo());
848   EXPECT_EQ(N, MDSubrange::get(Context, 5, 7));
849   EXPECT_EQ(MDSubrange::get(Context, 5, 0), MDSubrange::get(Context, 5));
850
851   TempMDSubrange Temp = N->clone();
852   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
853 }
854
855 TEST_F(MDSubrangeTest, getEmptyArray) {
856   auto *N = MDSubrange::get(Context, -1, 0);
857   EXPECT_EQ(dwarf::DW_TAG_subrange_type, N->getTag());
858   EXPECT_EQ(-1, N->getCount());
859   EXPECT_EQ(0, N->getLo());
860   EXPECT_EQ(N, MDSubrange::get(Context, -1, 0));
861 }
862
863 typedef MetadataTest MDEnumeratorTest;
864
865 TEST_F(MDEnumeratorTest, get) {
866   auto *N = MDEnumerator::get(Context, 7, "name");
867   EXPECT_EQ(dwarf::DW_TAG_enumerator, N->getTag());
868   EXPECT_EQ(7, N->getValue());
869   EXPECT_EQ("name", N->getName());
870   EXPECT_EQ(N, MDEnumerator::get(Context, 7, "name"));
871
872   EXPECT_NE(N, MDEnumerator::get(Context, 8, "name"));
873   EXPECT_NE(N, MDEnumerator::get(Context, 7, "nam"));
874
875   TempMDEnumerator Temp = N->clone();
876   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
877 }
878
879 typedef MetadataTest MDBasicTypeTest;
880
881 TEST_F(MDBasicTypeTest, get) {
882   auto *N =
883       MDBasicType::get(Context, dwarf::DW_TAG_base_type, "special", 33, 26, 7);
884   EXPECT_EQ(dwarf::DW_TAG_base_type, N->getTag());
885   EXPECT_EQ("special", N->getName());
886   EXPECT_EQ(33u, N->getSizeInBits());
887   EXPECT_EQ(26u, N->getAlignInBits());
888   EXPECT_EQ(7u, N->getEncoding());
889   EXPECT_EQ(0u, N->getLine());
890   EXPECT_EQ(N, MDBasicType::get(Context, dwarf::DW_TAG_base_type, "special", 33,
891                                 26, 7));
892
893   EXPECT_NE(N, MDBasicType::get(Context, dwarf::DW_TAG_unspecified_type,
894                                 "special", 33, 26, 7));
895   EXPECT_NE(N,
896             MDBasicType::get(Context, dwarf::DW_TAG_base_type, "s", 33, 26, 7));
897   EXPECT_NE(N, MDBasicType::get(Context, dwarf::DW_TAG_base_type, "special", 32,
898                                 26, 7));
899   EXPECT_NE(N, MDBasicType::get(Context, dwarf::DW_TAG_base_type, "special", 33,
900                                 25, 7));
901   EXPECT_NE(N, MDBasicType::get(Context, dwarf::DW_TAG_base_type, "special", 33,
902                                 26, 6));
903
904   TempMDBasicType Temp = N->clone();
905   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
906 }
907
908 TEST_F(MDBasicTypeTest, getWithLargeValues) {
909   auto *N = MDBasicType::get(Context, dwarf::DW_TAG_base_type, "special",
910                              UINT64_MAX, UINT64_MAX - 1, 7);
911   EXPECT_EQ(UINT64_MAX, N->getSizeInBits());
912   EXPECT_EQ(UINT64_MAX - 1, N->getAlignInBits());
913 }
914
915 TEST_F(MDBasicTypeTest, getUnspecified) {
916   auto *N =
917       MDBasicType::get(Context, dwarf::DW_TAG_unspecified_type, "unspecified");
918   EXPECT_EQ(dwarf::DW_TAG_unspecified_type, N->getTag());
919   EXPECT_EQ("unspecified", N->getName());
920   EXPECT_EQ(0u, N->getSizeInBits());
921   EXPECT_EQ(0u, N->getAlignInBits());
922   EXPECT_EQ(0u, N->getEncoding());
923   EXPECT_EQ(0u, N->getLine());
924 }
925
926 typedef MetadataTest MDTypeTest;
927
928 TEST_F(MDTypeTest, clone) {
929   // Check that MDType has a specialized clone that returns TempMDType.
930   MDType *N = MDBasicType::get(Context, dwarf::DW_TAG_base_type, "int", 32, 32,
931                                dwarf::DW_ATE_signed);
932
933   TempMDType Temp = N->clone();
934   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
935 }
936
937 TEST_F(MDTypeTest, setFlags) {
938   // void (void)
939   Metadata *TypesOps[] = {nullptr};
940   Metadata *Types = MDTuple::get(Context, TypesOps);
941
942   MDType *D = MDSubroutineType::getDistinct(Context, 0u, Types);
943   EXPECT_EQ(0u, D->getFlags());
944   D->setFlags(DIDescriptor::FlagRValueReference);
945   EXPECT_EQ(DIDescriptor::FlagRValueReference, D->getFlags());
946   D->setFlags(0u);
947   EXPECT_EQ(0u, D->getFlags());
948
949   TempMDType T = MDSubroutineType::getTemporary(Context, 0u, Types);
950   EXPECT_EQ(0u, T->getFlags());
951   T->setFlags(DIDescriptor::FlagRValueReference);
952   EXPECT_EQ(DIDescriptor::FlagRValueReference, T->getFlags());
953   T->setFlags(0u);
954   EXPECT_EQ(0u, T->getFlags());
955 }
956
957 typedef MetadataTest MDDerivedTypeTest;
958
959 TEST_F(MDDerivedTypeTest, get) {
960   MDFile *File = getFile();
961   MDScope *Scope = getSubprogram();
962   MDType *BaseType = getBasicType("basic");
963   MDTuple *ExtraData = getTuple();
964
965   auto *N = MDDerivedType::get(Context, dwarf::DW_TAG_pointer_type, "something",
966                                File, 1, Scope, BaseType, 2, 3, 4, 5, ExtraData);
967   EXPECT_EQ(dwarf::DW_TAG_pointer_type, N->getTag());
968   EXPECT_EQ("something", N->getName());
969   EXPECT_EQ(File, N->getFile());
970   EXPECT_EQ(1u, N->getLine());
971   EXPECT_EQ(Scope, N->getScope());
972   EXPECT_EQ(BaseType, N->getBaseType());
973   EXPECT_EQ(2u, N->getSizeInBits());
974   EXPECT_EQ(3u, N->getAlignInBits());
975   EXPECT_EQ(4u, N->getOffsetInBits());
976   EXPECT_EQ(5u, N->getFlags());
977   EXPECT_EQ(ExtraData, N->getExtraData());
978   EXPECT_EQ(N, MDDerivedType::get(Context, dwarf::DW_TAG_pointer_type,
979                                   "something", File, 1, Scope, BaseType, 2, 3,
980                                   4, 5, ExtraData));
981
982   EXPECT_NE(N, MDDerivedType::get(Context, dwarf::DW_TAG_reference_type,
983                                   "something", File, 1, Scope, BaseType, 2, 3,
984                                   4, 5, ExtraData));
985   EXPECT_NE(N, MDDerivedType::get(Context, dwarf::DW_TAG_pointer_type, "else",
986                                   File, 1, Scope, BaseType, 2, 3, 4, 5,
987                                   ExtraData));
988   EXPECT_NE(N, MDDerivedType::get(Context, dwarf::DW_TAG_pointer_type,
989                                   "something", getFile(), 1, Scope, BaseType, 2,
990                                   3, 4, 5, ExtraData));
991   EXPECT_NE(N, MDDerivedType::get(Context, dwarf::DW_TAG_pointer_type,
992                                   "something", File, 2, Scope, BaseType, 2, 3,
993                                   4, 5, ExtraData));
994   EXPECT_NE(N, MDDerivedType::get(Context, dwarf::DW_TAG_pointer_type,
995                                   "something", File, 1, getSubprogram(),
996                                   BaseType, 2, 3, 4, 5, ExtraData));
997   EXPECT_NE(N, MDDerivedType::get(
998                    Context, dwarf::DW_TAG_pointer_type, "something", File, 1,
999                    Scope, getBasicType("basic2"), 2, 3, 4, 5, ExtraData));
1000   EXPECT_NE(N, MDDerivedType::get(Context, dwarf::DW_TAG_pointer_type,
1001                                   "something", File, 1, Scope, BaseType, 3, 3,
1002                                   4, 5, ExtraData));
1003   EXPECT_NE(N, MDDerivedType::get(Context, dwarf::DW_TAG_pointer_type,
1004                                   "something", File, 1, Scope, BaseType, 2, 2,
1005                                   4, 5, ExtraData));
1006   EXPECT_NE(N, MDDerivedType::get(Context, dwarf::DW_TAG_pointer_type,
1007                                   "something", File, 1, Scope, BaseType, 2, 3,
1008                                   5, 5, ExtraData));
1009   EXPECT_NE(N, MDDerivedType::get(Context, dwarf::DW_TAG_pointer_type,
1010                                   "something", File, 1, Scope, BaseType, 2, 3,
1011                                   4, 4, ExtraData));
1012   EXPECT_NE(N, MDDerivedType::get(Context, dwarf::DW_TAG_pointer_type,
1013                                   "something", File, 1, Scope, BaseType, 2, 3,
1014                                   4, 5, getTuple()));
1015
1016   TempMDDerivedType Temp = N->clone();
1017   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1018 }
1019
1020 TEST_F(MDDerivedTypeTest, getWithLargeValues) {
1021   MDFile *File = getFile();
1022   MDScope *Scope = getSubprogram();
1023   MDType *BaseType = getBasicType("basic");
1024   MDTuple *ExtraData = getTuple();
1025
1026   auto *N = MDDerivedType::get(Context, dwarf::DW_TAG_pointer_type, "something",
1027                                File, 1, Scope, BaseType, UINT64_MAX,
1028                                UINT64_MAX - 1, UINT64_MAX - 2, 5, ExtraData);
1029   EXPECT_EQ(UINT64_MAX, N->getSizeInBits());
1030   EXPECT_EQ(UINT64_MAX - 1, N->getAlignInBits());
1031   EXPECT_EQ(UINT64_MAX - 2, N->getOffsetInBits());
1032 }
1033
1034 typedef MetadataTest MDCompositeTypeTest;
1035
1036 TEST_F(MDCompositeTypeTest, get) {
1037   unsigned Tag = dwarf::DW_TAG_structure_type;
1038   StringRef Name = "some name";
1039   MDFile *File = getFile();
1040   unsigned Line = 1;
1041   MDScope *Scope = getSubprogram();
1042   MDType *BaseType = getCompositeType();
1043   uint64_t SizeInBits = 2;
1044   uint64_t AlignInBits = 3;
1045   uint64_t OffsetInBits = 4;
1046   unsigned Flags = 5;
1047   MDTuple *Elements = getTuple();
1048   unsigned RuntimeLang = 6;
1049   MDType *VTableHolder = getCompositeType();
1050   MDTuple *TemplateParams = getTuple();
1051   StringRef Identifier = "some id";
1052
1053   auto *N = MDCompositeType::get(Context, Tag, Name, File, Line, Scope,
1054                                  BaseType, SizeInBits, AlignInBits,
1055                                  OffsetInBits, Flags, Elements, RuntimeLang,
1056                                  VTableHolder, TemplateParams, Identifier);
1057   EXPECT_EQ(Tag, N->getTag());
1058   EXPECT_EQ(Name, N->getName());
1059   EXPECT_EQ(File, N->getFile());
1060   EXPECT_EQ(Line, N->getLine());
1061   EXPECT_EQ(Scope, N->getScope());
1062   EXPECT_EQ(BaseType, N->getBaseType());
1063   EXPECT_EQ(SizeInBits, N->getSizeInBits());
1064   EXPECT_EQ(AlignInBits, N->getAlignInBits());
1065   EXPECT_EQ(OffsetInBits, N->getOffsetInBits());
1066   EXPECT_EQ(Flags, N->getFlags());
1067   EXPECT_EQ(Elements, N->getElements());
1068   EXPECT_EQ(RuntimeLang, N->getRuntimeLang());
1069   EXPECT_EQ(VTableHolder, N->getVTableHolder());
1070   EXPECT_EQ(TemplateParams, N->getTemplateParams());
1071   EXPECT_EQ(Identifier, N->getIdentifier());
1072
1073   EXPECT_EQ(N, MDCompositeType::get(Context, Tag, Name, File, Line, Scope,
1074                                     BaseType, SizeInBits, AlignInBits,
1075                                     OffsetInBits, Flags, Elements, RuntimeLang,
1076                                     VTableHolder, TemplateParams, Identifier));
1077
1078   EXPECT_NE(N, MDCompositeType::get(Context, Tag + 1, Name, File, Line, Scope,
1079                                     BaseType, SizeInBits, AlignInBits,
1080                                     OffsetInBits, Flags, Elements, RuntimeLang,
1081                                     VTableHolder, TemplateParams, Identifier));
1082   EXPECT_NE(N, MDCompositeType::get(Context, Tag, "abc", File, Line, Scope,
1083                                     BaseType, SizeInBits, AlignInBits,
1084                                     OffsetInBits, Flags, Elements, RuntimeLang,
1085                                     VTableHolder, TemplateParams, Identifier));
1086   EXPECT_NE(N, MDCompositeType::get(Context, Tag, Name, getFile(), Line, Scope,
1087                                     BaseType, SizeInBits, AlignInBits,
1088                                     OffsetInBits, Flags, Elements, RuntimeLang,
1089                                     VTableHolder, TemplateParams, Identifier));
1090   EXPECT_NE(N, MDCompositeType::get(Context, Tag, Name, File, Line + 1, Scope,
1091                                     BaseType, SizeInBits, AlignInBits,
1092                                     OffsetInBits, Flags, Elements, RuntimeLang,
1093                                     VTableHolder, TemplateParams, Identifier));
1094   EXPECT_NE(N, MDCompositeType::get(
1095                    Context, Tag, Name, File, Line, getSubprogram(), BaseType,
1096                    SizeInBits, AlignInBits, OffsetInBits, Flags, Elements,
1097                    RuntimeLang, VTableHolder, TemplateParams, Identifier));
1098   EXPECT_NE(N, MDCompositeType::get(Context, Tag, Name, File, Line, Scope, File,
1099                                     SizeInBits, AlignInBits, OffsetInBits,
1100                                     Flags, Elements, RuntimeLang, VTableHolder,
1101                                     TemplateParams, Identifier));
1102   EXPECT_NE(N, MDCompositeType::get(Context, Tag, Name, File, Line, Scope,
1103                                     BaseType, SizeInBits + 1, AlignInBits,
1104                                     OffsetInBits, Flags, Elements, RuntimeLang,
1105                                     VTableHolder, TemplateParams, Identifier));
1106   EXPECT_NE(N, MDCompositeType::get(Context, Tag, Name, File, Line, Scope,
1107                                     BaseType, SizeInBits, AlignInBits + 1,
1108                                     OffsetInBits, Flags, Elements, RuntimeLang,
1109                                     VTableHolder, TemplateParams, Identifier));
1110   EXPECT_NE(N, MDCompositeType::get(
1111                    Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
1112                    AlignInBits, OffsetInBits + 1, Flags, Elements, RuntimeLang,
1113                    VTableHolder, TemplateParams, Identifier));
1114   EXPECT_NE(N, MDCompositeType::get(
1115                    Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
1116                    AlignInBits, OffsetInBits, Flags + 1, Elements, RuntimeLang,
1117                    VTableHolder, TemplateParams, Identifier));
1118   EXPECT_NE(N, MDCompositeType::get(
1119                    Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
1120                    AlignInBits, OffsetInBits, Flags, getTuple(), RuntimeLang,
1121                    VTableHolder, TemplateParams, Identifier));
1122   EXPECT_NE(N, MDCompositeType::get(
1123                    Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
1124                    AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang + 1,
1125                    VTableHolder, TemplateParams, Identifier));
1126   EXPECT_NE(N, MDCompositeType::get(
1127                    Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
1128                    AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
1129                    getCompositeType(), TemplateParams, Identifier));
1130   EXPECT_NE(N, MDCompositeType::get(Context, Tag, Name, File, Line, Scope,
1131                                     BaseType, SizeInBits, AlignInBits,
1132                                     OffsetInBits, Flags, Elements, RuntimeLang,
1133                                     VTableHolder, getTuple(), Identifier));
1134   EXPECT_NE(N, MDCompositeType::get(Context, Tag, Name, File, Line, Scope,
1135                                     BaseType, SizeInBits, AlignInBits,
1136                                     OffsetInBits, Flags, Elements, RuntimeLang,
1137                                     VTableHolder, TemplateParams, "other"));
1138
1139   // Be sure that missing identifiers get null pointers.
1140   EXPECT_FALSE(MDCompositeType::get(
1141                    Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
1142                    AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
1143                    VTableHolder, TemplateParams, "")->getRawIdentifier());
1144   EXPECT_FALSE(MDCompositeType::get(
1145                    Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
1146                    AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
1147                    VTableHolder, TemplateParams)->getRawIdentifier());
1148
1149   TempMDCompositeType Temp = N->clone();
1150   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1151 }
1152
1153 TEST_F(MDCompositeTypeTest, getWithLargeValues) {
1154   unsigned Tag = dwarf::DW_TAG_structure_type;
1155   StringRef Name = "some name";
1156   MDFile *File = getFile();
1157   unsigned Line = 1;
1158   MDScope *Scope = getSubprogram();
1159   MDType *BaseType = getCompositeType();
1160   uint64_t SizeInBits = UINT64_MAX;
1161   uint64_t AlignInBits = UINT64_MAX - 1;
1162   uint64_t OffsetInBits = UINT64_MAX - 2;
1163   unsigned Flags = 5;
1164   MDTuple *Elements = getTuple();
1165   unsigned RuntimeLang = 6;
1166   MDType *VTableHolder = getCompositeType();
1167   MDTuple *TemplateParams = getTuple();
1168   StringRef Identifier = "some id";
1169
1170   auto *N = MDCompositeType::get(Context, Tag, Name, File, Line, Scope,
1171                                  BaseType, SizeInBits, AlignInBits,
1172                                  OffsetInBits, Flags, Elements, RuntimeLang,
1173                                  VTableHolder, TemplateParams, Identifier);
1174   EXPECT_EQ(SizeInBits, N->getSizeInBits());
1175   EXPECT_EQ(AlignInBits, N->getAlignInBits());
1176   EXPECT_EQ(OffsetInBits, N->getOffsetInBits());
1177 }
1178
1179 TEST_F(MDCompositeTypeTest, replaceOperands) {
1180   unsigned Tag = dwarf::DW_TAG_structure_type;
1181   StringRef Name = "some name";
1182   MDFile *File = getFile();
1183   unsigned Line = 1;
1184   MDScope *Scope = getSubprogram();
1185   MDType *BaseType = getCompositeType();
1186   uint64_t SizeInBits = 2;
1187   uint64_t AlignInBits = 3;
1188   uint64_t OffsetInBits = 4;
1189   unsigned Flags = 5;
1190   unsigned RuntimeLang = 6;
1191   StringRef Identifier = "some id";
1192
1193   auto *N = MDCompositeType::get(Context, Tag, Name, File, Line, Scope,
1194                                  BaseType, SizeInBits, AlignInBits,
1195                                  OffsetInBits, Flags, nullptr, RuntimeLang,
1196                                  nullptr, nullptr, Identifier);
1197
1198   auto *Elements = MDTuple::getDistinct(Context, None);
1199   EXPECT_EQ(nullptr, N->getElements());
1200   N->replaceElements(Elements);
1201   EXPECT_EQ(Elements, N->getElements());
1202   N->replaceElements(nullptr);
1203   EXPECT_EQ(nullptr, N->getElements());
1204
1205   auto *VTableHolder = MDTuple::getDistinct(Context, None);
1206   EXPECT_EQ(nullptr, N->getVTableHolder());
1207   N->replaceVTableHolder(VTableHolder);
1208   EXPECT_EQ(VTableHolder, N->getVTableHolder());
1209   N->replaceVTableHolder(nullptr);
1210   EXPECT_EQ(nullptr, N->getVTableHolder());
1211
1212   auto *TemplateParams = MDTuple::getDistinct(Context, None);
1213   EXPECT_EQ(nullptr, N->getTemplateParams());
1214   N->replaceTemplateParams(TemplateParams);
1215   EXPECT_EQ(TemplateParams, N->getTemplateParams());
1216   N->replaceTemplateParams(nullptr);
1217   EXPECT_EQ(nullptr, N->getTemplateParams());
1218 }
1219
1220 typedef MetadataTest MDSubroutineTypeTest;
1221
1222 TEST_F(MDSubroutineTypeTest, get) {
1223   unsigned Flags = 1;
1224   MDTuple *TypeArray = getTuple();
1225
1226   auto *N = MDSubroutineType::get(Context, Flags, TypeArray);
1227   EXPECT_EQ(dwarf::DW_TAG_subroutine_type, N->getTag());
1228   EXPECT_EQ(Flags, N->getFlags());
1229   EXPECT_EQ(TypeArray, N->getTypeArray());
1230   EXPECT_EQ(N, MDSubroutineType::get(Context, Flags, TypeArray));
1231
1232   EXPECT_NE(N, MDSubroutineType::get(Context, Flags + 1, TypeArray));
1233   EXPECT_NE(N, MDSubroutineType::get(Context, Flags, getTuple()));
1234
1235   TempMDSubroutineType Temp = N->clone();
1236   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1237
1238   // Test always-empty operands.
1239   EXPECT_EQ(nullptr, N->getScope());
1240   EXPECT_EQ(nullptr, N->getFile());
1241   EXPECT_EQ("", N->getName());
1242   EXPECT_EQ(nullptr, N->getBaseType());
1243   EXPECT_EQ(nullptr, N->getVTableHolder());
1244   EXPECT_EQ(nullptr, N->getTemplateParams());
1245   EXPECT_EQ("", N->getIdentifier());
1246 }
1247
1248 typedef MetadataTest MDFileTest;
1249
1250 TEST_F(MDFileTest, get) {
1251   StringRef Filename = "file";
1252   StringRef Directory = "dir";
1253   auto *N = MDFile::get(Context, Filename, Directory);
1254
1255   EXPECT_EQ(dwarf::DW_TAG_file_type, N->getTag());
1256   EXPECT_EQ(Filename, N->getFilename());
1257   EXPECT_EQ(Directory, N->getDirectory());
1258   EXPECT_EQ(N, MDFile::get(Context, Filename, Directory));
1259
1260   EXPECT_NE(N, MDFile::get(Context, "other", Directory));
1261   EXPECT_NE(N, MDFile::get(Context, Filename, "other"));
1262
1263   TempMDFile Temp = N->clone();
1264   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1265 }
1266
1267 TEST_F(MDFileTest, ScopeGetFile) {
1268   // Ensure that MDScope::getFile() returns itself.
1269   MDScope *N = MDFile::get(Context, "file", "dir");
1270   EXPECT_EQ(N, N->getFile());
1271 }
1272
1273 typedef MetadataTest MDCompileUnitTest;
1274
1275 TEST_F(MDCompileUnitTest, get) {
1276   unsigned SourceLanguage = 1;
1277   MDFile *File = getFile();
1278   StringRef Producer = "some producer";
1279   bool IsOptimized = false;
1280   StringRef Flags = "flag after flag";
1281   unsigned RuntimeVersion = 2;
1282   StringRef SplitDebugFilename = "another/file";
1283   unsigned EmissionKind = 3;
1284   MDTuple *EnumTypes = getTuple();
1285   MDTuple *RetainedTypes = getTuple();
1286   MDTuple *Subprograms = getTuple();
1287   MDTuple *GlobalVariables = getTuple();
1288   MDTuple *ImportedEntities = getTuple();
1289   auto *N = MDCompileUnit::get(
1290       Context, SourceLanguage, File, Producer, IsOptimized, Flags,
1291       RuntimeVersion, SplitDebugFilename, EmissionKind, EnumTypes,
1292       RetainedTypes, Subprograms, GlobalVariables, ImportedEntities);
1293
1294   EXPECT_EQ(dwarf::DW_TAG_compile_unit, N->getTag());
1295   EXPECT_EQ(SourceLanguage, N->getSourceLanguage());
1296   EXPECT_EQ(File, N->getFile());
1297   EXPECT_EQ(Producer, N->getProducer());
1298   EXPECT_EQ(IsOptimized, N->isOptimized());
1299   EXPECT_EQ(Flags, N->getFlags());
1300   EXPECT_EQ(RuntimeVersion, N->getRuntimeVersion());
1301   EXPECT_EQ(SplitDebugFilename, N->getSplitDebugFilename());
1302   EXPECT_EQ(EmissionKind, N->getEmissionKind());
1303   EXPECT_EQ(EnumTypes, N->getEnumTypes());
1304   EXPECT_EQ(RetainedTypes, N->getRetainedTypes());
1305   EXPECT_EQ(Subprograms, N->getSubprograms());
1306   EXPECT_EQ(GlobalVariables, N->getGlobalVariables());
1307   EXPECT_EQ(ImportedEntities, N->getImportedEntities());
1308   EXPECT_EQ(N, MDCompileUnit::get(Context, SourceLanguage, File, Producer,
1309                                   IsOptimized, Flags, RuntimeVersion,
1310                                   SplitDebugFilename, EmissionKind, EnumTypes,
1311                                   RetainedTypes, Subprograms, GlobalVariables,
1312                                   ImportedEntities));
1313
1314   EXPECT_NE(N, MDCompileUnit::get(Context, SourceLanguage + 1, File, Producer,
1315                                   IsOptimized, Flags, RuntimeVersion,
1316                                   SplitDebugFilename, EmissionKind, EnumTypes,
1317                                   RetainedTypes, Subprograms, GlobalVariables,
1318                                   ImportedEntities));
1319   EXPECT_NE(N, MDCompileUnit::get(Context, SourceLanguage, getFile(), Producer,
1320                                   IsOptimized, Flags, RuntimeVersion,
1321                                   SplitDebugFilename, EmissionKind, EnumTypes,
1322                                   RetainedTypes, Subprograms, GlobalVariables,
1323                                   ImportedEntities));
1324   EXPECT_NE(N, MDCompileUnit::get(Context, SourceLanguage, File, "other",
1325                                   IsOptimized, Flags, RuntimeVersion,
1326                                   SplitDebugFilename, EmissionKind, EnumTypes,
1327                                   RetainedTypes, Subprograms, GlobalVariables,
1328                                   ImportedEntities));
1329   EXPECT_NE(N, MDCompileUnit::get(Context, SourceLanguage, File, Producer,
1330                                   !IsOptimized, Flags, RuntimeVersion,
1331                                   SplitDebugFilename, EmissionKind, EnumTypes,
1332                                   RetainedTypes, Subprograms, GlobalVariables,
1333                                   ImportedEntities));
1334   EXPECT_NE(N, MDCompileUnit::get(Context, SourceLanguage, File, Producer,
1335                                   IsOptimized, "other", RuntimeVersion,
1336                                   SplitDebugFilename, EmissionKind, EnumTypes,
1337                                   RetainedTypes, Subprograms, GlobalVariables,
1338                                   ImportedEntities));
1339   EXPECT_NE(N, MDCompileUnit::get(Context, SourceLanguage, File, Producer,
1340                                   IsOptimized, Flags, RuntimeVersion + 1,
1341                                   SplitDebugFilename, EmissionKind, EnumTypes,
1342                                   RetainedTypes, Subprograms, GlobalVariables,
1343                                   ImportedEntities));
1344   EXPECT_NE(N,
1345             MDCompileUnit::get(Context, SourceLanguage, File, Producer,
1346                                IsOptimized, Flags, RuntimeVersion, "other",
1347                                EmissionKind, EnumTypes, RetainedTypes,
1348                                Subprograms, GlobalVariables, ImportedEntities));
1349   EXPECT_NE(N, MDCompileUnit::get(Context, SourceLanguage, File, Producer,
1350                                   IsOptimized, Flags, RuntimeVersion,
1351                                   SplitDebugFilename, EmissionKind + 1,
1352                                   EnumTypes, RetainedTypes, Subprograms,
1353                                   GlobalVariables, ImportedEntities));
1354   EXPECT_NE(N, MDCompileUnit::get(Context, SourceLanguage, File, Producer,
1355                                   IsOptimized, Flags, RuntimeVersion,
1356                                   SplitDebugFilename, EmissionKind, getTuple(),
1357                                   RetainedTypes, Subprograms, GlobalVariables,
1358                                   ImportedEntities));
1359   EXPECT_NE(N, MDCompileUnit::get(
1360                    Context, SourceLanguage, File, Producer, IsOptimized, Flags,
1361                    RuntimeVersion, SplitDebugFilename, EmissionKind, EnumTypes,
1362                    getTuple(), Subprograms, GlobalVariables, ImportedEntities));
1363   EXPECT_NE(N, MDCompileUnit::get(Context, SourceLanguage, File, Producer,
1364                                   IsOptimized, Flags, RuntimeVersion,
1365                                   SplitDebugFilename, EmissionKind, EnumTypes,
1366                                   RetainedTypes, getTuple(), GlobalVariables,
1367                                   ImportedEntities));
1368   EXPECT_NE(N, MDCompileUnit::get(
1369                    Context, SourceLanguage, File, Producer, IsOptimized, Flags,
1370                    RuntimeVersion, SplitDebugFilename, EmissionKind, EnumTypes,
1371                    RetainedTypes, Subprograms, getTuple(), ImportedEntities));
1372   EXPECT_NE(N, MDCompileUnit::get(
1373                    Context, SourceLanguage, File, Producer, IsOptimized, Flags,
1374                    RuntimeVersion, SplitDebugFilename, EmissionKind, EnumTypes,
1375                    RetainedTypes, Subprograms, GlobalVariables, getTuple()));
1376
1377   TempMDCompileUnit Temp = N->clone();
1378   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1379 }
1380
1381 TEST_F(MDCompileUnitTest, replaceArrays) {
1382   unsigned SourceLanguage = 1;
1383   MDFile *File = getFile();
1384   StringRef Producer = "some producer";
1385   bool IsOptimized = false;
1386   StringRef Flags = "flag after flag";
1387   unsigned RuntimeVersion = 2;
1388   StringRef SplitDebugFilename = "another/file";
1389   unsigned EmissionKind = 3;
1390   MDTuple *EnumTypes = MDTuple::getDistinct(Context, None);
1391   MDTuple *RetainedTypes = MDTuple::getDistinct(Context, None);
1392   MDTuple *ImportedEntities = MDTuple::getDistinct(Context, None);
1393   auto *N = MDCompileUnit::get(
1394       Context, SourceLanguage, File, Producer, IsOptimized, Flags,
1395       RuntimeVersion, SplitDebugFilename, EmissionKind, EnumTypes,
1396       RetainedTypes, nullptr, nullptr, ImportedEntities);
1397
1398   auto *Subprograms = MDTuple::getDistinct(Context, None);
1399   EXPECT_EQ(nullptr, N->getSubprograms());
1400   N->replaceSubprograms(Subprograms);
1401   EXPECT_EQ(Subprograms, N->getSubprograms());
1402   N->replaceSubprograms(nullptr);
1403   EXPECT_EQ(nullptr, N->getSubprograms());
1404
1405   auto *GlobalVariables = MDTuple::getDistinct(Context, None);
1406   EXPECT_EQ(nullptr, N->getGlobalVariables());
1407   N->replaceGlobalVariables(GlobalVariables);
1408   EXPECT_EQ(GlobalVariables, N->getGlobalVariables());
1409   N->replaceGlobalVariables(nullptr);
1410   EXPECT_EQ(nullptr, N->getGlobalVariables());
1411 }
1412
1413 typedef MetadataTest MDSubprogramTest;
1414
1415 TEST_F(MDSubprogramTest, get) {
1416   MDScope *Scope = getCompositeType();
1417   StringRef Name = "name";
1418   StringRef LinkageName = "linkage";
1419   MDFile *File = getFile();
1420   unsigned Line = 2;
1421   MDSubroutineType *Type = getSubroutineType();
1422   bool IsLocalToUnit = false;
1423   bool IsDefinition = true;
1424   unsigned ScopeLine = 3;
1425   MDType *ContainingType = getCompositeType();
1426   unsigned Virtuality = 4;
1427   unsigned VirtualIndex = 5;
1428   unsigned Flags = 6;
1429   bool IsOptimized = false;
1430   ConstantAsMetadata *Function = getFunctionAsMetadata("foo");
1431   MDTuple *TemplateParams = getTuple();
1432   MDSubprogram *Declaration = getSubprogram();
1433   MDTuple *Variables = getTuple();
1434
1435   auto *N = MDSubprogram::get(
1436       Context, Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit,
1437       IsDefinition, ScopeLine, ContainingType, Virtuality, VirtualIndex, Flags,
1438       IsOptimized, Function, TemplateParams, Declaration, Variables);
1439
1440   EXPECT_EQ(dwarf::DW_TAG_subprogram, N->getTag());
1441   EXPECT_EQ(Scope, N->getScope());
1442   EXPECT_EQ(Name, N->getName());
1443   EXPECT_EQ(LinkageName, N->getLinkageName());
1444   EXPECT_EQ(File, N->getFile());
1445   EXPECT_EQ(Line, N->getLine());
1446   EXPECT_EQ(Type, N->getType());
1447   EXPECT_EQ(IsLocalToUnit, N->isLocalToUnit());
1448   EXPECT_EQ(IsDefinition, N->isDefinition());
1449   EXPECT_EQ(ScopeLine, N->getScopeLine());
1450   EXPECT_EQ(ContainingType, N->getContainingType());
1451   EXPECT_EQ(Virtuality, N->getVirtuality());
1452   EXPECT_EQ(VirtualIndex, N->getVirtualIndex());
1453   EXPECT_EQ(Flags, N->getFlags());
1454   EXPECT_EQ(IsOptimized, N->isOptimized());
1455   EXPECT_EQ(Function, N->getFunction());
1456   EXPECT_EQ(TemplateParams, N->getTemplateParams());
1457   EXPECT_EQ(Declaration, N->getDeclaration());
1458   EXPECT_EQ(Variables, N->getVariables());
1459   EXPECT_EQ(N, MDSubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1460                                  Type, IsLocalToUnit, IsDefinition, ScopeLine,
1461                                  ContainingType, Virtuality, VirtualIndex,
1462                                  Flags, IsOptimized, Function, TemplateParams,
1463                                  Declaration, Variables));
1464
1465   EXPECT_NE(N, MDSubprogram::get(Context, getCompositeType(), Name, LinkageName,
1466                                  File, Line, Type, IsLocalToUnit, IsDefinition,
1467                                  ScopeLine, ContainingType, Virtuality,
1468                                  VirtualIndex, Flags, IsOptimized, Function,
1469                                  TemplateParams, Declaration, Variables));
1470   EXPECT_NE(N, MDSubprogram::get(Context, Scope, "other", LinkageName, File,
1471                                  Line, Type, IsLocalToUnit, IsDefinition,
1472                                  ScopeLine, ContainingType, Virtuality,
1473                                  VirtualIndex, Flags, IsOptimized, Function,
1474                                  TemplateParams, Declaration, Variables));
1475   EXPECT_NE(N, MDSubprogram::get(Context, Scope, Name, "other", File, Line,
1476                                  Type, IsLocalToUnit, IsDefinition, ScopeLine,
1477                                  ContainingType, Virtuality, VirtualIndex,
1478                                  Flags, IsOptimized, Function, TemplateParams,
1479                                  Declaration, Variables));
1480   EXPECT_NE(N, MDSubprogram::get(Context, Scope, Name, LinkageName, getFile(),
1481                                  Line, Type, IsLocalToUnit, IsDefinition,
1482                                  ScopeLine, ContainingType, Virtuality,
1483                                  VirtualIndex, Flags, IsOptimized, Function,
1484                                  TemplateParams, Declaration, Variables));
1485   EXPECT_NE(N, MDSubprogram::get(Context, Scope, Name, LinkageName, File,
1486                                  Line + 1, Type, IsLocalToUnit, IsDefinition,
1487                                  ScopeLine, ContainingType, Virtuality,
1488                                  VirtualIndex, Flags, IsOptimized, Function,
1489                                  TemplateParams, Declaration, Variables));
1490   EXPECT_NE(N, MDSubprogram::get(
1491                    Context, Scope, Name, LinkageName, File, Line,
1492                    getSubroutineType(), IsLocalToUnit, IsDefinition, ScopeLine,
1493                    ContainingType, Virtuality, VirtualIndex, Flags, IsOptimized,
1494                    Function, TemplateParams, Declaration, Variables));
1495   EXPECT_NE(N, MDSubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1496                                  Type, !IsLocalToUnit, IsDefinition, ScopeLine,
1497                                  ContainingType, Virtuality, VirtualIndex,
1498                                  Flags, IsOptimized, Function, TemplateParams,
1499                                  Declaration, Variables));
1500   EXPECT_NE(N, MDSubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1501                                  Type, IsLocalToUnit, !IsDefinition, ScopeLine,
1502                                  ContainingType, Virtuality, VirtualIndex,
1503                                  Flags, IsOptimized, Function, TemplateParams,
1504                                  Declaration, Variables));
1505   EXPECT_NE(N, MDSubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1506                                  Type, IsLocalToUnit, IsDefinition,
1507                                  ScopeLine + 1, ContainingType, Virtuality,
1508                                  VirtualIndex, Flags, IsOptimized, Function,
1509                                  TemplateParams, Declaration, Variables));
1510   EXPECT_NE(N, MDSubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1511                                  Type, IsLocalToUnit, IsDefinition, ScopeLine,
1512                                  getCompositeType(), Virtuality, VirtualIndex,
1513                                  Flags, IsOptimized, Function, TemplateParams,
1514                                  Declaration, Variables));
1515   EXPECT_NE(N, MDSubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1516                                  Type, IsLocalToUnit, IsDefinition, ScopeLine,
1517                                  ContainingType, Virtuality + 1, VirtualIndex,
1518                                  Flags, IsOptimized, Function, TemplateParams,
1519                                  Declaration, Variables));
1520   EXPECT_NE(N, MDSubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1521                                  Type, IsLocalToUnit, IsDefinition, ScopeLine,
1522                                  ContainingType, Virtuality, VirtualIndex + 1,
1523                                  Flags, IsOptimized, Function, TemplateParams,
1524                                  Declaration, Variables));
1525   EXPECT_NE(N, MDSubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1526                                  Type, IsLocalToUnit, IsDefinition, ScopeLine,
1527                                  ContainingType, Virtuality, VirtualIndex,
1528                                  ~Flags, IsOptimized, Function, TemplateParams,
1529                                  Declaration, Variables));
1530   EXPECT_NE(N, MDSubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1531                                  Type, IsLocalToUnit, IsDefinition, ScopeLine,
1532                                  ContainingType, Virtuality, VirtualIndex,
1533                                  Flags, !IsOptimized, Function, TemplateParams,
1534                                  Declaration, Variables));
1535   EXPECT_NE(N,
1536             MDSubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1537                               Type, IsLocalToUnit, IsDefinition, ScopeLine,
1538                               ContainingType, Virtuality, VirtualIndex, Flags,
1539                               IsOptimized, getFunctionAsMetadata("bar"),
1540                               TemplateParams, Declaration, Variables));
1541   EXPECT_NE(N, MDSubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1542                                  Type, IsLocalToUnit, IsDefinition, ScopeLine,
1543                                  ContainingType, Virtuality, VirtualIndex,
1544                                  Flags, IsOptimized, Function, getTuple(),
1545                                  Declaration, Variables));
1546   EXPECT_NE(N, MDSubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1547                                  Type, IsLocalToUnit, IsDefinition, ScopeLine,
1548                                  ContainingType, Virtuality, VirtualIndex,
1549                                  Flags, IsOptimized, Function, TemplateParams,
1550                                  getSubprogram(), Variables));
1551   EXPECT_NE(N, MDSubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1552                                  Type, IsLocalToUnit, IsDefinition, ScopeLine,
1553                                  ContainingType, Virtuality, VirtualIndex,
1554                                  Flags, IsOptimized, Function, TemplateParams,
1555                                  Declaration, getTuple()));
1556
1557   TempMDSubprogram Temp = N->clone();
1558   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1559 }
1560
1561 TEST_F(MDSubprogramTest, replaceFunction) {
1562   MDScope *Scope = getCompositeType();
1563   StringRef Name = "name";
1564   StringRef LinkageName = "linkage";
1565   MDFile *File = getFile();
1566   unsigned Line = 2;
1567   MDSubroutineType *Type = getSubroutineType();
1568   bool IsLocalToUnit = false;
1569   bool IsDefinition = true;
1570   unsigned ScopeLine = 3;
1571   MDCompositeType *ContainingType = getCompositeType();
1572   unsigned Virtuality = 4;
1573   unsigned VirtualIndex = 5;
1574   unsigned Flags = 6;
1575   bool IsOptimized = false;
1576   MDTuple *TemplateParams = getTuple();
1577   MDSubprogram *Declaration = getSubprogram();
1578   MDTuple *Variables = getTuple();
1579
1580   auto *N = MDSubprogram::get(
1581       Context, Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit,
1582       IsDefinition, ScopeLine, ContainingType, Virtuality, VirtualIndex, Flags,
1583       IsOptimized, nullptr, TemplateParams, Declaration, Variables);
1584
1585   EXPECT_EQ(nullptr, N->getFunction());
1586
1587   std::unique_ptr<Function> F(
1588       Function::Create(FunctionType::get(Type::getVoidTy(Context), false),
1589                        GlobalValue::ExternalLinkage));
1590   N->replaceFunction(F.get());
1591   EXPECT_EQ(ConstantAsMetadata::get(F.get()), N->getFunction());
1592
1593   N->replaceFunction(nullptr);
1594   EXPECT_EQ(nullptr, N->getFunction());
1595 }
1596
1597 typedef MetadataTest MDLexicalBlockTest;
1598
1599 TEST_F(MDLexicalBlockTest, get) {
1600   MDLocalScope *Scope = getSubprogram();
1601   MDFile *File = getFile();
1602   unsigned Line = 5;
1603   unsigned Column = 8;
1604
1605   auto *N = MDLexicalBlock::get(Context, Scope, File, Line, Column);
1606
1607   EXPECT_EQ(dwarf::DW_TAG_lexical_block, N->getTag());
1608   EXPECT_EQ(Scope, N->getScope());
1609   EXPECT_EQ(File, N->getFile());
1610   EXPECT_EQ(Line, N->getLine());
1611   EXPECT_EQ(Column, N->getColumn());
1612   EXPECT_EQ(N, MDLexicalBlock::get(Context, Scope, File, Line, Column));
1613
1614   EXPECT_NE(N,
1615             MDLexicalBlock::get(Context, getSubprogram(), File, Line, Column));
1616   EXPECT_NE(N, MDLexicalBlock::get(Context, Scope, getFile(), Line, Column));
1617   EXPECT_NE(N, MDLexicalBlock::get(Context, Scope, File, Line + 1, Column));
1618   EXPECT_NE(N, MDLexicalBlock::get(Context, Scope, File, Line, Column + 1));
1619
1620   TempMDLexicalBlock Temp = N->clone();
1621   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1622 }
1623
1624 typedef MetadataTest MDLexicalBlockFileTest;
1625
1626 TEST_F(MDLexicalBlockFileTest, get) {
1627   MDLocalScope *Scope = getSubprogram();
1628   MDFile *File = getFile();
1629   unsigned Discriminator = 5;
1630
1631   auto *N = MDLexicalBlockFile::get(Context, Scope, File, Discriminator);
1632
1633   EXPECT_EQ(dwarf::DW_TAG_lexical_block, N->getTag());
1634   EXPECT_EQ(Scope, N->getScope());
1635   EXPECT_EQ(File, N->getFile());
1636   EXPECT_EQ(Discriminator, N->getDiscriminator());
1637   EXPECT_EQ(N, MDLexicalBlockFile::get(Context, Scope, File, Discriminator));
1638
1639   EXPECT_NE(N, MDLexicalBlockFile::get(Context, getSubprogram(), File,
1640                                        Discriminator));
1641   EXPECT_NE(N,
1642             MDLexicalBlockFile::get(Context, Scope, getFile(), Discriminator));
1643   EXPECT_NE(N,
1644             MDLexicalBlockFile::get(Context, Scope, File, Discriminator + 1));
1645
1646   TempMDLexicalBlockFile Temp = N->clone();
1647   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1648 }
1649
1650 typedef MetadataTest MDNamespaceTest;
1651
1652 TEST_F(MDNamespaceTest, get) {
1653   MDScope *Scope = getFile();
1654   MDFile *File = getFile();
1655   StringRef Name = "namespace";
1656   unsigned Line = 5;
1657
1658   auto *N = MDNamespace::get(Context, Scope, File, Name, Line);
1659
1660   EXPECT_EQ(dwarf::DW_TAG_namespace, N->getTag());
1661   EXPECT_EQ(Scope, N->getScope());
1662   EXPECT_EQ(File, N->getFile());
1663   EXPECT_EQ(Name, N->getName());
1664   EXPECT_EQ(Line, N->getLine());
1665   EXPECT_EQ(N, MDNamespace::get(Context, Scope, File, Name, Line));
1666
1667   EXPECT_NE(N, MDNamespace::get(Context, getFile(), File, Name, Line));
1668   EXPECT_NE(N, MDNamespace::get(Context, Scope, getFile(), Name, Line));
1669   EXPECT_NE(N, MDNamespace::get(Context, Scope, File, "other", Line));
1670   EXPECT_NE(N, MDNamespace::get(Context, Scope, File, Name, Line + 1));
1671
1672   TempMDNamespace Temp = N->clone();
1673   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1674 }
1675
1676 typedef MetadataTest MDTemplateTypeParameterTest;
1677
1678 TEST_F(MDTemplateTypeParameterTest, get) {
1679   StringRef Name = "template";
1680   MDType *Type = getBasicType("basic");
1681
1682   auto *N = MDTemplateTypeParameter::get(Context, Name, Type);
1683
1684   EXPECT_EQ(dwarf::DW_TAG_template_type_parameter, N->getTag());
1685   EXPECT_EQ(Name, N->getName());
1686   EXPECT_EQ(Type, N->getType());
1687   EXPECT_EQ(N, MDTemplateTypeParameter::get(Context, Name, Type));
1688
1689   EXPECT_NE(N, MDTemplateTypeParameter::get(Context, "other", Type));
1690   EXPECT_NE(N,
1691             MDTemplateTypeParameter::get(Context, Name, getBasicType("other")));
1692
1693   TempMDTemplateTypeParameter Temp = N->clone();
1694   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1695 }
1696
1697 typedef MetadataTest MDTemplateValueParameterTest;
1698
1699 TEST_F(MDTemplateValueParameterTest, get) {
1700   unsigned Tag = dwarf::DW_TAG_template_value_parameter;
1701   StringRef Name = "template";
1702   MDType *Type = getBasicType("basic");
1703   Metadata *Value = getConstantAsMetadata();
1704
1705   auto *N = MDTemplateValueParameter::get(Context, Tag, Name, Type, Value);
1706   EXPECT_EQ(Tag, N->getTag());
1707   EXPECT_EQ(Name, N->getName());
1708   EXPECT_EQ(Type, N->getType());
1709   EXPECT_EQ(Value, N->getValue());
1710   EXPECT_EQ(N, MDTemplateValueParameter::get(Context, Tag, Name, Type, Value));
1711
1712   EXPECT_NE(N, MDTemplateValueParameter::get(
1713                    Context, dwarf::DW_TAG_GNU_template_template_param, Name,
1714                    Type, Value));
1715   EXPECT_NE(N, MDTemplateValueParameter::get(Context, Tag,  "other", Type,
1716                                              Value));
1717   EXPECT_NE(N, MDTemplateValueParameter::get(Context, Tag, Name,
1718                                              getBasicType("other"), Value));
1719   EXPECT_NE(N, MDTemplateValueParameter::get(Context, Tag, Name, Type,
1720                                              getConstantAsMetadata()));
1721
1722   TempMDTemplateValueParameter Temp = N->clone();
1723   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1724 }
1725
1726 typedef MetadataTest MDGlobalVariableTest;
1727
1728 TEST_F(MDGlobalVariableTest, get) {
1729   MDScope *Scope = getSubprogram();
1730   StringRef Name = "name";
1731   StringRef LinkageName = "linkage";
1732   MDFile *File = getFile();
1733   unsigned Line = 5;
1734   Metadata *Type = MDTuple::getDistinct(Context, None);
1735   bool IsLocalToUnit = false;
1736   bool IsDefinition = true;
1737   ConstantAsMetadata *Variable = getConstantAsMetadata();
1738   MDDerivedType *StaticDataMemberDeclaration = getDerivedType();
1739
1740   auto *N = MDGlobalVariable::get(Context, Scope, Name, LinkageName, File, Line,
1741                                   Type, IsLocalToUnit, IsDefinition, Variable,
1742                                   StaticDataMemberDeclaration);
1743   EXPECT_EQ(dwarf::DW_TAG_variable, N->getTag());
1744   EXPECT_EQ(Scope, N->getScope());
1745   EXPECT_EQ(Name, N->getName());
1746   EXPECT_EQ(LinkageName, N->getLinkageName());
1747   EXPECT_EQ(File, N->getFile());
1748   EXPECT_EQ(Line, N->getLine());
1749   EXPECT_EQ(Type, N->getType());
1750   EXPECT_EQ(IsLocalToUnit, N->isLocalToUnit());
1751   EXPECT_EQ(IsDefinition, N->isDefinition());
1752   EXPECT_EQ(Variable, N->getVariable());
1753   EXPECT_EQ(StaticDataMemberDeclaration, N->getStaticDataMemberDeclaration());
1754   EXPECT_EQ(N, MDGlobalVariable::get(Context, Scope, Name, LinkageName, File,
1755                                      Line, Type, IsLocalToUnit, IsDefinition,
1756                                      Variable, StaticDataMemberDeclaration));
1757
1758   EXPECT_NE(N,
1759             MDGlobalVariable::get(Context, getSubprogram(), Name, LinkageName,
1760                                   File, Line, Type, IsLocalToUnit, IsDefinition,
1761                                   Variable, StaticDataMemberDeclaration));
1762   EXPECT_NE(N, MDGlobalVariable::get(Context, Scope, "other", LinkageName, File,
1763                                      Line, Type, IsLocalToUnit, IsDefinition,
1764                                      Variable, StaticDataMemberDeclaration));
1765   EXPECT_NE(N, MDGlobalVariable::get(Context, Scope, Name, "other", File, Line,
1766                                      Type, IsLocalToUnit, IsDefinition,
1767                                      Variable, StaticDataMemberDeclaration));
1768   EXPECT_NE(N,
1769             MDGlobalVariable::get(Context, Scope, Name, LinkageName, getFile(),
1770                                   Line, Type, IsLocalToUnit, IsDefinition,
1771                                   Variable, StaticDataMemberDeclaration));
1772   EXPECT_NE(N,
1773             MDGlobalVariable::get(Context, Scope, Name, LinkageName, File,
1774                                   Line + 1, Type, IsLocalToUnit, IsDefinition,
1775                                   Variable, StaticDataMemberDeclaration));
1776   EXPECT_NE(N, MDGlobalVariable::get(Context, Scope, Name, LinkageName, File,
1777                                      Line, Scope, IsLocalToUnit, IsDefinition,
1778                                      Variable, StaticDataMemberDeclaration));
1779   EXPECT_NE(N, MDGlobalVariable::get(Context, Scope, Name, LinkageName, File,
1780                                      Line, Type, !IsLocalToUnit, IsDefinition,
1781                                      Variable, StaticDataMemberDeclaration));
1782   EXPECT_NE(N, MDGlobalVariable::get(Context, Scope, Name, LinkageName, File,
1783                                      Line, Type, IsLocalToUnit, !IsDefinition,
1784                                      Variable, StaticDataMemberDeclaration));
1785   EXPECT_NE(N, MDGlobalVariable::get(Context, Scope, Name, LinkageName, File,
1786                                      Line, Type, IsLocalToUnit, IsDefinition,
1787                                      getConstantAsMetadata(),
1788                                      StaticDataMemberDeclaration));
1789   EXPECT_NE(N, MDGlobalVariable::get(Context, Scope, Name, LinkageName, File,
1790                                      Line, Type, IsLocalToUnit, IsDefinition,
1791                                      Variable, getDerivedType()));
1792
1793   TempMDGlobalVariable Temp = N->clone();
1794   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1795 }
1796
1797 typedef MetadataTest MDLocalVariableTest;
1798
1799 TEST_F(MDLocalVariableTest, get) {
1800   unsigned Tag = dwarf::DW_TAG_arg_variable;
1801   MDLocalScope *Scope = getSubprogram();
1802   StringRef Name = "name";
1803   MDFile *File = getFile();
1804   unsigned Line = 5;
1805   Metadata *Type = MDTuple::getDistinct(Context, None);
1806   unsigned Arg = 6;
1807   unsigned Flags = 7;
1808   MDLocation *InlinedAt =
1809       MDLocation::getDistinct(Context, 10, 20, getSubprogram());
1810
1811   auto *N = MDLocalVariable::get(Context, Tag, Scope, Name, File, Line, Type,
1812                                  Arg, Flags, InlinedAt);
1813   EXPECT_EQ(Tag, N->getTag());
1814   EXPECT_EQ(Scope, N->getScope());
1815   EXPECT_EQ(Name, N->getName());
1816   EXPECT_EQ(File, N->getFile());
1817   EXPECT_EQ(Line, N->getLine());
1818   EXPECT_EQ(Type, N->getType());
1819   EXPECT_EQ(Arg, N->getArg());
1820   EXPECT_EQ(Flags, N->getFlags());
1821   EXPECT_EQ(InlinedAt, N->getInlinedAt());
1822   EXPECT_EQ(N, MDLocalVariable::get(Context, Tag, Scope, Name, File, Line, Type,
1823                                     Arg, Flags, InlinedAt));
1824
1825   EXPECT_NE(N, MDLocalVariable::get(Context, dwarf::DW_TAG_auto_variable, Scope,
1826                                     Name, File, Line, Type, Arg, Flags,
1827                                     InlinedAt));
1828   EXPECT_NE(N, MDLocalVariable::get(Context, Tag, getSubprogram(), Name, File,
1829                                     Line, Type, Arg, Flags, InlinedAt));
1830   EXPECT_NE(N, MDLocalVariable::get(Context, Tag, Scope, "other", File, Line,
1831                                     Type, Arg, Flags, InlinedAt));
1832   EXPECT_NE(N, MDLocalVariable::get(Context, Tag, Scope, Name, getFile(), Line,
1833                                     Type, Arg, Flags, InlinedAt));
1834   EXPECT_NE(N, MDLocalVariable::get(Context, Tag, Scope, Name, File, Line + 1,
1835                                     Type, Arg, Flags, InlinedAt));
1836   EXPECT_NE(N, MDLocalVariable::get(Context, Tag, Scope, Name, File, Line,
1837                                     Scope, Arg, Flags, InlinedAt));
1838   EXPECT_NE(N, MDLocalVariable::get(Context, Tag, Scope, Name, File, Line, Type,
1839                                     Arg + 1, Flags, InlinedAt));
1840   EXPECT_NE(N, MDLocalVariable::get(Context, Tag, Scope, Name, File, Line, Type,
1841                                     Arg, ~Flags, InlinedAt));
1842   EXPECT_NE(N, MDLocalVariable::get(
1843                    Context, Tag, Scope, Name, File, Line, Type, Arg, Flags,
1844                    MDLocation::getDistinct(Context, 10, 20, getSubprogram())));
1845
1846   TempMDLocalVariable Temp = N->clone();
1847   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1848
1849   auto *Inlined = N->withoutInline();
1850   EXPECT_NE(N, Inlined);
1851   EXPECT_EQ(N->getTag(), Inlined->getTag());
1852   EXPECT_EQ(N->getScope(), Inlined->getScope());
1853   EXPECT_EQ(N->getName(), Inlined->getName());
1854   EXPECT_EQ(N->getFile(), Inlined->getFile());
1855   EXPECT_EQ(N->getLine(), Inlined->getLine());
1856   EXPECT_EQ(N->getType(), Inlined->getType());
1857   EXPECT_EQ(N->getArg(), Inlined->getArg());
1858   EXPECT_EQ(N->getFlags(), Inlined->getFlags());
1859   EXPECT_EQ(nullptr, Inlined->getInlinedAt());
1860   EXPECT_EQ(N, Inlined->withInline(cast<MDLocation>(InlinedAt)));
1861 }
1862
1863 typedef MetadataTest MDExpressionTest;
1864
1865 TEST_F(MDExpressionTest, get) {
1866   uint64_t Elements[] = {2, 6, 9, 78, 0};
1867   auto *N = MDExpression::get(Context, Elements);
1868   EXPECT_EQ(makeArrayRef(Elements), N->getElements());
1869   EXPECT_EQ(N, MDExpression::get(Context, Elements));
1870
1871   EXPECT_EQ(5u, N->getNumElements());
1872   EXPECT_EQ(2u, N->getElement(0));
1873   EXPECT_EQ(6u, N->getElement(1));
1874   EXPECT_EQ(9u, N->getElement(2));
1875   EXPECT_EQ(78u, N->getElement(3));
1876   EXPECT_EQ(0u, N->getElement(4));
1877
1878   TempMDExpression Temp = N->clone();
1879   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1880 }
1881
1882 TEST_F(MDExpressionTest, isValid) {
1883 #define EXPECT_VALID(...)                                                      \
1884   do {                                                                         \
1885     uint64_t Elements[] = {__VA_ARGS__};                                       \
1886     EXPECT_TRUE(MDExpression::get(Context, Elements)->isValid());              \
1887   } while (false)
1888 #define EXPECT_INVALID(...)                                                    \
1889   do {                                                                         \
1890     uint64_t Elements[] = {__VA_ARGS__};                                       \
1891     EXPECT_FALSE(MDExpression::get(Context, Elements)->isValid());             \
1892   } while (false)
1893
1894   // Empty expression should be valid.
1895   EXPECT_TRUE(MDExpression::get(Context, None));
1896
1897   // Valid constructions.
1898   EXPECT_VALID(dwarf::DW_OP_plus, 6);
1899   EXPECT_VALID(dwarf::DW_OP_deref);
1900   EXPECT_VALID(dwarf::DW_OP_bit_piece, 3, 7);
1901   EXPECT_VALID(dwarf::DW_OP_plus, 6, dwarf::DW_OP_deref);
1902   EXPECT_VALID(dwarf::DW_OP_deref, dwarf::DW_OP_plus, 6);
1903   EXPECT_VALID(dwarf::DW_OP_deref, dwarf::DW_OP_bit_piece, 3, 7);
1904   EXPECT_VALID(dwarf::DW_OP_deref, dwarf::DW_OP_plus, 6, dwarf::DW_OP_bit_piece, 3, 7);
1905
1906   // Invalid constructions.
1907   EXPECT_INVALID(~0u);
1908   EXPECT_INVALID(dwarf::DW_OP_plus);
1909   EXPECT_INVALID(dwarf::DW_OP_bit_piece);
1910   EXPECT_INVALID(dwarf::DW_OP_bit_piece, 3);
1911   EXPECT_INVALID(dwarf::DW_OP_bit_piece, 3, 7, dwarf::DW_OP_plus, 3);
1912   EXPECT_INVALID(dwarf::DW_OP_bit_piece, 3, 7, dwarf::DW_OP_deref);
1913
1914 #undef EXPECT_VALID
1915 #undef EXPECT_INVALID
1916 }
1917
1918 typedef MetadataTest MDObjCPropertyTest;
1919
1920 TEST_F(MDObjCPropertyTest, get) {
1921   StringRef Name = "name";
1922   MDFile *File = getFile();
1923   unsigned Line = 5;
1924   StringRef GetterName = "getter";
1925   StringRef SetterName = "setter";
1926   unsigned Attributes = 7;
1927   MDType *Type = getBasicType("basic");
1928
1929   auto *N = MDObjCProperty::get(Context, Name, File, Line, GetterName,
1930                                 SetterName, Attributes, Type);
1931
1932   EXPECT_EQ(dwarf::DW_TAG_APPLE_property, N->getTag());
1933   EXPECT_EQ(Name, N->getName());
1934   EXPECT_EQ(File, N->getFile());
1935   EXPECT_EQ(Line, N->getLine());
1936   EXPECT_EQ(GetterName, N->getGetterName());
1937   EXPECT_EQ(SetterName, N->getSetterName());
1938   EXPECT_EQ(Attributes, N->getAttributes());
1939   EXPECT_EQ(Type, N->getType());
1940   EXPECT_EQ(N, MDObjCProperty::get(Context, Name, File, Line, GetterName,
1941                                    SetterName, Attributes, Type));
1942
1943   EXPECT_NE(N, MDObjCProperty::get(Context, "other", File, Line, GetterName,
1944                                    SetterName, Attributes, Type));
1945   EXPECT_NE(N, MDObjCProperty::get(Context, Name, getFile(), Line, GetterName,
1946                                    SetterName, Attributes, Type));
1947   EXPECT_NE(N, MDObjCProperty::get(Context, Name, File, Line + 1, GetterName,
1948                                    SetterName, Attributes, Type));
1949   EXPECT_NE(N, MDObjCProperty::get(Context, Name, File, Line, "other",
1950                                    SetterName, Attributes, Type));
1951   EXPECT_NE(N, MDObjCProperty::get(Context, Name, File, Line, GetterName,
1952                                    "other", Attributes, Type));
1953   EXPECT_NE(N, MDObjCProperty::get(Context, Name, File, Line, GetterName,
1954                                    SetterName, Attributes + 1, Type));
1955   EXPECT_NE(N,
1956             MDObjCProperty::get(Context, Name, File, Line, GetterName,
1957                                 SetterName, Attributes, getBasicType("other")));
1958
1959   TempMDObjCProperty Temp = N->clone();
1960   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1961 }
1962
1963 typedef MetadataTest MDImportedEntityTest;
1964
1965 TEST_F(MDImportedEntityTest, get) {
1966   unsigned Tag = dwarf::DW_TAG_imported_module;
1967   MDScope *Scope = getSubprogram();
1968   DebugNode *Entity = getCompositeType();
1969   unsigned Line = 5;
1970   StringRef Name = "name";
1971
1972   auto *N = MDImportedEntity::get(Context, Tag, Scope, Entity, Line, Name);
1973
1974   EXPECT_EQ(Tag, N->getTag());
1975   EXPECT_EQ(Scope, N->getScope());
1976   EXPECT_EQ(Entity, N->getEntity());
1977   EXPECT_EQ(Line, N->getLine());
1978   EXPECT_EQ(Name, N->getName());
1979   EXPECT_EQ(N, MDImportedEntity::get(Context, Tag, Scope, Entity, Line, Name));
1980
1981   EXPECT_NE(N,
1982             MDImportedEntity::get(Context, dwarf::DW_TAG_imported_declaration,
1983                                   Scope, Entity, Line, Name));
1984   EXPECT_NE(N, MDImportedEntity::get(Context, Tag, getSubprogram(), Entity,
1985                                      Line, Name));
1986   EXPECT_NE(N, MDImportedEntity::get(Context, Tag, Scope, getCompositeType(),
1987                                      Line, Name));
1988   EXPECT_NE(N,
1989             MDImportedEntity::get(Context, Tag, Scope, Entity, Line + 1, Name));
1990   EXPECT_NE(N,
1991             MDImportedEntity::get(Context, Tag, Scope, Entity, Line, "other"));
1992
1993   TempMDImportedEntity Temp = N->clone();
1994   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1995 }
1996
1997 typedef MetadataTest MetadataAsValueTest;
1998
1999 TEST_F(MetadataAsValueTest, MDNode) {
2000   MDNode *N = MDNode::get(Context, None);
2001   auto *V = MetadataAsValue::get(Context, N);
2002   EXPECT_TRUE(V->getType()->isMetadataTy());
2003   EXPECT_EQ(N, V->getMetadata());
2004
2005   auto *V2 = MetadataAsValue::get(Context, N);
2006   EXPECT_EQ(V, V2);
2007 }
2008
2009 TEST_F(MetadataAsValueTest, MDNodeMDNode) {
2010   MDNode *N = MDNode::get(Context, None);
2011   Metadata *Ops[] = {N};
2012   MDNode *N2 = MDNode::get(Context, Ops);
2013   auto *V = MetadataAsValue::get(Context, N2);
2014   EXPECT_TRUE(V->getType()->isMetadataTy());
2015   EXPECT_EQ(N2, V->getMetadata());
2016
2017   auto *V2 = MetadataAsValue::get(Context, N2);
2018   EXPECT_EQ(V, V2);
2019
2020   auto *V3 = MetadataAsValue::get(Context, N);
2021   EXPECT_TRUE(V3->getType()->isMetadataTy());
2022   EXPECT_NE(V, V3);
2023   EXPECT_EQ(N, V3->getMetadata());
2024 }
2025
2026 TEST_F(MetadataAsValueTest, MDNodeConstant) {
2027   auto *C = ConstantInt::getTrue(Context);
2028   auto *MD = ConstantAsMetadata::get(C);
2029   Metadata *Ops[] = {MD};
2030   auto *N = MDNode::get(Context, Ops);
2031
2032   auto *V = MetadataAsValue::get(Context, MD);
2033   EXPECT_TRUE(V->getType()->isMetadataTy());
2034   EXPECT_EQ(MD, V->getMetadata());
2035
2036   auto *V2 = MetadataAsValue::get(Context, N);
2037   EXPECT_EQ(MD, V2->getMetadata());
2038   EXPECT_EQ(V, V2);
2039 }
2040
2041 typedef MetadataTest ValueAsMetadataTest;
2042
2043 TEST_F(ValueAsMetadataTest, UpdatesOnRAUW) {
2044   Type *Ty = Type::getInt1PtrTy(Context);
2045   std::unique_ptr<GlobalVariable> GV0(
2046       new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage));
2047   auto *MD = ValueAsMetadata::get(GV0.get());
2048   EXPECT_TRUE(MD->getValue() == GV0.get());
2049   ASSERT_TRUE(GV0->use_empty());
2050
2051   std::unique_ptr<GlobalVariable> GV1(
2052       new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage));
2053   GV0->replaceAllUsesWith(GV1.get());
2054   EXPECT_TRUE(MD->getValue() == GV1.get());
2055 }
2056
2057 TEST_F(ValueAsMetadataTest, CollidingDoubleUpdates) {
2058   // Create a constant.
2059   ConstantAsMetadata *CI = ConstantAsMetadata::get(
2060       ConstantInt::get(getGlobalContext(), APInt(8, 0)));
2061
2062   // Create a temporary to prevent nodes from resolving.
2063   auto Temp = MDTuple::getTemporary(Context, None);
2064
2065   // When the first operand of N1 gets reset to nullptr, it'll collide with N2.
2066   Metadata *Ops1[] = {CI, CI, Temp.get()};
2067   Metadata *Ops2[] = {nullptr, CI, Temp.get()};
2068
2069   auto *N1 = MDTuple::get(Context, Ops1);
2070   auto *N2 = MDTuple::get(Context, Ops2);
2071   ASSERT_NE(N1, N2);
2072
2073   // Tell metadata that the constant is getting deleted.
2074   //
2075   // After this, N1 will be invalid, so don't touch it.
2076   ValueAsMetadata::handleDeletion(CI->getValue());
2077   EXPECT_EQ(nullptr, N2->getOperand(0));
2078   EXPECT_EQ(nullptr, N2->getOperand(1));
2079   EXPECT_EQ(Temp.get(), N2->getOperand(2));
2080
2081   // Clean up Temp for teardown.
2082   Temp->replaceAllUsesWith(nullptr);
2083 }
2084
2085 typedef MetadataTest TrackingMDRefTest;
2086
2087 TEST_F(TrackingMDRefTest, UpdatesOnRAUW) {
2088   Type *Ty = Type::getInt1PtrTy(Context);
2089   std::unique_ptr<GlobalVariable> GV0(
2090       new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage));
2091   TypedTrackingMDRef<ValueAsMetadata> MD(ValueAsMetadata::get(GV0.get()));
2092   EXPECT_TRUE(MD->getValue() == GV0.get());
2093   ASSERT_TRUE(GV0->use_empty());
2094
2095   std::unique_ptr<GlobalVariable> GV1(
2096       new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage));
2097   GV0->replaceAllUsesWith(GV1.get());
2098   EXPECT_TRUE(MD->getValue() == GV1.get());
2099
2100   // Reset it, so we don't inadvertently test deletion.
2101   MD.reset();
2102 }
2103
2104 TEST_F(TrackingMDRefTest, UpdatesOnDeletion) {
2105   Type *Ty = Type::getInt1PtrTy(Context);
2106   std::unique_ptr<GlobalVariable> GV(
2107       new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage));
2108   TypedTrackingMDRef<ValueAsMetadata> MD(ValueAsMetadata::get(GV.get()));
2109   EXPECT_TRUE(MD->getValue() == GV.get());
2110   ASSERT_TRUE(GV->use_empty());
2111
2112   GV.reset();
2113   EXPECT_TRUE(!MD);
2114 }
2115
2116 TEST(NamedMDNodeTest, Search) {
2117   LLVMContext Context;
2118   ConstantAsMetadata *C =
2119       ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Context), 1));
2120   ConstantAsMetadata *C2 =
2121       ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Context), 2));
2122
2123   Metadata *const V = C;
2124   Metadata *const V2 = C2;
2125   MDNode *n = MDNode::get(Context, V);
2126   MDNode *n2 = MDNode::get(Context, V2);
2127
2128   Module M("MyModule", Context);
2129   const char *Name = "llvm.NMD1";
2130   NamedMDNode *NMD = M.getOrInsertNamedMetadata(Name);
2131   NMD->addOperand(n);
2132   NMD->addOperand(n2);
2133
2134   std::string Str;
2135   raw_string_ostream oss(Str);
2136   NMD->print(oss);
2137   EXPECT_STREQ("!llvm.NMD1 = !{!0, !1}\n",
2138                oss.str().c_str());
2139 }
2140 }