From Wikipedia:
The genitalia of male flies is rotated to a varying degree from the position found in other insects. In some flies this is a temporary rotation during mating, but in others, it is a permanent torsion of the organs that occurs during the pupal stage. This torsion may lead to the anus being located below the genitals, or, in the case of 360° torsion, to the sperm duct being wrapped around the gut, despite the external organs being in their usual position. When flies mate, the male initially lies on top of the female, facing in the same direction, but then turns round to face in the opposite direction. In some species, this forces the male to lie on its back in order for its genitalia to remain engaged with those of the female, but in most cases, the torsion of the male genitals allows the male to mate while remaining upright.