Index: lib/Transforms/Instrumentation/InstrProfiling.cpp =================================================================== --- lib/Transforms/Instrumentation/InstrProfiling.cpp +++ lib/Transforms/Instrumentation/InstrProfiling.cpp @@ -137,11 +137,30 @@ // We did not know how many value sites there would be inside // the instrumented function. This is counting the number of instrumented // target value sites to enter it as field in the profile data variable. - for (Function &F : M) + // + // Also create the profile data variable -- do it here because there is no + // guarantee that a counter increment will be ahead of value profile + // instrumentation in IR level instrumentation where the profile data + // variable are needed in the lowering. We only need to see the first + // counter increment instruction to create the variable. This needs + // to be done after counting the number of value sites in this function. + for (Function &F : M) { + InstrProfIncrementInst *FirstProfIncInst = nullptr; + bool hasValueInstrumentation = false; for (BasicBlock &BB : F) - for (auto I = BB.begin(), E = BB.end(); I != E;) - if (auto *Ind = dyn_cast(I++)) + for (auto I = BB.begin(), E = BB.end(); I != E; I++) + if (auto *Ind = dyn_cast(I)) { computeNumValueSiteCounts(Ind); + hasValueInstrumentation = true; + } + else if (FirstProfIncInst == nullptr) + FirstProfIncInst = dyn_cast(I); + + if (hasValueInstrumentation) { + assert (FirstProfIncInst != nullptr); + getOrCreateRegionCounters(FirstProfIncInst); + } + } for (Function &F : M) for (BasicBlock &BB : F)