Differential cross sections are presented for the prompt and non-promptproduction of the hidden-charm states $X(3872)$ and $\psi(2S)$, in the decaymode $J/\psi \pi^+\pi^-$, measured using 11.4 fb$^{-1}$ of $pp$ collisions at$\sqrt{s} = 8$ TeV by the ATLAS detector at the LHC. The ratio ofcross-sections $X(3872)/\psi(2S)$ is also given, separately for prompt andnon-prompt components, as well as the non-prompt fractions of $X(3872)$ and$\psi(2S)$. Assuming independent single effective lifetimes for non-prompt$X(3872)$ and $\psi(2S)$ production gives $R_B = \frac{\mathcal{B}(B\rightarrow X(3872)\textrm{ + any}) \mathcal{B}(X(3872 \rightarrowJ/\psi\pi^+\pi^-)}{\mathcal{B}(B \rightarrow \psi(2S)\textrm{ + any})\mathcal{B}(\psi(2S) \rightarrow J/\psi\pi^+\pi^-)} = (3.95 \pm 0.32\mathrm{(stat)} \pm 0.08\mathrm{(sys)}) \times 10^{-2}$, while separatingshort- and long-lived contributions, assuming that the short-lived component isdue to $B_c$ decays, gives $R_B = (3.57 \pm 0.33\mathrm{(stat)} \pm0.11\mathrm{(sys)}) \times 10^{-2}$, with the fraction of non-prompt $X(3872)$produced via $B_c$ decays for $p_\mathrm{T}(X(3872)) > 10$ GeV being $(25 \pm13\mathrm{(stat)} \pm 2\mathrm{(sys)} \pm 5\mathrm{(spin)})\%$. Thedistributions of the dipion invariant mass in the $X(3872)$ and $\psi(2S)$decays are also measured and compared to theoretical predictions.