Verifier: Add operand checks for MDLexicalBlock
[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, replaceWithDistinct) {
631   {
632     auto *Empty = MDTuple::get(Context, None);
633     Metadata *Ops[] = {Empty};
634     auto Temp = MDTuple::getTemporary(Context, Ops);
635     EXPECT_TRUE(Temp->isTemporary());
636
637     // Don't expect a collision.
638     auto *Current = Temp.get();
639     auto *Distinct = MDNode::replaceWithDistinct(std::move(Temp));
640     EXPECT_TRUE(Distinct->isDistinct());
641     EXPECT_TRUE(Distinct->isResolved());
642     EXPECT_EQ(Current, Distinct);
643   }
644   {
645     auto Unresolved = MDTuple::getTemporary(Context, None);
646     Metadata *Ops[] = {Unresolved.get()};
647     auto Temp = MDTuple::getTemporary(Context, Ops);
648     EXPECT_TRUE(Temp->isTemporary());
649
650     // Don't expect a collision.
651     auto *Current = Temp.get();
652     auto *Distinct = MDNode::replaceWithDistinct(std::move(Temp));
653     EXPECT_TRUE(Distinct->isDistinct());
654     EXPECT_TRUE(Distinct->isResolved());
655     EXPECT_EQ(Current, Distinct);
656
657     // Cleanup; required for teardown.
658     Unresolved->replaceAllUsesWith(nullptr);
659   }
660 }
661
662 TEST_F(MDNodeTest, replaceWithPermanent) {
663   Metadata *Ops[] = {nullptr};
664   auto Temp = MDTuple::getTemporary(Context, Ops);
665   auto *T = Temp.get();
666
667   // U is a normal, uniqued node that references T.
668   auto *U = MDTuple::get(Context, T);
669   EXPECT_TRUE(U->isUniqued());
670
671   // Make Temp self-referencing.
672   Temp->replaceOperandWith(0, T);
673
674   // Try to uniquify Temp.  This should, despite the name in the API, give a
675   // 'distinct' node, since self-references aren't allowed to be uniqued.
676   //
677   // Since it's distinct, N should have the same address as when it was a
678   // temporary (i.e., be equal to T not U).
679   auto *N = MDNode::replaceWithPermanent(std::move(Temp));
680   EXPECT_EQ(N, T);
681   EXPECT_TRUE(N->isDistinct());
682
683   // U should be the canonical unique node with N as the argument.
684   EXPECT_EQ(U, MDTuple::get(Context, N));
685   EXPECT_TRUE(U->isUniqued());
686
687   // This temporary should collide with U when replaced, but it should still be
688   // uniqued.
689   EXPECT_EQ(U, MDNode::replaceWithPermanent(MDTuple::getTemporary(Context, N)));
690   EXPECT_TRUE(U->isUniqued());
691
692   // This temporary should become a new uniqued node.
693   auto Temp2 = MDTuple::getTemporary(Context, U);
694   auto *V = Temp2.get();
695   EXPECT_EQ(V, MDNode::replaceWithPermanent(std::move(Temp2)));
696   EXPECT_TRUE(V->isUniqued());
697   EXPECT_EQ(U, V->getOperand(0));
698 }
699
700 TEST_F(MDNodeTest, deleteTemporaryWithTrackingRef) {
701   TrackingMDRef Ref;
702   EXPECT_EQ(nullptr, Ref.get());
703   {
704     auto Temp = MDTuple::getTemporary(Context, None);
705     Ref.reset(Temp.get());
706     EXPECT_EQ(Temp.get(), Ref.get());
707   }
708   EXPECT_EQ(nullptr, Ref.get());
709 }
710
711 typedef MetadataTest MDLocationTest;
712
713 TEST_F(MDLocationTest, Overflow) {
714   MDSubprogram *N = getSubprogram();
715   {
716     MDLocation *L = MDLocation::get(Context, 2, 7, N);
717     EXPECT_EQ(2u, L->getLine());
718     EXPECT_EQ(7u, L->getColumn());
719   }
720   unsigned U16 = 1u << 16;
721   {
722     MDLocation *L = MDLocation::get(Context, UINT32_MAX, U16 - 1, N);
723     EXPECT_EQ(UINT32_MAX, L->getLine());
724     EXPECT_EQ(U16 - 1, L->getColumn());
725   }
726   {
727     MDLocation *L = MDLocation::get(Context, UINT32_MAX, U16, N);
728     EXPECT_EQ(UINT32_MAX, L->getLine());
729     EXPECT_EQ(0u, L->getColumn());
730   }
731   {
732     MDLocation *L = MDLocation::get(Context, UINT32_MAX, U16 + 1, N);
733     EXPECT_EQ(UINT32_MAX, L->getLine());
734     EXPECT_EQ(0u, L->getColumn());
735   }
736 }
737
738 TEST_F(MDLocationTest, getDistinct) {
739   MDNode *N = getSubprogram();
740   MDLocation *L0 = MDLocation::getDistinct(Context, 2, 7, N);
741   EXPECT_TRUE(L0->isDistinct());
742   MDLocation *L1 = MDLocation::get(Context, 2, 7, N);
743   EXPECT_FALSE(L1->isDistinct());
744   EXPECT_EQ(L1, MDLocation::get(Context, 2, 7, N));
745 }
746
747 TEST_F(MDLocationTest, getTemporary) {
748   MDNode *N = MDNode::get(Context, None);
749   auto L = MDLocation::getTemporary(Context, 2, 7, N);
750   EXPECT_TRUE(L->isTemporary());
751   EXPECT_FALSE(L->isResolved());
752 }
753
754 typedef MetadataTest GenericDebugNodeTest;
755
756 TEST_F(GenericDebugNodeTest, get) {
757   StringRef Header = "header";
758   auto *Empty = MDNode::get(Context, None);
759   Metadata *Ops1[] = {Empty};
760   auto *N = GenericDebugNode::get(Context, 15, Header, Ops1);
761   EXPECT_EQ(15u, N->getTag());
762   EXPECT_EQ(2u, N->getNumOperands());
763   EXPECT_EQ(Header, N->getHeader());
764   EXPECT_EQ(MDString::get(Context, Header), N->getOperand(0));
765   EXPECT_EQ(1u, N->getNumDwarfOperands());
766   EXPECT_EQ(Empty, N->getDwarfOperand(0));
767   EXPECT_EQ(Empty, N->getOperand(1));
768   ASSERT_TRUE(N->isUniqued());
769
770   EXPECT_EQ(N, GenericDebugNode::get(Context, 15, Header, Ops1));
771
772   N->replaceOperandWith(1, nullptr);
773   EXPECT_EQ(15u, N->getTag());
774   EXPECT_EQ(Header, N->getHeader());
775   EXPECT_EQ(nullptr, N->getDwarfOperand(0));
776   ASSERT_TRUE(N->isUniqued());
777
778   Metadata *Ops2[] = {nullptr};
779   EXPECT_EQ(N, GenericDebugNode::get(Context, 15, Header, Ops2));
780
781   N->replaceDwarfOperandWith(0, Empty);
782   EXPECT_EQ(15u, N->getTag());
783   EXPECT_EQ(Header, N->getHeader());
784   EXPECT_EQ(Empty, N->getDwarfOperand(0));
785   ASSERT_TRUE(N->isUniqued());
786   EXPECT_EQ(N, GenericDebugNode::get(Context, 15, Header, Ops1));
787
788   TempGenericDebugNode Temp = N->clone();
789   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
790 }
791
792 TEST_F(GenericDebugNodeTest, getEmptyHeader) {
793   // Canonicalize !"" to null.
794   auto *N = GenericDebugNode::get(Context, 15, StringRef(), None);
795   EXPECT_EQ(StringRef(), N->getHeader());
796   EXPECT_EQ(nullptr, N->getOperand(0));
797 }
798
799 typedef MetadataTest MDSubrangeTest;
800
801 TEST_F(MDSubrangeTest, get) {
802   auto *N = MDSubrange::get(Context, 5, 7);
803   EXPECT_EQ(dwarf::DW_TAG_subrange_type, N->getTag());
804   EXPECT_EQ(5, N->getCount());
805   EXPECT_EQ(7, N->getLo());
806   EXPECT_EQ(N, MDSubrange::get(Context, 5, 7));
807   EXPECT_EQ(MDSubrange::get(Context, 5, 0), MDSubrange::get(Context, 5));
808
809   TempMDSubrange Temp = N->clone();
810   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
811 }
812
813 TEST_F(MDSubrangeTest, getEmptyArray) {
814   auto *N = MDSubrange::get(Context, -1, 0);
815   EXPECT_EQ(dwarf::DW_TAG_subrange_type, N->getTag());
816   EXPECT_EQ(-1, N->getCount());
817   EXPECT_EQ(0, N->getLo());
818   EXPECT_EQ(N, MDSubrange::get(Context, -1, 0));
819 }
820
821 typedef MetadataTest MDEnumeratorTest;
822
823 TEST_F(MDEnumeratorTest, get) {
824   auto *N = MDEnumerator::get(Context, 7, "name");
825   EXPECT_EQ(dwarf::DW_TAG_enumerator, N->getTag());
826   EXPECT_EQ(7, N->getValue());
827   EXPECT_EQ("name", N->getName());
828   EXPECT_EQ(N, MDEnumerator::get(Context, 7, "name"));
829
830   EXPECT_NE(N, MDEnumerator::get(Context, 8, "name"));
831   EXPECT_NE(N, MDEnumerator::get(Context, 7, "nam"));
832
833   TempMDEnumerator Temp = N->clone();
834   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
835 }
836
837 typedef MetadataTest MDBasicTypeTest;
838
839 TEST_F(MDBasicTypeTest, get) {
840   auto *N =
841       MDBasicType::get(Context, dwarf::DW_TAG_base_type, "special", 33, 26, 7);
842   EXPECT_EQ(dwarf::DW_TAG_base_type, N->getTag());
843   EXPECT_EQ("special", N->getName());
844   EXPECT_EQ(33u, N->getSizeInBits());
845   EXPECT_EQ(26u, N->getAlignInBits());
846   EXPECT_EQ(7u, N->getEncoding());
847   EXPECT_EQ(0u, N->getLine());
848   EXPECT_EQ(N, MDBasicType::get(Context, dwarf::DW_TAG_base_type, "special", 33,
849                                 26, 7));
850
851   EXPECT_NE(N, MDBasicType::get(Context, dwarf::DW_TAG_unspecified_type,
852                                 "special", 33, 26, 7));
853   EXPECT_NE(N,
854             MDBasicType::get(Context, dwarf::DW_TAG_base_type, "s", 33, 26, 7));
855   EXPECT_NE(N, MDBasicType::get(Context, dwarf::DW_TAG_base_type, "special", 32,
856                                 26, 7));
857   EXPECT_NE(N, MDBasicType::get(Context, dwarf::DW_TAG_base_type, "special", 33,
858                                 25, 7));
859   EXPECT_NE(N, MDBasicType::get(Context, dwarf::DW_TAG_base_type, "special", 33,
860                                 26, 6));
861
862   TempMDBasicType Temp = N->clone();
863   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
864 }
865
866 TEST_F(MDBasicTypeTest, getWithLargeValues) {
867   auto *N = MDBasicType::get(Context, dwarf::DW_TAG_base_type, "special",
868                              UINT64_MAX, UINT64_MAX - 1, 7);
869   EXPECT_EQ(UINT64_MAX, N->getSizeInBits());
870   EXPECT_EQ(UINT64_MAX - 1, N->getAlignInBits());
871 }
872
873 TEST_F(MDBasicTypeTest, getUnspecified) {
874   auto *N =
875       MDBasicType::get(Context, dwarf::DW_TAG_unspecified_type, "unspecified");
876   EXPECT_EQ(dwarf::DW_TAG_unspecified_type, N->getTag());
877   EXPECT_EQ("unspecified", N->getName());
878   EXPECT_EQ(0u, N->getSizeInBits());
879   EXPECT_EQ(0u, N->getAlignInBits());
880   EXPECT_EQ(0u, N->getEncoding());
881   EXPECT_EQ(0u, N->getLine());
882 }
883
884 typedef MetadataTest MDTypeTest;
885
886 TEST_F(MDTypeTest, clone) {
887   // Check that MDType has a specialized clone that returns TempMDType.
888   MDType *N = MDBasicType::get(Context, dwarf::DW_TAG_base_type, "int", 32, 32,
889                                dwarf::DW_ATE_signed);
890
891   TempMDType Temp = N->clone();
892   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
893 }
894
895 TEST_F(MDTypeTest, setFlags) {
896   // void (void)
897   Metadata *TypesOps[] = {nullptr};
898   Metadata *Types = MDTuple::get(Context, TypesOps);
899
900   MDType *D = MDSubroutineType::getDistinct(Context, 0u, Types);
901   EXPECT_EQ(0u, D->getFlags());
902   D->setFlags(DIDescriptor::FlagRValueReference);
903   EXPECT_EQ(DIDescriptor::FlagRValueReference, D->getFlags());
904   D->setFlags(0u);
905   EXPECT_EQ(0u, D->getFlags());
906
907   TempMDType T = MDSubroutineType::getTemporary(Context, 0u, Types);
908   EXPECT_EQ(0u, T->getFlags());
909   T->setFlags(DIDescriptor::FlagRValueReference);
910   EXPECT_EQ(DIDescriptor::FlagRValueReference, T->getFlags());
911   T->setFlags(0u);
912   EXPECT_EQ(0u, T->getFlags());
913 }
914
915 typedef MetadataTest MDDerivedTypeTest;
916
917 TEST_F(MDDerivedTypeTest, get) {
918   MDFile *File = getFile();
919   MDScope *Scope = getSubprogram();
920   MDType *BaseType = getBasicType("basic");
921   MDTuple *ExtraData = getTuple();
922
923   auto *N = MDDerivedType::get(Context, dwarf::DW_TAG_pointer_type, "something",
924                                File, 1, Scope, BaseType, 2, 3, 4, 5, ExtraData);
925   EXPECT_EQ(dwarf::DW_TAG_pointer_type, N->getTag());
926   EXPECT_EQ("something", N->getName());
927   EXPECT_EQ(File, N->getFile());
928   EXPECT_EQ(1u, N->getLine());
929   EXPECT_EQ(Scope, N->getScope());
930   EXPECT_EQ(BaseType, N->getBaseType());
931   EXPECT_EQ(2u, N->getSizeInBits());
932   EXPECT_EQ(3u, N->getAlignInBits());
933   EXPECT_EQ(4u, N->getOffsetInBits());
934   EXPECT_EQ(5u, N->getFlags());
935   EXPECT_EQ(ExtraData, N->getExtraData());
936   EXPECT_EQ(N, MDDerivedType::get(Context, dwarf::DW_TAG_pointer_type,
937                                   "something", File, 1, Scope, BaseType, 2, 3,
938                                   4, 5, ExtraData));
939
940   EXPECT_NE(N, MDDerivedType::get(Context, dwarf::DW_TAG_reference_type,
941                                   "something", File, 1, Scope, BaseType, 2, 3,
942                                   4, 5, ExtraData));
943   EXPECT_NE(N, MDDerivedType::get(Context, dwarf::DW_TAG_pointer_type, "else",
944                                   File, 1, Scope, BaseType, 2, 3, 4, 5,
945                                   ExtraData));
946   EXPECT_NE(N, MDDerivedType::get(Context, dwarf::DW_TAG_pointer_type,
947                                   "something", getFile(), 1, Scope, BaseType, 2,
948                                   3, 4, 5, ExtraData));
949   EXPECT_NE(N, MDDerivedType::get(Context, dwarf::DW_TAG_pointer_type,
950                                   "something", File, 2, Scope, BaseType, 2, 3,
951                                   4, 5, ExtraData));
952   EXPECT_NE(N, MDDerivedType::get(Context, dwarf::DW_TAG_pointer_type,
953                                   "something", File, 1, getSubprogram(),
954                                   BaseType, 2, 3, 4, 5, ExtraData));
955   EXPECT_NE(N, MDDerivedType::get(
956                    Context, dwarf::DW_TAG_pointer_type, "something", File, 1,
957                    Scope, getBasicType("basic2"), 2, 3, 4, 5, ExtraData));
958   EXPECT_NE(N, MDDerivedType::get(Context, dwarf::DW_TAG_pointer_type,
959                                   "something", File, 1, Scope, BaseType, 3, 3,
960                                   4, 5, ExtraData));
961   EXPECT_NE(N, MDDerivedType::get(Context, dwarf::DW_TAG_pointer_type,
962                                   "something", File, 1, Scope, BaseType, 2, 2,
963                                   4, 5, ExtraData));
964   EXPECT_NE(N, MDDerivedType::get(Context, dwarf::DW_TAG_pointer_type,
965                                   "something", File, 1, Scope, BaseType, 2, 3,
966                                   5, 5, ExtraData));
967   EXPECT_NE(N, MDDerivedType::get(Context, dwarf::DW_TAG_pointer_type,
968                                   "something", File, 1, Scope, BaseType, 2, 3,
969                                   4, 4, ExtraData));
970   EXPECT_NE(N, MDDerivedType::get(Context, dwarf::DW_TAG_pointer_type,
971                                   "something", File, 1, Scope, BaseType, 2, 3,
972                                   4, 5, getTuple()));
973
974   TempMDDerivedType Temp = N->clone();
975   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
976 }
977
978 TEST_F(MDDerivedTypeTest, getWithLargeValues) {
979   MDFile *File = getFile();
980   MDScope *Scope = getSubprogram();
981   MDType *BaseType = getBasicType("basic");
982   MDTuple *ExtraData = getTuple();
983
984   auto *N = MDDerivedType::get(Context, dwarf::DW_TAG_pointer_type, "something",
985                                File, 1, Scope, BaseType, UINT64_MAX,
986                                UINT64_MAX - 1, UINT64_MAX - 2, 5, ExtraData);
987   EXPECT_EQ(UINT64_MAX, N->getSizeInBits());
988   EXPECT_EQ(UINT64_MAX - 1, N->getAlignInBits());
989   EXPECT_EQ(UINT64_MAX - 2, N->getOffsetInBits());
990 }
991
992 typedef MetadataTest MDCompositeTypeTest;
993
994 TEST_F(MDCompositeTypeTest, get) {
995   unsigned Tag = dwarf::DW_TAG_structure_type;
996   StringRef Name = "some name";
997   MDFile *File = getFile();
998   unsigned Line = 1;
999   MDScope *Scope = getSubprogram();
1000   MDType *BaseType = getCompositeType();
1001   uint64_t SizeInBits = 2;
1002   uint64_t AlignInBits = 3;
1003   uint64_t OffsetInBits = 4;
1004   unsigned Flags = 5;
1005   MDTuple *Elements = getTuple();
1006   unsigned RuntimeLang = 6;
1007   MDType *VTableHolder = getCompositeType();
1008   MDTuple *TemplateParams = getTuple();
1009   StringRef Identifier = "some id";
1010
1011   auto *N = MDCompositeType::get(Context, Tag, Name, File, Line, Scope,
1012                                  BaseType, SizeInBits, AlignInBits,
1013                                  OffsetInBits, Flags, Elements, RuntimeLang,
1014                                  VTableHolder, TemplateParams, Identifier);
1015   EXPECT_EQ(Tag, N->getTag());
1016   EXPECT_EQ(Name, N->getName());
1017   EXPECT_EQ(File, N->getFile());
1018   EXPECT_EQ(Line, N->getLine());
1019   EXPECT_EQ(Scope, N->getScope());
1020   EXPECT_EQ(BaseType, N->getBaseType());
1021   EXPECT_EQ(SizeInBits, N->getSizeInBits());
1022   EXPECT_EQ(AlignInBits, N->getAlignInBits());
1023   EXPECT_EQ(OffsetInBits, N->getOffsetInBits());
1024   EXPECT_EQ(Flags, N->getFlags());
1025   EXPECT_EQ(Elements, N->getElements());
1026   EXPECT_EQ(RuntimeLang, N->getRuntimeLang());
1027   EXPECT_EQ(VTableHolder, N->getVTableHolder());
1028   EXPECT_EQ(TemplateParams, N->getTemplateParams());
1029   EXPECT_EQ(Identifier, N->getIdentifier());
1030
1031   EXPECT_EQ(N, MDCompositeType::get(Context, Tag, Name, File, Line, Scope,
1032                                     BaseType, SizeInBits, AlignInBits,
1033                                     OffsetInBits, Flags, Elements, RuntimeLang,
1034                                     VTableHolder, TemplateParams, Identifier));
1035
1036   EXPECT_NE(N, MDCompositeType::get(Context, Tag + 1, Name, File, Line, Scope,
1037                                     BaseType, SizeInBits, AlignInBits,
1038                                     OffsetInBits, Flags, Elements, RuntimeLang,
1039                                     VTableHolder, TemplateParams, Identifier));
1040   EXPECT_NE(N, MDCompositeType::get(Context, Tag, "abc", File, Line, Scope,
1041                                     BaseType, SizeInBits, AlignInBits,
1042                                     OffsetInBits, Flags, Elements, RuntimeLang,
1043                                     VTableHolder, TemplateParams, Identifier));
1044   EXPECT_NE(N, MDCompositeType::get(Context, Tag, Name, getFile(), Line, Scope,
1045                                     BaseType, SizeInBits, AlignInBits,
1046                                     OffsetInBits, Flags, Elements, RuntimeLang,
1047                                     VTableHolder, TemplateParams, Identifier));
1048   EXPECT_NE(N, MDCompositeType::get(Context, Tag, Name, File, Line + 1, Scope,
1049                                     BaseType, SizeInBits, AlignInBits,
1050                                     OffsetInBits, Flags, Elements, RuntimeLang,
1051                                     VTableHolder, TemplateParams, Identifier));
1052   EXPECT_NE(N, MDCompositeType::get(
1053                    Context, Tag, Name, File, Line, getSubprogram(), BaseType,
1054                    SizeInBits, AlignInBits, OffsetInBits, Flags, Elements,
1055                    RuntimeLang, VTableHolder, TemplateParams, Identifier));
1056   EXPECT_NE(N, MDCompositeType::get(Context, Tag, Name, File, Line, Scope, File,
1057                                     SizeInBits, AlignInBits, OffsetInBits,
1058                                     Flags, Elements, RuntimeLang, VTableHolder,
1059                                     TemplateParams, Identifier));
1060   EXPECT_NE(N, MDCompositeType::get(Context, Tag, Name, File, Line, Scope,
1061                                     BaseType, SizeInBits + 1, AlignInBits,
1062                                     OffsetInBits, Flags, Elements, RuntimeLang,
1063                                     VTableHolder, TemplateParams, Identifier));
1064   EXPECT_NE(N, MDCompositeType::get(Context, Tag, Name, File, Line, Scope,
1065                                     BaseType, SizeInBits, AlignInBits + 1,
1066                                     OffsetInBits, Flags, Elements, RuntimeLang,
1067                                     VTableHolder, TemplateParams, Identifier));
1068   EXPECT_NE(N, MDCompositeType::get(
1069                    Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
1070                    AlignInBits, OffsetInBits + 1, Flags, Elements, RuntimeLang,
1071                    VTableHolder, TemplateParams, Identifier));
1072   EXPECT_NE(N, MDCompositeType::get(
1073                    Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
1074                    AlignInBits, OffsetInBits, Flags + 1, Elements, RuntimeLang,
1075                    VTableHolder, TemplateParams, Identifier));
1076   EXPECT_NE(N, MDCompositeType::get(
1077                    Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
1078                    AlignInBits, OffsetInBits, Flags, getTuple(), RuntimeLang,
1079                    VTableHolder, TemplateParams, Identifier));
1080   EXPECT_NE(N, MDCompositeType::get(
1081                    Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
1082                    AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang + 1,
1083                    VTableHolder, TemplateParams, Identifier));
1084   EXPECT_NE(N, MDCompositeType::get(
1085                    Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
1086                    AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
1087                    getCompositeType(), TemplateParams, Identifier));
1088   EXPECT_NE(N, MDCompositeType::get(Context, Tag, Name, File, Line, Scope,
1089                                     BaseType, SizeInBits, AlignInBits,
1090                                     OffsetInBits, Flags, Elements, RuntimeLang,
1091                                     VTableHolder, getTuple(), Identifier));
1092   EXPECT_NE(N, MDCompositeType::get(Context, Tag, Name, File, Line, Scope,
1093                                     BaseType, SizeInBits, AlignInBits,
1094                                     OffsetInBits, Flags, Elements, RuntimeLang,
1095                                     VTableHolder, TemplateParams, "other"));
1096
1097   // Be sure that missing identifiers get null pointers.
1098   EXPECT_FALSE(MDCompositeType::get(
1099                    Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
1100                    AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
1101                    VTableHolder, TemplateParams, "")->getRawIdentifier());
1102   EXPECT_FALSE(MDCompositeType::get(
1103                    Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
1104                    AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
1105                    VTableHolder, TemplateParams)->getRawIdentifier());
1106
1107   TempMDCompositeType Temp = N->clone();
1108   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1109 }
1110
1111 TEST_F(MDCompositeTypeTest, getWithLargeValues) {
1112   unsigned Tag = dwarf::DW_TAG_structure_type;
1113   StringRef Name = "some name";
1114   MDFile *File = getFile();
1115   unsigned Line = 1;
1116   MDScope *Scope = getSubprogram();
1117   MDType *BaseType = getCompositeType();
1118   uint64_t SizeInBits = UINT64_MAX;
1119   uint64_t AlignInBits = UINT64_MAX - 1;
1120   uint64_t OffsetInBits = UINT64_MAX - 2;
1121   unsigned Flags = 5;
1122   MDTuple *Elements = getTuple();
1123   unsigned RuntimeLang = 6;
1124   MDType *VTableHolder = getCompositeType();
1125   MDTuple *TemplateParams = getTuple();
1126   StringRef Identifier = "some id";
1127
1128   auto *N = MDCompositeType::get(Context, Tag, Name, File, Line, Scope,
1129                                  BaseType, SizeInBits, AlignInBits,
1130                                  OffsetInBits, Flags, Elements, RuntimeLang,
1131                                  VTableHolder, TemplateParams, Identifier);
1132   EXPECT_EQ(SizeInBits, N->getSizeInBits());
1133   EXPECT_EQ(AlignInBits, N->getAlignInBits());
1134   EXPECT_EQ(OffsetInBits, N->getOffsetInBits());
1135 }
1136
1137 TEST_F(MDCompositeTypeTest, replaceOperands) {
1138   unsigned Tag = dwarf::DW_TAG_structure_type;
1139   StringRef Name = "some name";
1140   MDFile *File = getFile();
1141   unsigned Line = 1;
1142   MDScope *Scope = getSubprogram();
1143   MDType *BaseType = getCompositeType();
1144   uint64_t SizeInBits = 2;
1145   uint64_t AlignInBits = 3;
1146   uint64_t OffsetInBits = 4;
1147   unsigned Flags = 5;
1148   unsigned RuntimeLang = 6;
1149   StringRef Identifier = "some id";
1150
1151   auto *N = MDCompositeType::get(Context, Tag, Name, File, Line, Scope,
1152                                  BaseType, SizeInBits, AlignInBits,
1153                                  OffsetInBits, Flags, nullptr, RuntimeLang,
1154                                  nullptr, nullptr, Identifier);
1155
1156   auto *Elements = MDTuple::getDistinct(Context, None);
1157   EXPECT_EQ(nullptr, N->getElements());
1158   N->replaceElements(Elements);
1159   EXPECT_EQ(Elements, N->getElements());
1160   N->replaceElements(nullptr);
1161   EXPECT_EQ(nullptr, N->getElements());
1162
1163   auto *VTableHolder = MDTuple::getDistinct(Context, None);
1164   EXPECT_EQ(nullptr, N->getVTableHolder());
1165   N->replaceVTableHolder(VTableHolder);
1166   EXPECT_EQ(VTableHolder, N->getVTableHolder());
1167   N->replaceVTableHolder(nullptr);
1168   EXPECT_EQ(nullptr, N->getVTableHolder());
1169
1170   auto *TemplateParams = MDTuple::getDistinct(Context, None);
1171   EXPECT_EQ(nullptr, N->getTemplateParams());
1172   N->replaceTemplateParams(TemplateParams);
1173   EXPECT_EQ(TemplateParams, N->getTemplateParams());
1174   N->replaceTemplateParams(nullptr);
1175   EXPECT_EQ(nullptr, N->getTemplateParams());
1176 }
1177
1178 typedef MetadataTest MDSubroutineTypeTest;
1179
1180 TEST_F(MDSubroutineTypeTest, get) {
1181   unsigned Flags = 1;
1182   MDTuple *TypeArray = getTuple();
1183
1184   auto *N = MDSubroutineType::get(Context, Flags, TypeArray);
1185   EXPECT_EQ(dwarf::DW_TAG_subroutine_type, N->getTag());
1186   EXPECT_EQ(Flags, N->getFlags());
1187   EXPECT_EQ(TypeArray, N->getTypeArray());
1188   EXPECT_EQ(N, MDSubroutineType::get(Context, Flags, TypeArray));
1189
1190   EXPECT_NE(N, MDSubroutineType::get(Context, Flags + 1, TypeArray));
1191   EXPECT_NE(N, MDSubroutineType::get(Context, Flags, getTuple()));
1192
1193   TempMDSubroutineType Temp = N->clone();
1194   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1195
1196   // Test always-empty operands.
1197   EXPECT_EQ(nullptr, N->getScope());
1198   EXPECT_EQ(nullptr, N->getFile());
1199   EXPECT_EQ("", N->getName());
1200   EXPECT_EQ(nullptr, N->getBaseType());
1201   EXPECT_EQ(nullptr, N->getVTableHolder());
1202   EXPECT_EQ(nullptr, N->getTemplateParams());
1203   EXPECT_EQ("", N->getIdentifier());
1204 }
1205
1206 typedef MetadataTest MDFileTest;
1207
1208 TEST_F(MDFileTest, get) {
1209   StringRef Filename = "file";
1210   StringRef Directory = "dir";
1211   auto *N = MDFile::get(Context, Filename, Directory);
1212
1213   EXPECT_EQ(dwarf::DW_TAG_file_type, N->getTag());
1214   EXPECT_EQ(Filename, N->getFilename());
1215   EXPECT_EQ(Directory, N->getDirectory());
1216   EXPECT_EQ(N, MDFile::get(Context, Filename, Directory));
1217
1218   EXPECT_NE(N, MDFile::get(Context, "other", Directory));
1219   EXPECT_NE(N, MDFile::get(Context, Filename, "other"));
1220
1221   TempMDFile Temp = N->clone();
1222   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1223 }
1224
1225 TEST_F(MDFileTest, ScopeGetFile) {
1226   // Ensure that MDScope::getFile() returns itself.
1227   MDScope *N = MDFile::get(Context, "file", "dir");
1228   EXPECT_EQ(N, N->getFile());
1229 }
1230
1231 typedef MetadataTest MDCompileUnitTest;
1232
1233 TEST_F(MDCompileUnitTest, get) {
1234   unsigned SourceLanguage = 1;
1235   MDFile *File = getFile();
1236   StringRef Producer = "some producer";
1237   bool IsOptimized = false;
1238   StringRef Flags = "flag after flag";
1239   unsigned RuntimeVersion = 2;
1240   StringRef SplitDebugFilename = "another/file";
1241   unsigned EmissionKind = 3;
1242   MDTuple *EnumTypes = getTuple();
1243   MDTuple *RetainedTypes = getTuple();
1244   MDTuple *Subprograms = getTuple();
1245   MDTuple *GlobalVariables = getTuple();
1246   MDTuple *ImportedEntities = getTuple();
1247   auto *N = MDCompileUnit::get(
1248       Context, SourceLanguage, File, Producer, IsOptimized, Flags,
1249       RuntimeVersion, SplitDebugFilename, EmissionKind, EnumTypes,
1250       RetainedTypes, Subprograms, GlobalVariables, ImportedEntities);
1251
1252   EXPECT_EQ(dwarf::DW_TAG_compile_unit, N->getTag());
1253   EXPECT_EQ(SourceLanguage, N->getSourceLanguage());
1254   EXPECT_EQ(File, N->getFile());
1255   EXPECT_EQ(Producer, N->getProducer());
1256   EXPECT_EQ(IsOptimized, N->isOptimized());
1257   EXPECT_EQ(Flags, N->getFlags());
1258   EXPECT_EQ(RuntimeVersion, N->getRuntimeVersion());
1259   EXPECT_EQ(SplitDebugFilename, N->getSplitDebugFilename());
1260   EXPECT_EQ(EmissionKind, N->getEmissionKind());
1261   EXPECT_EQ(EnumTypes, N->getEnumTypes());
1262   EXPECT_EQ(RetainedTypes, N->getRetainedTypes());
1263   EXPECT_EQ(Subprograms, N->getSubprograms());
1264   EXPECT_EQ(GlobalVariables, N->getGlobalVariables());
1265   EXPECT_EQ(ImportedEntities, N->getImportedEntities());
1266   EXPECT_EQ(N, MDCompileUnit::get(Context, SourceLanguage, File, Producer,
1267                                   IsOptimized, Flags, RuntimeVersion,
1268                                   SplitDebugFilename, EmissionKind, EnumTypes,
1269                                   RetainedTypes, Subprograms, GlobalVariables,
1270                                   ImportedEntities));
1271
1272   EXPECT_NE(N, MDCompileUnit::get(Context, SourceLanguage + 1, File, Producer,
1273                                   IsOptimized, Flags, RuntimeVersion,
1274                                   SplitDebugFilename, EmissionKind, EnumTypes,
1275                                   RetainedTypes, Subprograms, GlobalVariables,
1276                                   ImportedEntities));
1277   EXPECT_NE(N, MDCompileUnit::get(Context, SourceLanguage, getFile(), Producer,
1278                                   IsOptimized, Flags, RuntimeVersion,
1279                                   SplitDebugFilename, EmissionKind, EnumTypes,
1280                                   RetainedTypes, Subprograms, GlobalVariables,
1281                                   ImportedEntities));
1282   EXPECT_NE(N, MDCompileUnit::get(Context, SourceLanguage, File, "other",
1283                                   IsOptimized, Flags, RuntimeVersion,
1284                                   SplitDebugFilename, EmissionKind, EnumTypes,
1285                                   RetainedTypes, Subprograms, GlobalVariables,
1286                                   ImportedEntities));
1287   EXPECT_NE(N, MDCompileUnit::get(Context, SourceLanguage, File, Producer,
1288                                   !IsOptimized, Flags, RuntimeVersion,
1289                                   SplitDebugFilename, EmissionKind, EnumTypes,
1290                                   RetainedTypes, Subprograms, GlobalVariables,
1291                                   ImportedEntities));
1292   EXPECT_NE(N, MDCompileUnit::get(Context, SourceLanguage, File, Producer,
1293                                   IsOptimized, "other", RuntimeVersion,
1294                                   SplitDebugFilename, EmissionKind, EnumTypes,
1295                                   RetainedTypes, Subprograms, GlobalVariables,
1296                                   ImportedEntities));
1297   EXPECT_NE(N, MDCompileUnit::get(Context, SourceLanguage, File, Producer,
1298                                   IsOptimized, Flags, RuntimeVersion + 1,
1299                                   SplitDebugFilename, EmissionKind, EnumTypes,
1300                                   RetainedTypes, Subprograms, GlobalVariables,
1301                                   ImportedEntities));
1302   EXPECT_NE(N,
1303             MDCompileUnit::get(Context, SourceLanguage, File, Producer,
1304                                IsOptimized, Flags, RuntimeVersion, "other",
1305                                EmissionKind, EnumTypes, RetainedTypes,
1306                                Subprograms, GlobalVariables, ImportedEntities));
1307   EXPECT_NE(N, MDCompileUnit::get(Context, SourceLanguage, File, Producer,
1308                                   IsOptimized, Flags, RuntimeVersion,
1309                                   SplitDebugFilename, EmissionKind + 1,
1310                                   EnumTypes, RetainedTypes, Subprograms,
1311                                   GlobalVariables, ImportedEntities));
1312   EXPECT_NE(N, MDCompileUnit::get(Context, SourceLanguage, File, Producer,
1313                                   IsOptimized, Flags, RuntimeVersion,
1314                                   SplitDebugFilename, EmissionKind, getTuple(),
1315                                   RetainedTypes, Subprograms, GlobalVariables,
1316                                   ImportedEntities));
1317   EXPECT_NE(N, MDCompileUnit::get(
1318                    Context, SourceLanguage, File, Producer, IsOptimized, Flags,
1319                    RuntimeVersion, SplitDebugFilename, EmissionKind, EnumTypes,
1320                    getTuple(), Subprograms, GlobalVariables, ImportedEntities));
1321   EXPECT_NE(N, MDCompileUnit::get(Context, SourceLanguage, File, Producer,
1322                                   IsOptimized, Flags, RuntimeVersion,
1323                                   SplitDebugFilename, EmissionKind, EnumTypes,
1324                                   RetainedTypes, getTuple(), GlobalVariables,
1325                                   ImportedEntities));
1326   EXPECT_NE(N, MDCompileUnit::get(
1327                    Context, SourceLanguage, File, Producer, IsOptimized, Flags,
1328                    RuntimeVersion, SplitDebugFilename, EmissionKind, EnumTypes,
1329                    RetainedTypes, Subprograms, getTuple(), ImportedEntities));
1330   EXPECT_NE(N, MDCompileUnit::get(
1331                    Context, SourceLanguage, File, Producer, IsOptimized, Flags,
1332                    RuntimeVersion, SplitDebugFilename, EmissionKind, EnumTypes,
1333                    RetainedTypes, Subprograms, GlobalVariables, getTuple()));
1334
1335   TempMDCompileUnit Temp = N->clone();
1336   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1337 }
1338
1339 TEST_F(MDCompileUnitTest, replaceArrays) {
1340   unsigned SourceLanguage = 1;
1341   MDFile *File = getFile();
1342   StringRef Producer = "some producer";
1343   bool IsOptimized = false;
1344   StringRef Flags = "flag after flag";
1345   unsigned RuntimeVersion = 2;
1346   StringRef SplitDebugFilename = "another/file";
1347   unsigned EmissionKind = 3;
1348   MDTuple *EnumTypes = MDTuple::getDistinct(Context, None);
1349   MDTuple *RetainedTypes = MDTuple::getDistinct(Context, None);
1350   MDTuple *ImportedEntities = MDTuple::getDistinct(Context, None);
1351   auto *N = MDCompileUnit::get(
1352       Context, SourceLanguage, File, Producer, IsOptimized, Flags,
1353       RuntimeVersion, SplitDebugFilename, EmissionKind, EnumTypes,
1354       RetainedTypes, nullptr, nullptr, ImportedEntities);
1355
1356   auto *Subprograms = MDTuple::getDistinct(Context, None);
1357   EXPECT_EQ(nullptr, N->getSubprograms());
1358   N->replaceSubprograms(Subprograms);
1359   EXPECT_EQ(Subprograms, N->getSubprograms());
1360   N->replaceSubprograms(nullptr);
1361   EXPECT_EQ(nullptr, N->getSubprograms());
1362
1363   auto *GlobalVariables = MDTuple::getDistinct(Context, None);
1364   EXPECT_EQ(nullptr, N->getGlobalVariables());
1365   N->replaceGlobalVariables(GlobalVariables);
1366   EXPECT_EQ(GlobalVariables, N->getGlobalVariables());
1367   N->replaceGlobalVariables(nullptr);
1368   EXPECT_EQ(nullptr, N->getGlobalVariables());
1369 }
1370
1371 typedef MetadataTest MDSubprogramTest;
1372
1373 TEST_F(MDSubprogramTest, get) {
1374   MDScope *Scope = getCompositeType();
1375   StringRef Name = "name";
1376   StringRef LinkageName = "linkage";
1377   MDFile *File = getFile();
1378   unsigned Line = 2;
1379   MDSubroutineType *Type = getSubroutineType();
1380   bool IsLocalToUnit = false;
1381   bool IsDefinition = true;
1382   unsigned ScopeLine = 3;
1383   MDType *ContainingType = getCompositeType();
1384   unsigned Virtuality = 4;
1385   unsigned VirtualIndex = 5;
1386   unsigned Flags = 6;
1387   bool IsOptimized = false;
1388   ConstantAsMetadata *Function = getFunctionAsMetadata("foo");
1389   MDTuple *TemplateParams = getTuple();
1390   MDSubprogram *Declaration = getSubprogram();
1391   MDTuple *Variables = getTuple();
1392
1393   auto *N = MDSubprogram::get(
1394       Context, Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit,
1395       IsDefinition, ScopeLine, ContainingType, Virtuality, VirtualIndex, Flags,
1396       IsOptimized, Function, TemplateParams, Declaration, Variables);
1397
1398   EXPECT_EQ(dwarf::DW_TAG_subprogram, N->getTag());
1399   EXPECT_EQ(Scope, N->getScope());
1400   EXPECT_EQ(Name, N->getName());
1401   EXPECT_EQ(LinkageName, N->getLinkageName());
1402   EXPECT_EQ(File, N->getFile());
1403   EXPECT_EQ(Line, N->getLine());
1404   EXPECT_EQ(Type, N->getType());
1405   EXPECT_EQ(IsLocalToUnit, N->isLocalToUnit());
1406   EXPECT_EQ(IsDefinition, N->isDefinition());
1407   EXPECT_EQ(ScopeLine, N->getScopeLine());
1408   EXPECT_EQ(ContainingType, N->getContainingType());
1409   EXPECT_EQ(Virtuality, N->getVirtuality());
1410   EXPECT_EQ(VirtualIndex, N->getVirtualIndex());
1411   EXPECT_EQ(Flags, N->getFlags());
1412   EXPECT_EQ(IsOptimized, N->isOptimized());
1413   EXPECT_EQ(Function, N->getFunction());
1414   EXPECT_EQ(TemplateParams, N->getTemplateParams());
1415   EXPECT_EQ(Declaration, N->getDeclaration());
1416   EXPECT_EQ(Variables, N->getVariables());
1417   EXPECT_EQ(N, MDSubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1418                                  Type, IsLocalToUnit, IsDefinition, ScopeLine,
1419                                  ContainingType, Virtuality, VirtualIndex,
1420                                  Flags, IsOptimized, Function, TemplateParams,
1421                                  Declaration, Variables));
1422
1423   EXPECT_NE(N, MDSubprogram::get(Context, getCompositeType(), Name, LinkageName,
1424                                  File, Line, Type, IsLocalToUnit, IsDefinition,
1425                                  ScopeLine, ContainingType, Virtuality,
1426                                  VirtualIndex, Flags, IsOptimized, Function,
1427                                  TemplateParams, Declaration, Variables));
1428   EXPECT_NE(N, MDSubprogram::get(Context, Scope, "other", LinkageName, File,
1429                                  Line, Type, IsLocalToUnit, IsDefinition,
1430                                  ScopeLine, ContainingType, Virtuality,
1431                                  VirtualIndex, Flags, IsOptimized, Function,
1432                                  TemplateParams, Declaration, Variables));
1433   EXPECT_NE(N, MDSubprogram::get(Context, Scope, Name, "other", File, Line,
1434                                  Type, IsLocalToUnit, IsDefinition, ScopeLine,
1435                                  ContainingType, Virtuality, VirtualIndex,
1436                                  Flags, IsOptimized, Function, TemplateParams,
1437                                  Declaration, Variables));
1438   EXPECT_NE(N, MDSubprogram::get(Context, Scope, Name, LinkageName, getFile(),
1439                                  Line, Type, IsLocalToUnit, IsDefinition,
1440                                  ScopeLine, ContainingType, Virtuality,
1441                                  VirtualIndex, Flags, IsOptimized, Function,
1442                                  TemplateParams, Declaration, Variables));
1443   EXPECT_NE(N, MDSubprogram::get(Context, Scope, Name, LinkageName, File,
1444                                  Line + 1, Type, IsLocalToUnit, IsDefinition,
1445                                  ScopeLine, ContainingType, Virtuality,
1446                                  VirtualIndex, Flags, IsOptimized, Function,
1447                                  TemplateParams, Declaration, Variables));
1448   EXPECT_NE(N, MDSubprogram::get(
1449                    Context, Scope, Name, LinkageName, File, Line,
1450                    getSubroutineType(), IsLocalToUnit, IsDefinition, ScopeLine,
1451                    ContainingType, Virtuality, VirtualIndex, Flags, IsOptimized,
1452                    Function, TemplateParams, Declaration, Variables));
1453   EXPECT_NE(N, MDSubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1454                                  Type, !IsLocalToUnit, IsDefinition, ScopeLine,
1455                                  ContainingType, Virtuality, VirtualIndex,
1456                                  Flags, IsOptimized, Function, TemplateParams,
1457                                  Declaration, Variables));
1458   EXPECT_NE(N, MDSubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1459                                  Type, IsLocalToUnit, !IsDefinition, ScopeLine,
1460                                  ContainingType, Virtuality, VirtualIndex,
1461                                  Flags, IsOptimized, Function, TemplateParams,
1462                                  Declaration, Variables));
1463   EXPECT_NE(N, MDSubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1464                                  Type, IsLocalToUnit, IsDefinition,
1465                                  ScopeLine + 1, ContainingType, Virtuality,
1466                                  VirtualIndex, Flags, IsOptimized, Function,
1467                                  TemplateParams, Declaration, Variables));
1468   EXPECT_NE(N, MDSubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1469                                  Type, IsLocalToUnit, IsDefinition, ScopeLine,
1470                                  getCompositeType(), Virtuality, VirtualIndex,
1471                                  Flags, IsOptimized, Function, TemplateParams,
1472                                  Declaration, Variables));
1473   EXPECT_NE(N, MDSubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1474                                  Type, IsLocalToUnit, IsDefinition, ScopeLine,
1475                                  ContainingType, Virtuality + 1, VirtualIndex,
1476                                  Flags, IsOptimized, Function, TemplateParams,
1477                                  Declaration, Variables));
1478   EXPECT_NE(N, MDSubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1479                                  Type, IsLocalToUnit, IsDefinition, ScopeLine,
1480                                  ContainingType, Virtuality, VirtualIndex + 1,
1481                                  Flags, IsOptimized, Function, TemplateParams,
1482                                  Declaration, Variables));
1483   EXPECT_NE(N, MDSubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1484                                  Type, IsLocalToUnit, IsDefinition, ScopeLine,
1485                                  ContainingType, Virtuality, VirtualIndex,
1486                                  ~Flags, IsOptimized, Function, TemplateParams,
1487                                  Declaration, Variables));
1488   EXPECT_NE(N, MDSubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1489                                  Type, IsLocalToUnit, IsDefinition, ScopeLine,
1490                                  ContainingType, Virtuality, VirtualIndex,
1491                                  Flags, !IsOptimized, Function, TemplateParams,
1492                                  Declaration, Variables));
1493   EXPECT_NE(N,
1494             MDSubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1495                               Type, IsLocalToUnit, IsDefinition, ScopeLine,
1496                               ContainingType, Virtuality, VirtualIndex, Flags,
1497                               IsOptimized, getFunctionAsMetadata("bar"),
1498                               TemplateParams, Declaration, Variables));
1499   EXPECT_NE(N, MDSubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1500                                  Type, IsLocalToUnit, IsDefinition, ScopeLine,
1501                                  ContainingType, Virtuality, VirtualIndex,
1502                                  Flags, IsOptimized, Function, getTuple(),
1503                                  Declaration, Variables));
1504   EXPECT_NE(N, MDSubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1505                                  Type, IsLocalToUnit, IsDefinition, ScopeLine,
1506                                  ContainingType, Virtuality, VirtualIndex,
1507                                  Flags, IsOptimized, Function, TemplateParams,
1508                                  getSubprogram(), Variables));
1509   EXPECT_NE(N, MDSubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1510                                  Type, IsLocalToUnit, IsDefinition, ScopeLine,
1511                                  ContainingType, Virtuality, VirtualIndex,
1512                                  Flags, IsOptimized, Function, TemplateParams,
1513                                  Declaration, getTuple()));
1514
1515   TempMDSubprogram Temp = N->clone();
1516   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1517 }
1518
1519 TEST_F(MDSubprogramTest, replaceFunction) {
1520   MDScope *Scope = getCompositeType();
1521   StringRef Name = "name";
1522   StringRef LinkageName = "linkage";
1523   MDFile *File = getFile();
1524   unsigned Line = 2;
1525   MDSubroutineType *Type = getSubroutineType();
1526   bool IsLocalToUnit = false;
1527   bool IsDefinition = true;
1528   unsigned ScopeLine = 3;
1529   MDCompositeType *ContainingType = getCompositeType();
1530   unsigned Virtuality = 4;
1531   unsigned VirtualIndex = 5;
1532   unsigned Flags = 6;
1533   bool IsOptimized = false;
1534   MDTuple *TemplateParams = getTuple();
1535   MDSubprogram *Declaration = getSubprogram();
1536   MDTuple *Variables = getTuple();
1537
1538   auto *N = MDSubprogram::get(
1539       Context, Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit,
1540       IsDefinition, ScopeLine, ContainingType, Virtuality, VirtualIndex, Flags,
1541       IsOptimized, nullptr, TemplateParams, Declaration, Variables);
1542
1543   EXPECT_EQ(nullptr, N->getFunction());
1544
1545   std::unique_ptr<Function> F(
1546       Function::Create(FunctionType::get(Type::getVoidTy(Context), false),
1547                        GlobalValue::ExternalLinkage));
1548   N->replaceFunction(F.get());
1549   EXPECT_EQ(ConstantAsMetadata::get(F.get()), N->getFunction());
1550
1551   N->replaceFunction(nullptr);
1552   EXPECT_EQ(nullptr, N->getFunction());
1553 }
1554
1555 typedef MetadataTest MDLexicalBlockTest;
1556
1557 TEST_F(MDLexicalBlockTest, get) {
1558   MDLocalScope *Scope = getSubprogram();
1559   MDFile *File = getFile();
1560   unsigned Line = 5;
1561   unsigned Column = 8;
1562
1563   auto *N = MDLexicalBlock::get(Context, Scope, File, Line, Column);
1564
1565   EXPECT_EQ(dwarf::DW_TAG_lexical_block, N->getTag());
1566   EXPECT_EQ(Scope, N->getScope());
1567   EXPECT_EQ(File, N->getFile());
1568   EXPECT_EQ(Line, N->getLine());
1569   EXPECT_EQ(Column, N->getColumn());
1570   EXPECT_EQ(N, MDLexicalBlock::get(Context, Scope, File, Line, Column));
1571
1572   EXPECT_NE(N,
1573             MDLexicalBlock::get(Context, getSubprogram(), File, Line, Column));
1574   EXPECT_NE(N, MDLexicalBlock::get(Context, Scope, getFile(), Line, Column));
1575   EXPECT_NE(N, MDLexicalBlock::get(Context, Scope, File, Line + 1, Column));
1576   EXPECT_NE(N, MDLexicalBlock::get(Context, Scope, File, Line, Column + 1));
1577
1578   TempMDLexicalBlock Temp = N->clone();
1579   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1580 }
1581
1582 typedef MetadataTest MDLexicalBlockFileTest;
1583
1584 TEST_F(MDLexicalBlockFileTest, get) {
1585   MDLocalScope *Scope = getSubprogram();
1586   MDFile *File = getFile();
1587   unsigned Discriminator = 5;
1588
1589   auto *N = MDLexicalBlockFile::get(Context, Scope, File, Discriminator);
1590
1591   EXPECT_EQ(dwarf::DW_TAG_lexical_block, N->getTag());
1592   EXPECT_EQ(Scope, N->getScope());
1593   EXPECT_EQ(File, N->getFile());
1594   EXPECT_EQ(Discriminator, N->getDiscriminator());
1595   EXPECT_EQ(N, MDLexicalBlockFile::get(Context, Scope, File, Discriminator));
1596
1597   EXPECT_NE(N, MDLexicalBlockFile::get(Context, getSubprogram(), File,
1598                                        Discriminator));
1599   EXPECT_NE(N,
1600             MDLexicalBlockFile::get(Context, Scope, getFile(), Discriminator));
1601   EXPECT_NE(N,
1602             MDLexicalBlockFile::get(Context, Scope, File, Discriminator + 1));
1603
1604   TempMDLexicalBlockFile Temp = N->clone();
1605   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1606 }
1607
1608 typedef MetadataTest MDNamespaceTest;
1609
1610 TEST_F(MDNamespaceTest, get) {
1611   Metadata *Scope = MDTuple::getDistinct(Context, None);
1612   Metadata *File = MDTuple::getDistinct(Context, None);
1613   StringRef Name = "namespace";
1614   unsigned Line = 5;
1615
1616   auto *N = MDNamespace::get(Context, Scope, File, Name, Line);
1617
1618   EXPECT_EQ(dwarf::DW_TAG_namespace, N->getTag());
1619   EXPECT_EQ(Scope, N->getScope());
1620   EXPECT_EQ(File, N->getFile());
1621   EXPECT_EQ(Name, N->getName());
1622   EXPECT_EQ(Line, N->getLine());
1623   EXPECT_EQ(N, MDNamespace::get(Context, Scope, File, Name, Line));
1624
1625   EXPECT_NE(N, MDNamespace::get(Context, File, File, Name, Line));
1626   EXPECT_NE(N, MDNamespace::get(Context, Scope, Scope, Name, Line));
1627   EXPECT_NE(N, MDNamespace::get(Context, Scope, File, "other", Line));
1628   EXPECT_NE(N, MDNamespace::get(Context, Scope, File, Name, Line + 1));
1629
1630   TempMDNamespace Temp = N->clone();
1631   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1632 }
1633
1634 typedef MetadataTest MDTemplateTypeParameterTest;
1635
1636 TEST_F(MDTemplateTypeParameterTest, get) {
1637   StringRef Name = "template";
1638   Metadata *Type = MDTuple::getDistinct(Context, None);
1639   Metadata *Other = MDTuple::getDistinct(Context, None);
1640
1641   auto *N = MDTemplateTypeParameter::get(Context, Name, Type);
1642
1643   EXPECT_EQ(dwarf::DW_TAG_template_type_parameter, N->getTag());
1644   EXPECT_EQ(Name, N->getName());
1645   EXPECT_EQ(Type, N->getType());
1646   EXPECT_EQ(N, MDTemplateTypeParameter::get(Context, Name, Type));
1647
1648   EXPECT_NE(N, MDTemplateTypeParameter::get(Context, "other", Type));
1649   EXPECT_NE(N, MDTemplateTypeParameter::get(Context, Name, Other));
1650
1651   TempMDTemplateTypeParameter Temp = N->clone();
1652   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1653 }
1654
1655 typedef MetadataTest MDTemplateValueParameterTest;
1656
1657 TEST_F(MDTemplateValueParameterTest, get) {
1658   unsigned Tag = dwarf::DW_TAG_template_value_parameter;
1659   StringRef Name = "template";
1660   Metadata *Type = MDTuple::getDistinct(Context, None);
1661   Metadata *Value = MDTuple::getDistinct(Context, None);
1662   Metadata *Other = MDTuple::getDistinct(Context, None);
1663
1664   auto *N = MDTemplateValueParameter::get(Context, Tag, Name, Type, Value);
1665   EXPECT_EQ(Tag, N->getTag());
1666   EXPECT_EQ(Name, N->getName());
1667   EXPECT_EQ(Type, N->getType());
1668   EXPECT_EQ(Value, N->getValue());
1669   EXPECT_EQ(N, MDTemplateValueParameter::get(Context, Tag, Name, Type, Value));
1670
1671   EXPECT_NE(N, MDTemplateValueParameter::get(
1672                    Context, dwarf::DW_TAG_GNU_template_template_param, Name,
1673                    Type, Value));
1674   EXPECT_NE(N, MDTemplateValueParameter::get(Context, Tag,  "other", Type,
1675                                              Value));
1676   EXPECT_NE(N, MDTemplateValueParameter::get(Context, Tag,  Name, Other,
1677                                              Value));
1678   EXPECT_NE(N, MDTemplateValueParameter::get(Context, Tag, Name, Type, Other));
1679
1680   TempMDTemplateValueParameter Temp = N->clone();
1681   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1682 }
1683
1684 typedef MetadataTest MDGlobalVariableTest;
1685
1686 TEST_F(MDGlobalVariableTest, get) {
1687   MDScope *Scope = getSubprogram();
1688   StringRef Name = "name";
1689   StringRef LinkageName = "linkage";
1690   MDFile *File = getFile();
1691   unsigned Line = 5;
1692   Metadata *Type = MDTuple::getDistinct(Context, None);
1693   bool IsLocalToUnit = false;
1694   bool IsDefinition = true;
1695   ConstantAsMetadata *Variable = getConstantAsMetadata();
1696   MDDerivedType *StaticDataMemberDeclaration = getDerivedType();
1697
1698   auto *N = MDGlobalVariable::get(Context, Scope, Name, LinkageName, File, Line,
1699                                   Type, IsLocalToUnit, IsDefinition, Variable,
1700                                   StaticDataMemberDeclaration);
1701   EXPECT_EQ(dwarf::DW_TAG_variable, N->getTag());
1702   EXPECT_EQ(Scope, N->getScope());
1703   EXPECT_EQ(Name, N->getName());
1704   EXPECT_EQ(LinkageName, N->getLinkageName());
1705   EXPECT_EQ(File, N->getFile());
1706   EXPECT_EQ(Line, N->getLine());
1707   EXPECT_EQ(Type, N->getType());
1708   EXPECT_EQ(IsLocalToUnit, N->isLocalToUnit());
1709   EXPECT_EQ(IsDefinition, N->isDefinition());
1710   EXPECT_EQ(Variable, N->getVariable());
1711   EXPECT_EQ(StaticDataMemberDeclaration, N->getStaticDataMemberDeclaration());
1712   EXPECT_EQ(N, MDGlobalVariable::get(Context, Scope, Name, LinkageName, File,
1713                                      Line, Type, IsLocalToUnit, IsDefinition,
1714                                      Variable, StaticDataMemberDeclaration));
1715
1716   EXPECT_NE(N,
1717             MDGlobalVariable::get(Context, getSubprogram(), Name, LinkageName,
1718                                   File, Line, Type, IsLocalToUnit, IsDefinition,
1719                                   Variable, StaticDataMemberDeclaration));
1720   EXPECT_NE(N, MDGlobalVariable::get(Context, Scope, "other", LinkageName, File,
1721                                      Line, Type, IsLocalToUnit, IsDefinition,
1722                                      Variable, StaticDataMemberDeclaration));
1723   EXPECT_NE(N, MDGlobalVariable::get(Context, Scope, Name, "other", File, Line,
1724                                      Type, IsLocalToUnit, IsDefinition,
1725                                      Variable, StaticDataMemberDeclaration));
1726   EXPECT_NE(N,
1727             MDGlobalVariable::get(Context, Scope, Name, LinkageName, getFile(),
1728                                   Line, Type, IsLocalToUnit, IsDefinition,
1729                                   Variable, StaticDataMemberDeclaration));
1730   EXPECT_NE(N,
1731             MDGlobalVariable::get(Context, Scope, Name, LinkageName, File,
1732                                   Line + 1, Type, IsLocalToUnit, IsDefinition,
1733                                   Variable, StaticDataMemberDeclaration));
1734   EXPECT_NE(N, MDGlobalVariable::get(Context, Scope, Name, LinkageName, File,
1735                                      Line, Scope, IsLocalToUnit, IsDefinition,
1736                                      Variable, StaticDataMemberDeclaration));
1737   EXPECT_NE(N, MDGlobalVariable::get(Context, Scope, Name, LinkageName, File,
1738                                      Line, Type, !IsLocalToUnit, IsDefinition,
1739                                      Variable, StaticDataMemberDeclaration));
1740   EXPECT_NE(N, MDGlobalVariable::get(Context, Scope, Name, LinkageName, File,
1741                                      Line, Type, IsLocalToUnit, !IsDefinition,
1742                                      Variable, StaticDataMemberDeclaration));
1743   EXPECT_NE(N, MDGlobalVariable::get(Context, Scope, Name, LinkageName, File,
1744                                      Line, Type, IsLocalToUnit, IsDefinition,
1745                                      getConstantAsMetadata(),
1746                                      StaticDataMemberDeclaration));
1747   EXPECT_NE(N, MDGlobalVariable::get(Context, Scope, Name, LinkageName, File,
1748                                      Line, Type, IsLocalToUnit, IsDefinition,
1749                                      Variable, getDerivedType()));
1750
1751   TempMDGlobalVariable Temp = N->clone();
1752   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1753 }
1754
1755 typedef MetadataTest MDLocalVariableTest;
1756
1757 TEST_F(MDLocalVariableTest, get) {
1758   unsigned Tag = dwarf::DW_TAG_arg_variable;
1759   MDLocalScope *Scope = getSubprogram();
1760   StringRef Name = "name";
1761   MDFile *File = getFile();
1762   unsigned Line = 5;
1763   Metadata *Type = MDTuple::getDistinct(Context, None);
1764   unsigned Arg = 6;
1765   unsigned Flags = 7;
1766   MDLocation *InlinedAt =
1767       MDLocation::getDistinct(Context, 10, 20, getSubprogram());
1768
1769   auto *N = MDLocalVariable::get(Context, Tag, Scope, Name, File, Line, Type,
1770                                  Arg, Flags, InlinedAt);
1771   EXPECT_EQ(Tag, N->getTag());
1772   EXPECT_EQ(Scope, N->getScope());
1773   EXPECT_EQ(Name, N->getName());
1774   EXPECT_EQ(File, N->getFile());
1775   EXPECT_EQ(Line, N->getLine());
1776   EXPECT_EQ(Type, N->getType());
1777   EXPECT_EQ(Arg, N->getArg());
1778   EXPECT_EQ(Flags, N->getFlags());
1779   EXPECT_EQ(InlinedAt, N->getInlinedAt());
1780   EXPECT_EQ(N, MDLocalVariable::get(Context, Tag, Scope, Name, File, Line, Type,
1781                                     Arg, Flags, InlinedAt));
1782
1783   EXPECT_NE(N, MDLocalVariable::get(Context, dwarf::DW_TAG_auto_variable, Scope,
1784                                     Name, File, Line, Type, Arg, Flags,
1785                                     InlinedAt));
1786   EXPECT_NE(N, MDLocalVariable::get(Context, Tag, getSubprogram(), Name, File,
1787                                     Line, Type, Arg, Flags, InlinedAt));
1788   EXPECT_NE(N, MDLocalVariable::get(Context, Tag, Scope, "other", File, Line,
1789                                     Type, Arg, Flags, InlinedAt));
1790   EXPECT_NE(N, MDLocalVariable::get(Context, Tag, Scope, Name, getFile(), Line,
1791                                     Type, Arg, Flags, InlinedAt));
1792   EXPECT_NE(N, MDLocalVariable::get(Context, Tag, Scope, Name, File, Line + 1,
1793                                     Type, Arg, Flags, InlinedAt));
1794   EXPECT_NE(N, MDLocalVariable::get(Context, Tag, Scope, Name, File, Line,
1795                                     Scope, Arg, Flags, InlinedAt));
1796   EXPECT_NE(N, MDLocalVariable::get(Context, Tag, Scope, Name, File, Line, Type,
1797                                     Arg + 1, Flags, InlinedAt));
1798   EXPECT_NE(N, MDLocalVariable::get(Context, Tag, Scope, Name, File, Line, Type,
1799                                     Arg, ~Flags, InlinedAt));
1800   EXPECT_NE(N, MDLocalVariable::get(
1801                    Context, Tag, Scope, Name, File, Line, Type, Arg, Flags,
1802                    MDLocation::getDistinct(Context, 10, 20, getSubprogram())));
1803
1804   TempMDLocalVariable Temp = N->clone();
1805   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1806
1807   auto *Inlined = N->withoutInline();
1808   EXPECT_NE(N, Inlined);
1809   EXPECT_EQ(N->getTag(), Inlined->getTag());
1810   EXPECT_EQ(N->getScope(), Inlined->getScope());
1811   EXPECT_EQ(N->getName(), Inlined->getName());
1812   EXPECT_EQ(N->getFile(), Inlined->getFile());
1813   EXPECT_EQ(N->getLine(), Inlined->getLine());
1814   EXPECT_EQ(N->getType(), Inlined->getType());
1815   EXPECT_EQ(N->getArg(), Inlined->getArg());
1816   EXPECT_EQ(N->getFlags(), Inlined->getFlags());
1817   EXPECT_EQ(nullptr, Inlined->getInlinedAt());
1818   EXPECT_EQ(N, Inlined->withInline(cast<MDLocation>(InlinedAt)));
1819 }
1820
1821 typedef MetadataTest MDExpressionTest;
1822
1823 TEST_F(MDExpressionTest, get) {
1824   uint64_t Elements[] = {2, 6, 9, 78, 0};
1825   auto *N = MDExpression::get(Context, Elements);
1826   EXPECT_EQ(makeArrayRef(Elements), N->getElements());
1827   EXPECT_EQ(N, MDExpression::get(Context, Elements));
1828
1829   EXPECT_EQ(5u, N->getNumElements());
1830   EXPECT_EQ(2u, N->getElement(0));
1831   EXPECT_EQ(6u, N->getElement(1));
1832   EXPECT_EQ(9u, N->getElement(2));
1833   EXPECT_EQ(78u, N->getElement(3));
1834   EXPECT_EQ(0u, N->getElement(4));
1835
1836   TempMDExpression Temp = N->clone();
1837   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1838 }
1839
1840 TEST_F(MDExpressionTest, isValid) {
1841 #define EXPECT_VALID(...)                                                      \
1842   do {                                                                         \
1843     uint64_t Elements[] = {__VA_ARGS__};                                       \
1844     EXPECT_TRUE(MDExpression::get(Context, Elements)->isValid());              \
1845   } while (false)
1846 #define EXPECT_INVALID(...)                                                    \
1847   do {                                                                         \
1848     uint64_t Elements[] = {__VA_ARGS__};                                       \
1849     EXPECT_FALSE(MDExpression::get(Context, Elements)->isValid());             \
1850   } while (false)
1851
1852   // Empty expression should be valid.
1853   EXPECT_TRUE(MDExpression::get(Context, None));
1854
1855   // Valid constructions.
1856   EXPECT_VALID(dwarf::DW_OP_plus, 6);
1857   EXPECT_VALID(dwarf::DW_OP_deref);
1858   EXPECT_VALID(dwarf::DW_OP_bit_piece, 3, 7);
1859   EXPECT_VALID(dwarf::DW_OP_plus, 6, dwarf::DW_OP_deref);
1860   EXPECT_VALID(dwarf::DW_OP_deref, dwarf::DW_OP_plus, 6);
1861   EXPECT_VALID(dwarf::DW_OP_deref, dwarf::DW_OP_bit_piece, 3, 7);
1862   EXPECT_VALID(dwarf::DW_OP_deref, dwarf::DW_OP_plus, 6, dwarf::DW_OP_bit_piece, 3, 7);
1863
1864   // Invalid constructions.
1865   EXPECT_INVALID(~0u);
1866   EXPECT_INVALID(dwarf::DW_OP_plus);
1867   EXPECT_INVALID(dwarf::DW_OP_bit_piece);
1868   EXPECT_INVALID(dwarf::DW_OP_bit_piece, 3);
1869   EXPECT_INVALID(dwarf::DW_OP_bit_piece, 3, 7, dwarf::DW_OP_plus, 3);
1870   EXPECT_INVALID(dwarf::DW_OP_bit_piece, 3, 7, dwarf::DW_OP_deref);
1871
1872 #undef EXPECT_VALID
1873 #undef EXPECT_INVALID
1874 }
1875
1876 typedef MetadataTest MDObjCPropertyTest;
1877
1878 TEST_F(MDObjCPropertyTest, get) {
1879   StringRef Name = "name";
1880   Metadata *File = MDTuple::getDistinct(Context, None);
1881   unsigned Line = 5;
1882   StringRef GetterName = "getter";
1883   StringRef SetterName = "setter";
1884   unsigned Attributes = 7;
1885   Metadata *Type = MDTuple::getDistinct(Context, None);
1886
1887   auto *N = MDObjCProperty::get(Context, Name, File, Line, GetterName,
1888                                 SetterName, Attributes, Type);
1889
1890   EXPECT_EQ(dwarf::DW_TAG_APPLE_property, N->getTag());
1891   EXPECT_EQ(Name, N->getName());
1892   EXPECT_EQ(File, N->getFile());
1893   EXPECT_EQ(Line, N->getLine());
1894   EXPECT_EQ(GetterName, N->getGetterName());
1895   EXPECT_EQ(SetterName, N->getSetterName());
1896   EXPECT_EQ(Attributes, N->getAttributes());
1897   EXPECT_EQ(Type, N->getType());
1898   EXPECT_EQ(N, MDObjCProperty::get(Context, Name, File, Line, GetterName,
1899                                    SetterName, Attributes, Type));
1900
1901   EXPECT_NE(N, MDObjCProperty::get(Context, "other", File, Line, GetterName,
1902                                    SetterName, Attributes, Type));
1903   EXPECT_NE(N, MDObjCProperty::get(Context, Name, Type, Line, GetterName,
1904                                    SetterName, Attributes, Type));
1905   EXPECT_NE(N, MDObjCProperty::get(Context, Name, File, Line + 1, GetterName,
1906                                    SetterName, Attributes, Type));
1907   EXPECT_NE(N, MDObjCProperty::get(Context, Name, File, Line, "other",
1908                                    SetterName, Attributes, Type));
1909   EXPECT_NE(N, MDObjCProperty::get(Context, Name, File, Line, GetterName,
1910                                    "other", Attributes, Type));
1911   EXPECT_NE(N, MDObjCProperty::get(Context, Name, File, Line, GetterName,
1912                                    SetterName, Attributes + 1, Type));
1913   EXPECT_NE(N, MDObjCProperty::get(Context, Name, File, Line, GetterName,
1914                                    SetterName, Attributes, File));
1915
1916   TempMDObjCProperty Temp = N->clone();
1917   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1918 }
1919
1920 typedef MetadataTest MDImportedEntityTest;
1921
1922 TEST_F(MDImportedEntityTest, get) {
1923   unsigned Tag = dwarf::DW_TAG_imported_module;
1924   Metadata *Scope = MDTuple::getDistinct(Context, None);
1925   Metadata *Entity = MDTuple::getDistinct(Context, None);
1926   unsigned Line = 5;
1927   StringRef Name = "name";
1928
1929   auto *N = MDImportedEntity::get(Context, Tag, Scope, Entity, Line, Name);
1930
1931   EXPECT_EQ(Tag, N->getTag());
1932   EXPECT_EQ(Scope, N->getScope());
1933   EXPECT_EQ(Entity, N->getEntity());
1934   EXPECT_EQ(Line, N->getLine());
1935   EXPECT_EQ(Name, N->getName());
1936   EXPECT_EQ(N, MDImportedEntity::get(Context, Tag, Scope, Entity, Line, Name));
1937
1938   EXPECT_NE(N,
1939             MDImportedEntity::get(Context, dwarf::DW_TAG_imported_declaration,
1940                                   Scope, Entity, Line, Name));
1941   EXPECT_NE(N, MDImportedEntity::get(Context, Tag, Entity, Entity, Line, Name));
1942   EXPECT_NE(N, MDImportedEntity::get(Context, Tag, Scope, Scope, Line, Name));
1943   EXPECT_NE(N,
1944             MDImportedEntity::get(Context, Tag, Scope, Entity, Line + 1, Name));
1945   EXPECT_NE(N,
1946             MDImportedEntity::get(Context, Tag, Scope, Entity, Line, "other"));
1947
1948   TempMDImportedEntity Temp = N->clone();
1949   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1950 }
1951
1952 typedef MetadataTest MetadataAsValueTest;
1953
1954 TEST_F(MetadataAsValueTest, MDNode) {
1955   MDNode *N = MDNode::get(Context, None);
1956   auto *V = MetadataAsValue::get(Context, N);
1957   EXPECT_TRUE(V->getType()->isMetadataTy());
1958   EXPECT_EQ(N, V->getMetadata());
1959
1960   auto *V2 = MetadataAsValue::get(Context, N);
1961   EXPECT_EQ(V, V2);
1962 }
1963
1964 TEST_F(MetadataAsValueTest, MDNodeMDNode) {
1965   MDNode *N = MDNode::get(Context, None);
1966   Metadata *Ops[] = {N};
1967   MDNode *N2 = MDNode::get(Context, Ops);
1968   auto *V = MetadataAsValue::get(Context, N2);
1969   EXPECT_TRUE(V->getType()->isMetadataTy());
1970   EXPECT_EQ(N2, V->getMetadata());
1971
1972   auto *V2 = MetadataAsValue::get(Context, N2);
1973   EXPECT_EQ(V, V2);
1974
1975   auto *V3 = MetadataAsValue::get(Context, N);
1976   EXPECT_TRUE(V3->getType()->isMetadataTy());
1977   EXPECT_NE(V, V3);
1978   EXPECT_EQ(N, V3->getMetadata());
1979 }
1980
1981 TEST_F(MetadataAsValueTest, MDNodeConstant) {
1982   auto *C = ConstantInt::getTrue(Context);
1983   auto *MD = ConstantAsMetadata::get(C);
1984   Metadata *Ops[] = {MD};
1985   auto *N = MDNode::get(Context, Ops);
1986
1987   auto *V = MetadataAsValue::get(Context, MD);
1988   EXPECT_TRUE(V->getType()->isMetadataTy());
1989   EXPECT_EQ(MD, V->getMetadata());
1990
1991   auto *V2 = MetadataAsValue::get(Context, N);
1992   EXPECT_EQ(MD, V2->getMetadata());
1993   EXPECT_EQ(V, V2);
1994 }
1995
1996 typedef MetadataTest ValueAsMetadataTest;
1997
1998 TEST_F(ValueAsMetadataTest, UpdatesOnRAUW) {
1999   Type *Ty = Type::getInt1PtrTy(Context);
2000   std::unique_ptr<GlobalVariable> GV0(
2001       new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage));
2002   auto *MD = ValueAsMetadata::get(GV0.get());
2003   EXPECT_TRUE(MD->getValue() == GV0.get());
2004   ASSERT_TRUE(GV0->use_empty());
2005
2006   std::unique_ptr<GlobalVariable> GV1(
2007       new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage));
2008   GV0->replaceAllUsesWith(GV1.get());
2009   EXPECT_TRUE(MD->getValue() == GV1.get());
2010 }
2011
2012 TEST_F(ValueAsMetadataTest, CollidingDoubleUpdates) {
2013   // Create a constant.
2014   ConstantAsMetadata *CI = ConstantAsMetadata::get(
2015       ConstantInt::get(getGlobalContext(), APInt(8, 0)));
2016
2017   // Create a temporary to prevent nodes from resolving.
2018   auto Temp = MDTuple::getTemporary(Context, None);
2019
2020   // When the first operand of N1 gets reset to nullptr, it'll collide with N2.
2021   Metadata *Ops1[] = {CI, CI, Temp.get()};
2022   Metadata *Ops2[] = {nullptr, CI, Temp.get()};
2023
2024   auto *N1 = MDTuple::get(Context, Ops1);
2025   auto *N2 = MDTuple::get(Context, Ops2);
2026   ASSERT_NE(N1, N2);
2027
2028   // Tell metadata that the constant is getting deleted.
2029   //
2030   // After this, N1 will be invalid, so don't touch it.
2031   ValueAsMetadata::handleDeletion(CI->getValue());
2032   EXPECT_EQ(nullptr, N2->getOperand(0));
2033   EXPECT_EQ(nullptr, N2->getOperand(1));
2034   EXPECT_EQ(Temp.get(), N2->getOperand(2));
2035
2036   // Clean up Temp for teardown.
2037   Temp->replaceAllUsesWith(nullptr);
2038 }
2039
2040 typedef MetadataTest TrackingMDRefTest;
2041
2042 TEST_F(TrackingMDRefTest, UpdatesOnRAUW) {
2043   Type *Ty = Type::getInt1PtrTy(Context);
2044   std::unique_ptr<GlobalVariable> GV0(
2045       new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage));
2046   TypedTrackingMDRef<ValueAsMetadata> MD(ValueAsMetadata::get(GV0.get()));
2047   EXPECT_TRUE(MD->getValue() == GV0.get());
2048   ASSERT_TRUE(GV0->use_empty());
2049
2050   std::unique_ptr<GlobalVariable> GV1(
2051       new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage));
2052   GV0->replaceAllUsesWith(GV1.get());
2053   EXPECT_TRUE(MD->getValue() == GV1.get());
2054
2055   // Reset it, so we don't inadvertently test deletion.
2056   MD.reset();
2057 }
2058
2059 TEST_F(TrackingMDRefTest, UpdatesOnDeletion) {
2060   Type *Ty = Type::getInt1PtrTy(Context);
2061   std::unique_ptr<GlobalVariable> GV(
2062       new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage));
2063   TypedTrackingMDRef<ValueAsMetadata> MD(ValueAsMetadata::get(GV.get()));
2064   EXPECT_TRUE(MD->getValue() == GV.get());
2065   ASSERT_TRUE(GV->use_empty());
2066
2067   GV.reset();
2068   EXPECT_TRUE(!MD);
2069 }
2070
2071 TEST(NamedMDNodeTest, Search) {
2072   LLVMContext Context;
2073   ConstantAsMetadata *C =
2074       ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Context), 1));
2075   ConstantAsMetadata *C2 =
2076       ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Context), 2));
2077
2078   Metadata *const V = C;
2079   Metadata *const V2 = C2;
2080   MDNode *n = MDNode::get(Context, V);
2081   MDNode *n2 = MDNode::get(Context, V2);
2082
2083   Module M("MyModule", Context);
2084   const char *Name = "llvm.NMD1";
2085   NamedMDNode *NMD = M.getOrInsertNamedMetadata(Name);
2086   NMD->addOperand(n);
2087   NMD->addOperand(n2);
2088
2089   std::string Str;
2090   raw_string_ostream oss(Str);
2091   NMD->print(oss);
2092   EXPECT_STREQ("!llvm.NMD1 = !{!0, !1}\n",
2093                oss.str().c_str());
2094 }
2095 }