That there are forty loaves is something I'd always heard. Thank you for making me realize that I had no idea where it actually comes from.
It gets intricate, so buckle up. I tried to explain it below, but just let me know if I should explain further.
On Menachos 77b, the Gemara derives that any loaf brought must be exactly one tenth-eiphah. It's a long, convoluted exposition, so I'll just quote the bottom line:
תלמוד לומר (ויקרא כג, יז) ממושבותיכם תביאו לחם תנופה שתים שאין תלמוד לומר תביאו ומה תלמוד לומר תביאו שכל מה שאתה מביא ממקום אחר הרי הוא כזה מה להלן עשרון לחלה אף כאן עשרון לחלה אי מה להלן שני עשרונות אף כאן שני עשרונות תלמוד לומר תהיינה למדנו עשרה לחמץ עשרה למצה מנין תלמוד לומר (ויקרא ז, יג) על חלות לחם חמץ נגד חמץ הבא מצה נמצאו עשרים עשרונות לחמי תודה עשרה לחמץ ועשרה למצה
The passuk says (Vayikra 23:17 [regarding the Two Loaves brought on Shavuos]), "From your dwelling places you will bring the bread of waving – two." The passuk does not need to say "you will bring." Why does it say "you will bring"? [To teach] that anything which you bring from another place, it must be like this: just as there, it's one tenth-eiphah per loaf, so, too, here, one tenth-eiphah per loaf. But [maybe we should expound] just as there it [totals] two tenth-eiphahs, so, too, here, two tenth-eiphahs! The passuk says, "they shall be." We have learned ten for the chametz; how do we know ten for the Matzah? The passuk says (Vayikra 7:13), "for loaves of leavened bread" – corresponding to the Chametz, you should bring Matzah. We have found that twenty tenth-eiphas are the loaves of the Todah: ten for the Chametz and ten for the Matzah.
The Gemara (78a) explains the exposition from "they shall be":
אמר רב יצחק בר אבדימי תהיינה כתיב אימא עשרה קפיזי אמר רבא בעשרונות דבר הכתוב
Rav Yitzchak bar Avdimi said, תהיינה is written. Maybe it's ten half-kav [a much smaller amount]? Rava said, the passuk is talking about tenth-eiphahs.
As Rashi explains:
תהיינה - בתרין יודין דחד יו"ד דמייתר אתיא ללחמי תודה:
תהיינה – with two yud's: the extra yud comes for the loaves of the Todah.
The last step is the remaining twenty loaves. The Gemara explains (77b):
יכול עשרה שבמצה לא יהו כולן אלא ממין אחד תלמוד לומר (ויקרא ז, יב) אם על תודה יקריבנו והקריב על זבח התודה חלות מצות בלולות בשמן ורקיקי מצות משחים בשמן סלת מרבכת וגו' נמצאו שלשה עשרונים ושליש לכל מין ומין ושלש חלות לעשרון
I might have thought that the ten Matzah loaves are only from one type; the passuk says (Vayikra 7:12): "If he brings it as a Todah, he will bring for the Todah offering loaves of Matzos kneaded with oil, and cakes of Matzos spread with oil, of poached fine flour." It comes out that there are 3 1/3 tenth-eiphahs for each type, and three loaves per tenth-eiphah.
Thus, as the Gemara concludes:
ונמצאו לחמי תודה ארבעים
It comes out that the Todah loaves are forty.