Index: lib/CodeGen/AsmPrinter/AsmPrinter.cpp =================================================================== --- lib/CodeGen/AsmPrinter/AsmPrinter.cpp +++ lib/CodeGen/AsmPrinter/AsmPrinter.cpp @@ -1148,7 +1148,7 @@ } OutStreamer->AddBlankLine(); - for (const auto &Alias : M.aliases()) { + const auto printAlias = [this, &M](const GlobalAlias &Alias) { MCSymbol *Name = getSymbol(&Alias); if (Alias.hasExternalLinkage() || !MAI->getWeakRefDirective()) @@ -1186,6 +1186,23 @@ OutStreamer->emitELFSize(cast(Name), MCConstantExpr::create(Size, OutContext)); } + }; + // Print aliases in topological order, that is, for each alias a = b, + // b must be printed before a. + // This is because on some targets (e.g. PowerPC) linker expects aliases in + // such an order to generate correct TOC information. + SmallVector AliasStack; + SmallPtrSet AliasVisited; + for (const auto &Alias : M.aliases()) { + for (const GlobalAlias *Cur = &Alias; Cur; + Cur = dyn_cast(Cur->getAliasee())) { + if (!AliasVisited.insert(Cur).second) + break; + AliasStack.push_back(Cur); + } + for (const GlobalAlias *AncestorAlias : reverse(AliasStack)) + printAlias(*AncestorAlias); + AliasStack.clear(); } GCModuleInfo *MI = getAnalysisIfAvailable(); Index: test/CodeGen/Generic/asm-printer-topological-order.ll =================================================================== --- /dev/null +++ test/CodeGen/Generic/asm-printer-topological-order.ll @@ -0,0 +1,15 @@ +; RUN: llc < %s | FileCheck %s + +@TestA = alias void (), void ()* @TestC +@TestB = alias void (), void ()* @TestC +@TestC = alias void (), void ()* @TestD + +define void @TestD() { +entry: + ret void +} + +; CHECK-LABEL: TestD: +; CHECK: TestC = TestD +; CHECK-DAG: TestB = TestC +; CHECK-DAG: TestA = TestC