Hemp cannabinoids may have evolved to deter insect pests
phys.org
phys.org
The same goes for mescaline, cocaine, psilocybin, ibogaine. Also the smelly components found in onion and garlic, for example. The ergot alkaloids from which LSD was first synthesised are from a fungus, a pest that grows on some grasses, so I'm not sure if it's the same.
Tobacco, coffee, cocoa or cannabis for that matter will never have to fear going extinct.
It is rather a "side effect" that came about later.