Is it legal to use someone else's trademark as an advertisement keyword?
It depends on how exactly other's trademark is used in the advertisement. You did not specify the jurisdiction you have in mind, so I will focus on US legislation.
The Lanham Act, 15 U.S. §1114 at (1), sanctions the commercial use, reproduction, imitation, etc. of a registered trademark "[where] such use is likely to cause confusion, or to cause mistake, or to deceive [consumers]". Accordingly, see Rosetta Stone v. Google, 676 F.3d 144, 157, 159 (2012)
What matters is whether the defendant's actual practice is likely to
produce confusion in the minds of consumers about the origin of the
goods or services in question.
[T]rademark infringement creates a likelihood of confusion not only as
to source, but also as to affiliation, connection or sponsorship.
(citations and internal quotation marks omitted).
Rosetta at 153 lists factors for assessing the inquiry of likelihood of confusion. Not all factors are relevant to a trademark infringement dispute, but only those which touch on the parties' role or capacity in the controversy. For instance, Apple would need to prove it used the competitor's trademark to identify that competitor's own goods (rather than to mislead consumers). This is known as nominative use. Other factors that would weigh in a dispute between competitors include the strength of the mark and the similarity of goods/services.
By contrast, controversies involving a search engine entail other different factors because usually a search engine is not a competitor of the trademark owner. In Rosetta the factors to decide on remand were the defendant's intent, actual confusion, and consumer sophistication. Intent is relevant for assessing whether infringement by the search engine was innocent, in which case the remedies would be limited to "an against the presentation of such advertising matter [...] in future transmissions". See 15 U.S. §1114(2)(B).
Could the search engine be held liable if they semantically associated "redmi" with cellphones and showed an iPhone ad to a user searching for "redmi"?
It might, as the previous paragraph implies. But Rosetta, albeit a lengthy opinion, only reviewed summary judgment and therefore gives no hint on the extent to which programs akin to Google's AdWords comply with trademark legislation.
The outline of evidence in Rosetta illustrates how fact-intensive this type of controversies can be.