BuildMI crashes on a certain probability on the exact same test

Dear there,

I'm trying to call BuildMI in my backend to add a machineinstr.

BuildMI(MBB, I, I->getDebugLoc(), TII->get(Vanilla::MOV),
Vanilla::R1).addReg(MI->getOperand(1).getReg());

But it gives me an error like this:

0 clang 0x000000010e61a56e
llvm::sys::PrintStackTrace(llvm::raw_ostream&) + 46
1 clang 0x000000010e61c209
PrintStackTraceSignalHandler(void*) + 25
2 clang 0x000000010e618809
llvm::sys::RunSignalHandlers() + 425
3 clang 0x000000010e61c549 SignalHandler(int) + 345
4 libsystem_platform.dylib 0x00007fff9d1a852a _sigtramp + 26
5 libsystem_platform.dylib 0x0000000000000003 _sigtramp + 1659206387
6 clang 0x000000010df459d6
llvm::MetadataTracking::track(void*, llvm::Metadata&,
llvm::PointerUnion<llvm::MetadataAsValue*, llvm::Metadata*>) + 262
7 clang 0x000000010e1bcf50
llvm::MetadataTracking::track(llvm::Metadata*&) + 64
8 clang 0x000000010e1bcefa llvm::TrackingMDRef::track() + 42
9 clang 0x000000010e1bcec6
llvm::TrackingMDRef::TrackingMDRef(llvm::TrackingMDRef const&) + 38
10 clang 0x000000010e1bce8d
llvm::TrackingMDRef::TrackingMDRef(llvm::TrackingMDRef const&) + 29
11 clang 0x000000010e1bce5d
llvm::TypedTrackingMDRef<llvm::MDNode>::TypedTrackingMDRef(llvm::TypedTrackingMDRef<llvm::MDNode>
const&) + 29
12 clang 0x000000010e1bce2d
llvm::TypedTrackingMDRef<llvm::MDNode>::TypedTrackingMDRef(llvm::TypedTrackingMDRef<llvm::MDNode>
const&) + 29
13 clang 0x000000010e1bcdfd
llvm::DebugLoc::DebugLoc(llvm::DebugLoc const&) + 29
14 clang 0x000000010e1bcb4d
llvm::DebugLoc::DebugLoc(llvm::DebugLoc const&) + 29
15 clang 0x000000010d5359f5 (anonymous
namespace)::VanillaVerifier::runOnMachineBasicBlock1(llvm::MachineBasicBlock&)
+ 997
16 clang 0x000000010d534d72 (anonymous
namespace)::VanillaVerifier::runOnMachineFunction(llvm::MachineFunction&)
+ 322

And the most strange thing is that this error does not happen
everytime for the same test (it happens under certain probability) ?!
Can anyone please show me some hints on how to debug this problem?

Thanks,
Xiaochu

My best guess is that I == MBB.end(), in which case there is no
MachineInstr behind it and I->getDebugLoc() is accessing random memory
that may or may not resemble a MachineInstr. Try asserting it's valid
just before the BuildMI, or just stepping through in a debugger.

Cheers.

Tim.

Thanks, Tim! I pulled the latest code from llvm master and it seems to
be working now... I will try your suggestion after it crashes again.

Yes, it is this problem. I use

BuildMI(&MBB, MI->getDebugLoc(), TII->get(Vanilla::MOV),
MI->getOperand(0).getReg()).addReg(Vanilla::R1);

for the case and it works now...